plotly-dash - Plotly Dash - dcc.Store 回调触发两次

标签 plotly-dash

我遇到了 Plotly Dash 的问题,即由 dcc.Store 组件触发的回调每次触发两次。请参阅下面的代码和示例输出代码,它基于 Dash 文档 ( https://dash.plot.ly/dash-core-components/store ) 中的示例。

任何人都可以解释这一点或建议一种解决方法来防止它?

最小的工作示例代码:

import dash

import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Output, Input, State
from dash.exceptions import PreventUpdate

app = dash.Dash(__name__)

app.layout = html.Div([
    dcc.Store(id='local', storage_type='local'),
    html.Div(html.Button('localStorage', id='local-button')),
    html.Div(0, id='local-clicks'),
])


@app.callback(Output('local', 'data'),
              [Input('local-button', 'n_clicks')],
              [State('local', 'data')])
def on_click(n_clicks, data):
    if n_clicks is None:
        raise PreventUpdate

    app.logger.info(f"Updating data store")

    data = data or {'clicks': 0}

    data['clicks'] = data['clicks'] + 1
    return data


@app.callback(Output('local-clicks', 'children'),
              [Input('local', 'modified_timestamp')],
              [State('local', 'data')]
              )
def on_data(ts, data):
    if ts is None:
        raise PreventUpdate

    app.logger.info(f"New data found! ({ts}, {data})")

    return f"{ts}, {data['clicks']}"


if __name__ == '__main__':
    app.run_server(debug=True, port=8077, threaded=True)

示例输出:
Running on http://127.0.0.1:8077/
Debugger PIN: 597-637-135
New data found! (1584011957193, {'clicks': 24})
New data found! (1584011957193, {'clicks': 24})
Updating data store
New data found! (1584012443177, {'clicks': 25})
New data found! (1584012443177, {'clicks': 25})
Updating data store
New data found! (1584012445159, {'clicks': 26})
New data found! (1584012445159, {'clicks': 26})

最佳答案

我建议将内存存储转换为 session并将第二个回调中的代码更改为以下内容:

def on_data(ts, data):

    if not data or not ts:
        raise PreventUpdate

    ...

这应该解决一些最初的几个循环回调。

关于plotly-dash - Plotly Dash - dcc.Store 回调触发两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60653311/

相关文章:

python - 将输入从一个 Dash DataTable 输入到第二个 Dash DataTable

python - 将 fastapi 与 plotly.dash 结合并将 token 依赖项添加为 auth 的问题

python - 运行 docker 时无法将 'app.server' 解析为属性名称或函数调用

python - 如何在python dash_cytoscape中设置同心圆布局参数?

python - 添加图例并为每个条形添加不同的颜色

python - 如何为 Plotly Dash 回调函数编写测试用例?

python - 回调警告: Callback error creating dash' DataTable

plotly - Python Dash Mapboxgl 多边形点击事件数据,

python - plotly/破折号 : is it possible to hide tick labels of a secondary y axis?

python-3.x - Python 破折号 : Hide a component with one event and make it visible with another created through a callback