How to run code after Flask send_file () or send_from_directory ()

I have a Flask-based site where users can upload some PDF files.

This can be implemented using Flask send_file() and send_from_directory() .

For example:

 @app.route('/downloadreport') def download_report(): return send_from_directory( '/reports', 'my_report.pdf', as_attachment=True) 

I would like to execute some logic (let it call it after_download() ) AFTER the download is complete .

I tried using @after_this_request . But it seems that send_file() works asynchronously, so @after_this_request can be run before the file is uploaded.

  • For example, if the file is very large, downloading may take some time, so @after_this_request seems to work when the file is being downloaded.
  • What the documentation looks like, for example send_file() , uses a WSGI file to execute the download ... maybe why it works asynchronously?

Is there a way to call after_download() so that it is guaranteed to work after send_file() finished sending the file to the user?

+7
python flask werkzeug download
source share
1 answer

You can not. While send_file transfers the file using Flask when using the dev server, it can (and really should for performance) use the web server (nginx, apache, etc.) AND X-SendFile during production. Since the web server is out of control of the application, you are out of luck.

+4
source share

All Articles