如何解决使用 Flask 和 Dash 通过休息调用接收数据并更新图表
我正在实施一个烧瓶应用程序,我希望在其上显示细胞景观图。我还想通过在烧瓶应用程序上发送一个 rest API 调用来动态更新数据,并根据数据 cytoscape 图更新图。
这是我为此编写的代码,但更新过程很慢,即它接收数据但数据未在破折号代码上更新。
import dash # pip install dash
import dash_cytoscape as cyto # pip install dash-cytoscape==0.2.0 or higher
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Output,Input
import pandas as pd # pip install pandas
import plotly.express as px
import requests
from flask import Flask,request
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
server = Flask(__name__)
app1 = dash.Dash(__name__,server=server,external_stylesheets=external_stylesheets)
@server.route('/data',methods=['POST'])
def query_example():
global data_out
data = request.get_data()
data = (literal_eval(data.decode('utf8')))["data"]
print("Data Received")
with open('topology_data.pkl','wb') as f:
pickle.dump(data,f)
return {"Data":True}
with open('topology_data.pkl','rb') as f:
data_out = pickle.load(f)
app1.layout = html.Div([
html.Div([
cyto.Cytoscape(
id='org-chart',layout={'name': 'breadthfirst'},style={'width': '100%','height': '500px'},elements=data_out,stylesheet=[
# Group selectors
{
'selector': 'node','style': {
'content': 'data(label)','background-color': 'green','line-color': 'green'
}
},{
'selector': 'edge','style': {
'background-color': 'green','line-color': 'green','label': 'data(label)'
}
},{
'selector': '[weight = 1]','style': {
'line-color': 'red'
}
}
]
)
],className='six columns'),],className='row')
if __name__ == '__main__':
app1.run_server(debug=True)
请告诉我使用 REST API 集成数据接收过程并更新图表数据的解决方案。
解决方法
您需要使用回调来更新数据。
@app.callback(Output('org-chart','elements'),[Input("button","n_clicks")],def update_data(nclicks):
"""Retrieves data from api call
Parameters
----------
nclicks : int | None
The number of times the button was pressed.
Used to prevent initial update with empty state.
"""
if nclicks in [0,None]:
raise PreventUpdate
else:
data = api_call()
return data
您可以在 https://dash.plotly.com/cytoscape/callbacks 的“添加和删除元素”下找到更多详细信息和示例
你当然需要在你的应用布局中添加一个按钮
html.Button('Make api call',id='button',n_clicks=0)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。