【问题标题】:How do I use Dash Loading with Dash Store?如何在 Dash Store 中使用 Dash 加载?
【发布时间】:2021-02-16 00:59:00
【问题描述】:

我正在编写一个简单的 Dash 页面。我从外部 API 等获取数据并将其放入 dcc.Store。然后,Graphs 会拉取数据并在回调中绘图。我正在尝试实现 dcc.Loading 功能,因为提取数据可能需要一些时间。但是,当 Store 完成工作时,我不知道如何触发加载图表。

下面是一个例子:

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate
import plotly.express as px
import pandas as pd
import time

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div(children=[
    html.H1(children='Hello Dash'),

    html.Div(children='''
        Dash: A web application framework for Python.
    '''),

    dcc.Dropdown(
        id='demo-dropdown',
        options=[
            {'label': 'New York City', 'value': 'NYC'},
            {'label': 'Montreal', 'value': 'MTL'},
            {'label': 'San Francisco', 'value': 'SF'}
        ],
        value='NYC'
    ),

    dcc.Loading(
        id='loading01',
        children=html.Div(id='loading-output')),
    # Store certain values
    dcc.Store(
        id='session',
        storage_type='session'),
])


@app.callback(Output('loading-output', 'children'),
              [Input('session', 'modified_timestamp')],
              [State('session', 'data')])
def loading_graph(ts, store):
    if store is None:
        raise PreventUpdate
    if 'NYC' in store['value']:
        v = 1
    elif 'SF' in store['value']:
        v=2
    else:
        v=3
    return dcc.Graph(
                 id='example-graph',
                 figure={
            'data': [
                {'x': [1, 2, 3], 'y': [4*v, 1*v, 2*v], 'type': 'bar', 'name': 'SF'},
                {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Montréal'},
            ],
            'layout': {
                'title': 'Dash Data Visualization'
            }
        }
             )

@app.callback(Output('session', 'data'),
              [Input('demo-dropdown', 'value')],
              [State('session', 'data')])
def storing(value, store):
    store = store or {}
    store['value'] = value
    time.sleep(3)
    return store


if __name__ == '__main__':
    app.run_server(debug=True)

我想我希望在 Store 取东西时微调器在场。

在此先感谢您的帮助或指点。

【问题讨论】:

    标签: python loading store plotly-dash


    【解决方案1】:

    如果您想在调用storing 回调时显示加载器,它还需要有一个输出到Loading 组件的children 属性。

    您不能有重复的回调输出,因此您可以将回调组合成一个回调。然后,只要组合的回调需要执行,您就可以拥有一个处于活动状态的微调器。

    或者您可以有多个Loading 组件:每个回调函数一个:

    import dash
    import dash_core_components as dcc
    import dash_html_components as html
    from dash.dependencies import Input, Output, State
    from dash.exceptions import PreventUpdate
    import time
    
    external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"]
    
    app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
    
    app.layout = html.Div(
        children=[
            html.H1(children="Hello Dash"),
            html.Div(
                children="""
            Dash: A web application framework for Python.
        """
            ),
            dcc.Dropdown(
                id="demo-dropdown",
                options=[
                    {"label": "New York City", "value": "NYC"},
                    {"label": "Montreal", "value": "MTL"},
                    {"label": "San Francisco", "value": "SF"},
                ],
                value="NYC",
            ),
            dcc.Loading(id="loading01", children=html.Div(id="loading-output1")),
            dcc.Loading(id="loading02", children=html.Div(id="loading-output2")),
            # Store certain values
            dcc.Store(id="session", storage_type="session"),
        ]
    )
    
    
    @app.callback(
        Output("loading-output2", "children"),
        Input("session", "modified_timestamp"),
        State("session", "data"),
        prevent_initial_call=True,
    )
    def loading_graph(ts, store):
        if store is None:
            raise PreventUpdate
        if "NYC" in store["value"]:
            v = 1
        elif "SF" in store["value"]:
            v = 2
        else:
            v = 3
    
        time.sleep(2)
    
        return dcc.Graph(
            id="example-graph",
            figure={
                "data": [
                    {
                        "x": [1, 2, 3],
                        "y": [4 * v, 1 * v, 2 * v],
                        "type": "bar",
                        "name": "SF",
                    },
                    {"x": [1, 2, 3], "y": [2, 4, 5], "type": "bar", "name": u"Montréal"},
                ],
                "layout": {"title": "Dash Data Visualization"},
            },
        )
    
    
    @app.callback(
        Output("session", "data"),
        Output("loading-output1", "children"),
        Input("demo-dropdown", "value"),
        State("session", "data"),
    )
    def storing(value, store):
        time.sleep(2)
        store = store or {}
        store["value"] = value
        return store, ""
    
    
    if __name__ == "__main__":
        app.run_server(debug=True)
    

    【讨论】:

      猜你喜欢
      • 2020-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多