How to link progress bars with a process in Dash Python

Viewed 1004

I am trying to link a process with the progress bar...not finding solution anywhere. The only thing I could find was the below code...but I want to link a background process to the progress bar. Please help.

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

progress = html.Div(
    [
        dcc.Interval(id="progress-interval", n_intervals=0, interval=500),
        dbc.Progress(id="progress"),
    ]
)

@app.callback(
    [Output("progress", "value"), Output("progress", "children")],
    [Input("progress-interval", "n_intervals")],
)
def update_progress(n):
    # check progress of some background process, in this example we'll just
    # use n_intervals constrained to be in 0-100
    progress = min(n % 110, 100)
    # only add text after 5% progress to ensure text isn't squashed too much
    return progress, f"{progress} %" if progress >= 5 else ""
1 Answers

Sharing an example here that I used(for my own reference as well):

import dash_bootstrap_components as dbc
from dash import Input, Output, dcc, html

from app import app

progress = html.Div(
    [
        dbc.Button("click", id='test_button', size="lg"),
        dcc.Interval(id="progress-interval", n_intervals=0, interval=500),
        dbc.Progress(id="progress"),
    ]
)


@app.callback(
    [Output("progress", "value"),
     Output("progress", "label"),
     Output("progress-interval", "disabled")],
    [Input("progress-interval", "disabled"),
     Input("progress-interval", "n_intervals"),
     Input("test_button", "n_clicks")],
)
def update_progress(disable, n, n_clicks):
    # check progress of some background process, in this example we'll just
    # use n_intervals constrained to be in 0-100
    if n_clicks and n_clicks >= 1:
        progress = min(n % 110, 100)
        # only add text after 5% progress to ensure text isn't squashed too much
        if progress == 100:
            return 100, '100%', not disable

        return progress, f"{progress} %" if progress >= 5 else "", False
    else:
        return 0, "", False


app.layout = progress
app.run_server(debug=True, port=8050)

The app code which is imported:

import dash
import flask
import dash_bootstrap_components as dbc

server = flask.Flask('app')
app = dash.Dash('app', server=server,
                external_stylesheets=[dbc.themes.CYBORG, dbc.icons.BOOTSTRAP])

You can add or call the method for background process inside 'if' condition and then return the updated status to progress bar as value and % label.

Similarly, stop the progress bar by making disabled property to True when the background process is completed.

Related