我还没有在网上看到以完全相同的方式提出这个问题,所以我将尝试以基本原则提出这个问题(至少就 Dash 基本原则而言)
我有一个来自互联网的 websocket feed 流数据。我将从中获取数据,有时我会使用这些数据用新数据点更新我的绘图。
我正在尝试使用
@app.callback(Output('graph', 'extendData')]
方法来这样做。
我从这个 Github 存储库中的代码开始。同样的代码也贴在下面:
import dash_extendable_graph as deg
import dash
from dash.dependencies import Input, Output, State
import dash_html_components as html
import dash_core_components as dcc
import random
app = dash.Dash(__name__)
app.scripts.config.serve_locally = True
app.css.config.serve_locally = True
app.layout = html.Div([
deg.ExtendableGraph(
id='extendablegraph_example',
figure=dict(
data=[{'x': [0],
'y': [0],
'mode':'lines+markers'
}],
)
),
dcc.Interval(
id='interval_extendablegraph_update',
interval=1000,
n_intervals=0,
max_intervals=-1),
html.Div(id='output')
])
@app.callback(Output('extendablegraph_example', 'extendData'),
[Input('interval_extendablegraph_update', 'n_intervals')],
[State('extendablegraph_example', 'figure')])
def update_extendData(n_intervals, existing):
x_new = existing['data'][0]['x'][-1] + 1
y_new = random.random()
return [dict(x=[x_new], y=[y_new])], [0], 100
if __name__ == '__main__':
app.run_server(debug=True)
上面的代码只是每 1 秒向图中添加一个新的随机点。它使用间隔对象来这样做。
我试图将它与我的 websocket 代码中的回调函数结合起来,它在回调方法中解析并打印一条消息。如下所示,简化:
def websocket_callback(msg):
#
#
# do some message parsing...
# (for now let's just assume casting to int is all that's needed)
#
new_point = int(msg)
print(f"Just received: {new_point}")
ws = websocket.WebSocketApp(url, on_message=websocket_callback)
wst = threading.Thread(target=ws.run_forever)
wst.daemon = True
wst.start()
while True:
time.sleep(1) # Wait for infinite websocket read
我尝试做的只是将装饰器放在
websocket_callback
方法之上:
counter = 0
@app.callback(Output('extendablegraph_example', 'extendData'),
[Input('interval_extendablegraph_update', 'n_intervals')],
[State('extendablegraph_example', 'figure')])
def update_extendData(n_intervals, existing, msg):
#
#
# do some message parsing...
# (for now let's just assume casting to int is all that's needed)
#
global counter
counter +=1
new_point = int(msg)
return [dict(x=[counter], y=[new_point])], [0], 100
问题在于该函数现在由 websocket 提要和示例中的
Interval
对象调用。
由于很多原因这段代码不起作用,我被困在这里
有没有办法在不需要回调的情况下手动触发
extendData
事件?我正在寻找一种方法来分离这两个部分,websocket 解析部分和图形刷新/更新部分。像这样的东西:
@app.callback(Output('graph', 'extendData'))
def update_graph(new_x, new_y):
return [dict(x=[new_x], y=[new_y])], [0], 1000
counter = 0
def websocket_callback(msg):
#
#
# do some message parsing...
# (for now let's just assume casting to int is all that's needed)
#
global counter
new_point = int(msg)
update_graph(counter, new_point)
counter +=1
这样我就可以在
websocket_callback
中解析我的消息并手动触发图形的刷新。
有没有办法做到这一点?运行上面的代码(适应我的设置)抱怨以下错误消息:
dash.exceptions.CallbackException: Inputs do not match callback definition```
which I'm assuming is because that `app.callback` decorator doesn't understand the two x,y inputs.
So I'm so lost...