在WebSockets中使用破折号 [英] Use Dash with websockets
本文介绍了在WebSockets中使用破折号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用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)
有没有办法在每次收到消息时都触发回调(可能之前将消息存储在数据库中)?
推荐答案
本论坛帖子介绍了一种将WebSocket回调与短划线配合使用的方法:
https://community.plot.ly/t/triggering-callback-from-within-python/23321/6
更新
试过了,效果很好。环境为Windows 10 x64+Python3.7。
要进行测试,请下载.tar.gz
文件并运行python usage.py
。它会抱怨一些缺失的包,安装这些。可能需要在usage.py
中将地址从0.0.0.0
编辑到127.0.0.1
。浏览http://127.0.0.1:5000
查看结果。如果我有更多的时间,我会把这个例子放到GitHub上(如果你让它工作有问题,或者原来的东西丢失了,就用ping通知我)。
这篇关于在WebSockets中使用破折号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文