How to download file using data from another callback

I’d like to do an ‘expensive’ calculation, and then download the data as a csv file. The csv file is too long to pass the data as an href. How can I do this? Here’s a working example, I’d like some way to get access to the dataframe ‘df’ that is calculated inside update() and download it as a csv.

import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import numpy as np
import flask
import io


from dash.dependencies import Input, Output, State
# import plotly.graph_objs as go

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div([
    html.Button('Calculate',id='calculate'),
    html.A('download',href='download_csv'),
    dcc.Store(id='data_store',storage_type='memory'),
])


# Calculate the data and store it.
@app.callback(
    Output('data_store', 'data'),
    [Input('calculate', 'n_clicks')])
def update(n_clicks):
    print('Running expensive calculation...')

    # This is the data we want to download:
    d = {'col1': np.array(range(1000))}
    df = pd.DataFrame.from_dict(d)
    return df.to_json()

@app.server.route('/download_csv/')
def download_excel():

    # --------------------------------------------------------------------
    # ** How do I get access to 'df' that is calculated in update()???
    # --------------------------------------------------------------------

    # Dummy dataframe for downloading.
    d = {'col1': [1, 2], 'col2': [3, 4]}
    df = pd.DataFrame(data=d)

    #Convert DF
    str_io = io.StringIO()
    df.to_csv(str_io, sep=",")

    mem = io.BytesIO()
    mem.write(str_io.getvalue().encode('utf-8'))
    mem.seek(0)
    str_io.close()

    return flask.send_file(mem,
					   mimetype='text/csv',
					   attachment_filename='downloadFile.csv',
					   as_attachment=True)


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

Hi, you can save your dataframe to db (redis) or file system using each session_id as the key or file_name. :slightly_smiling_face:

Have you solved this issue?I am stuck in the similar case. If you have already solved this can you please help me with this?