使用Flask和Dash通过rest调用接收数据并更新图表

2024-06-29 00:16:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在实现一个flask应用程序,我希望在它上面有cytoscape图。我还希望通过在flask应用程序上发送RESTAPI调用来动态更新数据,并且cytoscape图形根据数据更新图形

这是我编写的代码,但更新过程很慢,即它接收数据,但数据没有在dash代码上更新

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)

请告诉我一个使用RESTAPI集成数据接收过程并更新图形上数据的解决方案


Tags: pip数据nameimport图形flaskdataserver
1条回答
网友
1楼 · 发布于 2024-06-29 00:16:19

您需要使用回调来更新数据

@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)

相关问题 更多 >