Dash-Plotly:在页面重新加载时保留下拉选择

Dash-Plotly: keep dropdown selection on page reload

我对 python 的 Web 开发还很陌生,目前正在开发一个破折号应用程序。在应用程序中,有一个下拉菜单供用户 select 图表中显示数据的特定时间间隔。当页面刷新时 selection returns 显然回到默认值。此简化代码显示了下拉设置:

import dash_core_components as dcc

app = dash.Dash(__name__)
app.layout = html.Div(
    dcc.Store('memory-intervals', storage_type='session')
    dcc.Dropdown(
       id='time',
       options=get_intervals(),
       value=Interval.DAY.value,
       multi=False,
    ),
)

我目前的理解是,我可以通过 dash 的 Store 组件将数据存储在浏览器会话中。我设法像这样存储 selection:

@app.callback(
    Output('memory-intervals', 'data'),
    Input('time', 'value'),
)
def select_interval(interval):
    if interval is None:
        raise PreventUpdate

    return interval

所以我卡在了这一点上...如何在页面重新加载后将商店的数据设置为 selection 值?

提前致谢!

我不知道这是否是最好的解决方案,但关于 plotly documentation 我设法这样做了:

@app.callback(
    Output('time', 'value'),
    Output('memory-intervals', 'data'),
    Input('time', 'value'),
    Input('memory-intervals', 'data'),
    Input('memory-intervals', 'modified_timestamp'),
)
def select_interval(dd_interval, memory_interval, timestamp):
    ctx = dash.callback_context
    trigger_id = ctx.triggered[0]["prop_id"].split(".")[0]

    if trigger_id == 'time':
        interval = dd_interval
    elif timestamp == -1 or memory_interval is None:
        interval = Interval.DAY.value
    else:
        interval = memory_interval

    return interval, interval

您可以使用 Dash persistence 功能。

根据文档:

persistence_type ('local', 'session', or 'memory'; default 'local'): Where persisted user changes will be stored:

memory: only kept in memory, reset on page refresh. This is useful for example if you have a tabbed app, that deletes the component when a different tab is active, and you want changes persisted as you switch tabs but not after reloading the app.

local: uses window.localStorage. This is the default, and keeps the data indefinitely within that browser on that computer.

session: uses window.sessionStorage. Like 'local' the data is kept when you reload the page, but cleared when you close the browser or open the app in a new browser tab.

在您的示例中,如果您只需要在重新加载后保留下拉值,而不是在退出浏览器或关闭选项卡后,您可以这样写:

import dash_core_components as dcc

    app = dash.Dash(__name__)
    app.layout = html.Div(
        dcc.Store('memory-intervals', storage_type='session')
        dcc.Dropdown(
           id='time',
           options=get_intervals(),
           value=Interval.DAY.value,
           multi=False,
           persistence = True,
           persistence_type = 'session'
        ),
    )

但是,如果您需要在该计算机上的浏览器中无限期地保留选择,您可以简单地使用 persistence = True 因为'local' 类型是默认值。