【问题标题】:Receive data via a rest call using Flask and Dash and update the graphs使用 Flask 和 Dash 通过休息调用接收数据并更新图表
【发布时间】:2021-02-22 12:04:30
【问题描述】:

我正在实现一个烧瓶应用程序,我希望在其上显示 cytoscape 图。我还想通过在烧瓶应用程序上发送一个 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 集成数据接收过程并更新图表上的数据。

【问题讨论】:

  • 有什么更新吗?如果正确,请接受答案,否则如果它没有回答问题,请改写您的问题。不要让问题悬而未决
  • 非常感谢,现在可以使用了。我在 n_clicks 上使用了间隔的概念。
  • 您是说您使用Interval 定期从pkl 文件加载数据吗?我读过使用文件来做这些事情是危险的,使用会话会很方便:有可能吗?

标签: python flask plotly-dash cytoscape


【解决方案1】:

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

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

【讨论】:

  • 在我的用例中,我没有任何可以使用的输入。我只想根据我们在 API 调用中收到的数据在触发 api 调用后立即更新细胞图。
  • 那么你需要一个按钮。此按钮用作回调的输入。当按下时,回调被激活。在回调函数中,您可以进行 api 调用并返回数据。我更新了代码以显示如何使用按钮。
猜你喜欢
  • 2020-03-18
  • 1970-01-01
  • 2018-03-13
  • 2019-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-21
  • 2023-03-18
相关资源
最近更新 更多