How to share data from a Flask route to a Dash callback

Viewed 835

I programmed a Flask route (let's say '/post_data') to receive data from a remote sensor through a POST request.

I'd like to show that data with Dash with some dropdown to customize the graph responsively and that updates automatically when new data arrives at the Flask route.

import dash
import flask


app = dash.Dash(__name__)
app.layout = [
   # ... some  dash_core_components ...
   dcc.Graph(id='mygraph'),
]
server = app.server

@server.route('/post_data', methods=['GET', 'POST'])
def post_data():
    if request.method == 'POST':
        data = eval(request.data.decode('utf8'))


@app.callback(
    [Output('mygraph', 'figure')],
    [Input('mydropdown1', 'value'), ...],
)
def update_mygraph(mydropdown1_value, ...):
    # QUESTION: how to get data from post_data?
    # some elaboration on data based on dropdown values
    fig = px.scatter(data, x="x", y="y")
    return fig


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

What I don't understand is: how to share the data from the Flask route with the Dash callback?

Should I store the dataset in the Flask session? Is then possible to fetch the dataset from the session in the dash callback? How?

1 Answers

Only approaches that come into my mind are:

  1. Write all data into a file and then access the file from the callback.
  2. Save all data into a database and then access the db from the callback.
  3. Maybe you could pass the data as url params. On the callback you could access the flask session, maybe. This one is just a conjecture.

An alternative solution could be just to insert the data on the same dashboard... Upload Component

Related