【问题标题】:How to run code after Flask send_file() or send_from_directory()如何在 Flask send_file() 或 send_from_directory() 之后运行代码
【发布时间】:2015-05-25 08:58:01
【问题描述】:

我有一个基于 Flask 的网站,用户可以在其中下载一些 PDF 文件。

使用 Flask 的 send_file()send_from_directory() 很容易实现。

例如:

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

我想执行一些逻辑(我们称之为after_download()下载完成后

我试过使用@after_this_request 钩子。但看起来send_file() 是异步运行的,所以@after_this_request 可能会在文件下载之前触发。

  • 例如,如果文件非常大,下载可能需要一段时间,因此在下载文件时@after_this_request 似乎会触发。
  • the documentation 看来,send_file() 使用 WSGI 的文件包装器来实现下载...也许这就是它异步运行的原因?

有没有办法调用after_download() 以保证在send_file() 完成将文件发送给用户之后运行?

【问题讨论】:

    标签: python download flask werkzeug


    【解决方案1】:

    你不能。虽然send_file 在使用开发服务器时使用 Flask 流式传输文件,但它可能(并且确实应该为了性能)在生产中使用 Web 服务器(nginx、apache 等)和X-SendFile。由于 Web 服务器超出了应用程序的控制范围,因此您很不走运。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-11
      • 1970-01-01
      • 1970-01-01
      • 2020-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多