绘制破折号回调到具有不同输入功能的一个输出

问题描述 投票:0回答:1

我是 Plotly Dash 的新手,想为以下应用程序设计一个破折号,但找不到如何解决我面临的问题。

场景如下:我有一个包含以下列的 SQL 表:'date' (datetime)、'type' (varchar)、'item' (varchar)、'item-group' (varchar)、'county' (varchar) )和“值”(浮点数)。在我的仪表板中,我希望用户能够选择“日期”、“类型”、“项目组”和“国家/地区”的任意组合。根据他们的选择,我的目标是在 Dash 中将相应的数据框显示为表格(使用任何形式的表格可视化)。

但是,SQL 查询运行速度明显缓慢。我想获取仅以“日期”为条件的数据。这样,我需要重新运行查询的唯一时间是当用户更改默认时间范围时,这种情况非常罕见(与用户更改非常频繁的“item-group”和“county”相反,因此,我不想重新查询他们。我想为他们所有人提供它)。

这是我的挑战:我想优化仪表板,以便仅在用户更改日期范围时重新运行 SQL 查询。对于其他用户选择,我打算使用 pandas 过滤而不重新查询 SQL 数据库。我遇到的问题是设置回调。我正在努力区分回调触发器,以便当用户更改日期范围时,我触发重新查询,而对于其他选择,我利用 pandas 过滤而不重新查询数据库。我尝试使用相同的输出(表)进行多个回调,但它显示了一个错误。下面显示了一种低效的方法,每次更改后我都会重新查询。你能帮我实现我想要的功能吗?

@app.callback(
    Output('table', 'data'),
    [Input('date-range-picker', 'start_date'),
    Input('date-range-picker', 'end_date'),
    Input('type-dropdown', 'value'),
    Input('item-dropdown', 'value'),
    Input('item-group-dropdown', 'value'),
    Input('county-dropdown', 'value')],
)
def update_plots_uncertainty(start_date, end_date, selected_tpye, selected_item, selected_time_group, selected_counties):
    df = pd.read_sql(f"SELECT * FROM t WHERE [date] BETWEEN {start_date} AND {end_date}")
    if selected_tpye:
        df = df[df['type'] == selected_type]
    if selected_item:
        df = df[df['item'] == selected_item]
    if selected_item_group:
        df = df[df['item_group'] == selected_item_group]
    if selected_counties:
        df = df[df['counties'].isin(selected_counties)]
    return df.to_dict('record')
sql python-3.x visualization plotly-dash
1个回答
0
投票

您可以使用

context
确定回调的输入源。有关更多信息,请参见此处:https://dash.plotly.com/defining-which-callback-input-changed

from dash import ctx

@app.callback(
    Output('table', 'data'),
    [Input('date-range-picker', 'start_date'),
    Input('date-range-picker', 'end_date'),
    Input('type-dropdown', 'value'),
    Input('item-dropdown', 'value'),
    Input('item-group-dropdown', 'value'),
    Input('county-dropdown', 'value')],
)
def update_plots_uncertainty(start_date, end_date, selected_tpye, selected_item, selected_time_group, selected_counties):
    context = ctx.triggered_id
    if context == "date-range-picker":
        # SQL query here
    else:
       # Pandas query here
© www.soinside.com 2019 - 2024. All rights reserved.