Home > Software design >  Python Plotly Dash: How to display different data for the different users?
Python Plotly Dash: How to display different data for the different users?

Time:10-08

I use the PostgreSQL query as a data source for the Plotly Dash Dashboard. At the beginning of the query, I define UserID by a v_user parameter and get data only for that user and from this data, I build a dashboard.

import psycopg2
import pandas as pd
import plotly.express as px
import dash
import dash_core_components as dcc
import dash_html_components as html

v_user=111

conn = psycopg2.connect(host="xxxx", port = 5432, database="xxxxx", user="xxxxx", password="xxxxx")
statment= f""" select  month, count(id) as sales from public.orders where user_profile_id={v_user} group by 1"""
df_orders= pd.read_sql_query(statment ,con=conn)
df_orders

app = dash.Dash()

fig = px.bar(df_orders, x="month", y="sales")

app.layout = html.Div([
     html.H1('Sales by Users'),
     html.Div([dcc.Graph(figure=fig)])
])

if __name__ == '__main__':
    app.run_server(debug=True, use_reloader=False)

enter image description here

The goal is to display only data for each user, which means I need to change the v_user parameter even before the SQL query. That means the user "111" sees data only for it, and user "222" only for it. How to do it? Or maybe there is another way to filter and display different data for each user ??

CodePudding user response:

In dash you have what is call callback function that get input and output parameters in your case you need to add a way to select a user id and pass it on to the callback function

import psycopg2
import pandas as pd
import plotly.express as px
import dash
import dash_core_components as dcc
import dash_html_components as html

v_user=111

conn = psycopg2.connect(host="xxxx", port = 5432, database="xxxxx", user="xxxxx", password="xxxxx")
statment= f""" select  month, count(id) as sales from public.orders where user_profile_id={v_user} group by 1"""
df_orders= pd.read_sql_query(statment ,con=conn)
df_orders

app = dash.Dash()

fig = px.bar(df_orders, x="month", y="sales")

app.layout = html.Div([
     html.H1('Sales by Users'),
     html.Div([dcc.Graph(id='graph_1', figure=fig)])
])

if __name__ == '__main__':
    app.run_server(debug=True, use_reloader=False)

@app.callback(
    Output(component_id="graph_1", component_property="figure"),
    [Input(component_id="{add the component that hold the user id}", component_property='value')]
)
def update_dates(user_id):
    conn = psycopg2.connect(host="xxxx", port = 5432, database="xxxxx", 
    user="xxxxx", password="xxxxx")
    statment= f""" select  month, count(id) as sales from public.orders where 
    user_profile_id={user_id} group by 1"""
    df_orders= pd.read_sql_query(statment ,con=conn)
    return px.bar(df_orders, x="month", y="sales")

you need to understand where is your user id and when it change

  • Related