将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
尝试过,效果很好。
要进行测试,请下载.tar.gz
文件并运行python usage.py
。它将抱怨某些缺少的软件包,请安装它们。可能必须在0.0.0.0
中将地址从127.0.0.1
修改为usage.py
。浏览至http://127.0.0.1:5000
以查看结果。如果我有更多的时间,可以将这个示例放在GitHub上(如果您无法正常使用它,或者原始文档迷路了,请ping我)。