簡體   English   中英

Python Plotly Dash:如何為不同的用戶顯示不同的數據?

[英]Python Plotly Dash: How to display different data for the different users?

我使用 PostgreSQL 查詢作為 Plotly Dash 儀表板的數據源。 在查詢開始時,我通過 v_user 參數定義 UserID 並僅為該用戶獲取數據,並根據這些數據構建一個儀表板。

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)

在此處輸入圖像描述

目標是只顯示每個用戶的數據,這意味着我需要在 SQL 查詢之前更改 v_user 參數。 這意味着用戶“111”只能看到它的數據,用戶“222”只能看到它的數據。 怎么做? 或者也許還有另一種方法可以為每個用戶過濾和顯示不同的數據?

在破折號中你有什么是調用回調 function 獲取輸入和 output 參數在你的情況下你需要添加一個方法到 select 一個用戶 ID 並將它傳遞給回調 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")

您需要了解您的用戶 ID 在哪里以及何時更改

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM