1

Currently, I have a dashboard that allows users to export queried data in xlsx/csv format but the file generated is stuck with data that is first queried by the first user. If another user queries his/her own data and tries to export, he/she would open the downloaded file and see the data queried by the first user in another instance.

I believe this is due the global variable “queried_df” shown below in my code snippet. Is there a better way to share/send data from the callback to the server route export?

Any other suggestions are appreciated, thank you!

@app.callback(
    Output('tables', 'children'),
    [Input("bom_1", "value"),
     Input("bom_2", "value"),
     Input("org_1", "value"),
     Input("org_2", "value"),
     Input("level", "value"),
     Input('button', 'n_clicks')]
)
def update_tables(bom_1, bom_2, org_1, org_2, level, n_clicks):

    global queried_df

    if n_clicks == 0:
        return dash.no_update

    queried_df = bc.compare(bom_1, org_1, bom_2, org_2, level)

    # perform other actions

    return table


@app.server.route('/export/')
def download_excel():
    strIO = io.BytesIO()
    writer = pd.ExcelWriter(strIO, engine="xlsxwriter")
    left = queried_df[0]
    left.to_excel(writer, sheet_name='Sheet1', startrow=1)

    excel_data = strIO.getvalue()
    strIO.seek(0)

    return send_file(strIO, attachment_filename='test.xlsx', as_attachment=True)
jko0401
  • 47
  • 7

2 Answers2

1

Keeping users independent of each other is the sort of thing flask sessions can help with. Try:

from flask import session

and read up on the documentation here: https://flask.palletsprojects.com/en/1.1.x/quickstart/#sessions

jcklopp
  • 451
  • 5
  • 9
0

Turns out, send_file() would send the file held in cache. specifying cache_timeout=0 tells it to hold for 0 seconds. So, the solution would be:

return send_file(filename, as_attachment=True, cache_timeout=0)

Here is the original solution:

Flask send_file is sending old file instead of newest

jko0401
  • 47
  • 7