Sunday, 3 October 2021

Server Side Caching With Plotly Dash

Below I have a basic dash app where I query some data in a database and put it in a store component on the server. I am scratching my head on how to update the data store on a set interval (server side). In the current configuration below, it updates using the dcc.Interval. When multiple clients are connected, each person triggers their own interval component which very quickly deadlocks the database. What would be the best way to go about triggering the function that outputs the store on a set “server side” interval? I have been using this article as inspiration, but can’t seem to fully wrap my head around how to adapt it.

edit: I have looked in to APScheduler but am unsure how to use this with dcc.Store. This seems to be the best way to go about this (if it is possible).

Any help would be awesome!

app.layout = html.Div([
    html.Button("Query data", id="btn"),dcc.Graph(id='Time-graph',style={'width': '100%', 'height': '900px'}),
    dcc.Store(id="store",storage_type="session"),
    dcc.Interval(
        id='interval-component-Time',
        interval=1 * 8000,  # in milliseconds
        n_intervals=0
    )

])

# Create (server side) cache. Works with any flask caching backend.
cc = CallbackCache(cache=FileSystemCache(cache_dir="../cache"))


@cc.cached_callback(Output("store", "data"), [Trigger("interval-component-Time", "n_intervals")])  # Trigger is like Input, but excluded from args
def query_data():
    channel = pyodbc.connect("...connection string...'")
    Run=pd.read_sql("command ", channel).iloc[0]['Name']
    Event=pd.read_sql("command ", channel).iloc[0]['EventId']
    Lap=pd.read_sql("command ", channel)
    groups = [Run, Event, Lap]
    return groups

@cc.callback(Output("Time-graph", "figure"), [Input("store", "data")])
def update_graph(data):

    ...code to generate figure...

    return fig

cc.register(app)

if __name__ == '__main__':
    app.run_server(debug=True)


from Server Side Caching With Plotly Dash

No comments:

Post a Comment