following the guide from “Long Callbacks | Dash for Python Documentation | Plotly” I made code like bellow,
I’ve modified the variable of an external object in a background callback,
However, when I check the variable of the external object in subsequent callbacks, it doesn’t seem to be updated.
It seems like the screen is refreshed after the callback finishes, which might be the reason I’m unable to retrieve the updated value of the temp variable.
The temp
variable represents a large object data, so it’s crucial to process it on the server side.
import dash_bootstrap_components as dbc
from dash import Dash, DiskcacheManager, Input, Output, html, callback
# Diskcache for non-production apps when developing locally
import diskcache
cache = diskcache.Cache("./cache")
background_callback_manager = DiskcacheManager(cache)
app = Dash(__name__, background_callback_manager=background_callback_manager)
temp = False
app.layout = html.Div(
[
html.Div(
[
html.P(id="backgroundCallbackResult"),
dbc.Progress(id="progress_bar", color="infov", value="0"),
]
),
html.Button(id="button_id", children="Run Job!"),
html.Button(id="cancel_button_id", children="Cancel Running Job!"),
html.P(id="anotherCallbackResult"),
]
)
@callback(
output=Output("backgroundCallbackResult", "children"),
inputs=Input("button_id", "n_clicks"),
background=True,
running=[
(Output("button_id", "disabled"), True, False),
(Output("cancel_button_id", "disabled"), False, True),
(
Output("backgroundCallbackResult", "style"),
{"visibility": "hidden"},
{"visibility": "visible"},
),
(
Output("progress_bar", "style"),
{"visibility": "visible"},
{"visibility": "hidden"},
),
],
cancel=Input("cancel_button_id", "n_clicks"),
progress=[Output("progress_bar", "value"), Output("progress_bar", "max"), Output("progress_bar", "label")],
prevent_initial_call=True
)
def update_progress(set_progress, n_clicks):
total = 100
for i in range(total + 1):
set_progress((str(i), str(total), f"{i} %" if i >= 5 else ""))
temp =True
return f"backgroundCallbackResult: {temp}"
@callback(
output=Output("anotherCallbackResult", "children"),
inputs=Input("backgroundCallbackResult", "children"),
prevent_initial_call=True
)
def check_result(children):
return f"anotherCallbackResult: {temp}"
if __name__ == "__main__":
app.run_server(debug=True, host="0.0.0.0")