Dash Callback Python

Can someone help me what is wrong here? I just want to update the graph in every 3 seconds to pull data from database. (Meaning that data is changing in the database)

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div(html.Div([
        dcc.Interval(id='interval1', interval=3 * 1000, n_intervals=0),
        html.Div(className='graphs', children=[
        dcc.Graph(id='live-graph', animate=False,
                  style={'height': 450, 'width': '70%', 'display': 'blocl', '`overflowY`': 'scroll',
                         'margin-top': 35})])]))

@app.callback(Output('live-graph', 'figure'),
              [Input('interval1', 'n_intervals')])
def bar_graph():
    conn = sqlite3.connect('database.db')
    c = conn.cursor()
    df = pd.read_sql('SELECT * FROM hey ORDER BY id DESC, date DESC LIMIT 300', conn)
    df.set_index('date', inplace=True)
    X = df.index
    Y = df.volume.values
    fig = px.line(df, x=X, y=Y).add_bar(x=X, y=Y).update_layout(showlegend=False)
    return fig

Hi @sesop and welcome to the community!

Your callback function is missing an argument. The arguments to the function should match the number of inputs to your callback.

Like this:

@app.callback(Output('live-graph', 'figure'),
              [Input('interval1', 'n_intervals')])
def bar_graph(n):

Hi @atharvakatre,
That was a great answer! Thanks a lot! I just found out that by giving an argument to the function solved the issue. So, does it matter that argument is related to the callback or whether I will use the argument or not?


The callback is triggered whenever an action takes place for the input component (eg button click, value selection, etc).
In your case the input component - dcc.Interval is triggered automatically after every set interval.

The logic for what happens after the input is triggered is written inside the callback function which takes the exact same number of arguments as the number of input statements written in your @app.callback decorator and return the exact number of outputs as per the outputs in your decorator.

Check out this chapter from the docs for detailed info - Basic Callbacks | Dash for Python Documentation | Plotly

I’ve already checked that docs. The things I was asking is I don’t use the argument (n_intervals) anywhere in the function. So that argument might be any name, so what is the point of using that?

@app.callback(Output('pie-chart', 'figure'), [Input('pie-update', 'n_intervals')])
def pie_sentiment(n_intervals):
    fig = px.pie(values=[1, 2])
    return fig

Yes, the argument can be any name and though it isn’t used anywhere in the function it is still required to be passed as an argument. That’s just how the dash callback function needs it to be :neutral_face:

1 Like

Thanks a lot for your time! :heart:

1 Like