如何通过 Dash Store 使用 Dash 加载?

问题描述 投票:0回答:2

我正在编写一个简单的 Dash 页面。我从外部 API 等获取数据并将其放入 dcc.Store 中。然后,图表会提取数据并在回调中进行绘图。 我正在尝试实现 dcc.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 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)

我想我希望商店取东西时旋转器在场。

预先感谢您的任何帮助或指点。

python loading store plotly-dash
2个回答
3
投票

如果您想在调用

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)

0
投票

您可以将

dcc.Store
嵌套在
dcc.Loading
元素内:

dcc.Loading(
    children=[
        html.Div(id="loading-output1"),
        dcc.Store(id="my-store", storage_type="session"),
    ]
)

然后,每当回调正在更新时,微调器就会显示

my-store

© www.soinside.com 2019 - 2024. All rights reserved.