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

心不动则不痛 提交于 2020-01-13 08:25:09

问题


I have a Flask-based website where users can download some PDF files.

This is straightforward to implement using Flask's 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'd like to perform some logic (let's call it after_download()) AFTER the download is complete.

I've tried using the @after_this_request hook. But it looks like send_file() runs asynchronously so @after_this_request may fire before the file is downloaded.

  • For example, if the file is very large, a download may take a while so @after_this_request seems to fire while the file is being downloaded.
  • It looks from the documentation like send_file() uses WSGI's file wrapper to effectuate the download...maybe that's why it's running asynchronously?

Is there a way to call after_download() so that it's guaranteed to run after send_file() has completed sending the file to a user?


回答1:


You can't. While send_file streams the file using Flask when using the dev server, it may (and really should for performance) use the web server (nginx, apache, etc.) and X-SendFile in production. Since the web server is beyond the control of the application, you're out of luck.



来源:https://stackoverflow.com/questions/29192132/how-to-run-code-after-flask-send-file-or-send-from-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!