简体   繁体   中英

Update application state outside of callback in plotly dash

I'm writing a plotly Dash application where I don't initially have database access, so I need to wait for the database connection before I can set the initial application state.

Thus, I want to run a function that will set the application state later on, but the only way to set state seems to be with @app.callback() decorators, but the problem is they require a property or state variable to watch before firing, but in my case I'm not watching part of the Dash app, I'm watching something external.

How can I do this in Dash?

For example:

app = Dash(routes_pathname_prefix='/dash/trend/')

app.layout = html.Div(children=[
    dcc.Dropdown(
        options=get_field_options(),
        id='field_select',
        multi=True,
    )
])

@app.callback(
    dash.dependencies.Output('field_select', 'options'),
    [
         # What do I put here as an input??
    ]
)
def update_fields(href):
    return get_field_options()

You can use plotly dash store component to keep some data needed for event.

dcc.Store(id='local', storage_type='local'),

Dash Store component

Use a hidden html.Div() to store your information. This can be empty:

html.Div(id='application-state', style={'display': 'none'})

So your code should look like this:

import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output

app = Dash(routes_pathname_prefix='/dash/trend/')

app.layout = html.Div(children=[
    dcc.Dropdown(
        options=get_field_options(),
        id='field_select',
        multi=True,
    ),
    html.Div(id='application-state', style={'display': 'none'})

])

@app.callback(
    [Output('field_select', 'options')],
    [Input('application-state', 'children')])
def update_fields(href):
    if href =! None:
       return get_field_options()
    else:
       return []

Your external part should update the respective hidden div. You can change this to any other component that is able to store the information you want to transfer to the dash visualization. You find the best sources and tricks for this problem domain here .

The if else part for returning a valid object is a bit tricky. Please let me know if there is a callback output error like Expected 1 output but received None or something similar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM