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

2022-04-19 00:00:00 python flask plotly-dash cytoscape

问题描述

我正在实现一个FASK应用程序,我希望在该应用程序上有细胞景观图。我还希望通过在FlaskTM应用程序上发送REST API调用来动态更新数据,并且根据数据,细胞图更新图表。

这是我为执行此操作而编写的代码,但更新过程很慢,即它接收数据,但该数据不会在破折号代码上更新。

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)

相关文章