Flask send_file()或send_from_directory()之后如何运行代码 [英] How to run code after Flask send_file() or send_from_directory()

查看:161
本文介绍了Flask send_file()或send_from_directory()之后如何运行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

使用Flask的 send_file() send_from_directory()

This is straightforward to implement using Flask's send_file() and send_from_directory().

例如:

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

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

I'd like to perform some logic (let's call it after_download()) AFTER the download is complete.

我尝试使用 @after_this_request 挂钩。但是看起来 send_file()是异步运行的,因此 @after_this_request 可能会在文件下载前启动。

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.


  • 例如,如果文件很大,则下载可能需要一段时间,因此 @after_this_request

  • 它从文档(例如 send_file())使用WSGI的文件包装程序来实现下载...也许这就是为什么它异步运行?

  • 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?

是否可以调用 after_download(),这样可以保证在 send_file() 已完成将文件发送给用户?

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?

推荐答案

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

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.

这篇关于Flask send_file()或send_from_directory()之后如何运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆