使用 Dash 和 Websockets 构建实时仪表板的最佳方法是什么?我想在每次收到消息时更新图表,但我发现的唯一事情是每 x 秒调用一次回调,如下例所示。
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_daq as daq
from dash.dependencies import Input, Output
import plotly
import plotly.graph_objs as go
from websocket import create_connection
from tinydb import TinyDB, Query
import json
import ssl
# Setting up the websocket and the necessary web handles
ws = create_connection(address, sslopt={"cert_reqs": ssl.CERT_NONE})
app = dash.Dash(__name__)
app.layout = html.Div(
[
dcc.Graph(id='live-graph', animate=True),
dcc.Interval(
id='graph-update',
interval=1*1000,
n_intervals=0)
]
)
@app.callback(Output('live-graph', 'figure'),
[Input('graph-update', 'n_intervals')])
def update_graph_live(n):
message = ws.recv()
x=message.get('data1')
y=message.get('data2')
.....
fig = go.Figure(
data = [go.Bar(x=x,y=y)],
layout=go.Layout(
title=go.layout.Title(text="Bar Chart")
)
)
)
return fig
if __name__ == '__main__':
app.run_server(debug=True)
有没有办法在每次收到消息时触发回调(可能之前将它们存储在数据库中)?
最佳答案
这个论坛帖子描述了一种在 Dash 中使用 websocket 回调的方法:
https://community.plot.ly/t/triggering-callback-from-within-python/23321/6
更新
试过了,效果很好。环境为 Windows 10 x64 + Python 3.7。
要进行测试,请下载 .tar.gz
文件并运行 python usage.py
.它会提示一些丢失的包,安装这些。可能需要编辑来自 0.0.0.0
的地址至 127.0.0.1
在 usage.py
.浏览到 http://127.0.0.1:5000
查看结果。如果我有更多时间,我会把这个例子放在 GitHub 上(如果你在让它工作时遇到问题,或者原始文件丢失,请联系我)。
关于websocket - 将 Dash 与 websockets 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57860270/