将 Dash 与 websockets 结合使用

Sag*_*aro 5 real-time callback websocket plotly plotly-dash

使用 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)
Run Code Online (Sandbox Code Playgroud)

有没有办法在每次收到消息时触发回调(可能之前将它们存储在数据库中)?

Con*_*ngo 0

这篇论坛帖子描述了一种在 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。它会抱怨缺少一些软件包,安装它们。可能需要编辑地址 from0.0.0.0127.0.0.1in usage.py。浏览http://127.0.0.1:5000查看结果。如果我有更多时间,我会将这个示例放在 GitHub 上(如果您在使其正常工作时遇到问题,或者原始示例丢失,请联系我)。