plotly-dash - Plotly Dash - dcc.Store 回调触发两次
问题描述
我在使用 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
...
这应该解决前几个循环回调中的一些问题。
推荐阅读
- javascript - 如何从 html 页面调用在 javascript 模块 (type=module) 中声明的函数
- python - 气流:将 BashOperartor 作为字符串返回,用于 odbc 连接
- java - 根据具有 @joinColumn 注释的列上的 where 条件在休眠中选择查询
- javascript - 带有ajax响应表单php的尾随html
- jsp - tld 文件无效,但其文件名
- javascript - 如何从 Javascript 中的 REST api 调用中删除 HTTP 标头
- amazon-web-services - 当我使用 s3 presign url upload 上传文件时,AWS lambda 触发器不起作用
- matlab - 为matlab曲线拟合添加归一化系数的约束
- ios - AVPlayer 不通过蓝牙耳机输出音频
- mongodb - 我无法连接到我在 docker compose 中运行的 MongoDB