Flask send_file:我怎么知道我是否需要 "as_attachment"?

Flask send_file: how do I know if I need "as_attachment"?

Flask 有一个方法可以 return 一个文件:http://flask.pocoo.org/docs/1.0/api/#flask.send_file

有一个名为 as_attachment 的参数,默认值为 False,并且有一个关于它的 handwaavy 声明:"For extra security you probably want to send certain files as attachment (HTML for instance)"

我如何知道我的用例是否 "those certain files"?或者换句话说,这与将其保留为 False 相比有何作用?

您将在同一文档中找到线索,在参数列表的更下方:

as_attachment – set to True if you want to send this file with a Content-Disposition: attachment header.

所以当设置标志时,额外的 header 被添加到响应中,它控制浏览器将如何处理响应。来自 MDN documenation on Content-Disposition:

In a regular HTTP response, the Content-Disposition response header is a header indicating if the content is expected to be displayed inline in the browser, that is, as a Web page or as part of a Web page, or as an attachment, that is downloaded and saved locally.

如果没有显式 Content-Disposition header,来自 Flask 服务器的 text/html 响应将在浏览器中显示为网页。如果您需要将文件保存到磁盘(浏览器会提示您如何处理该文件),那么您需要设置 Content-Disposition: attachment

因此,当您的响应内容类型很可能在浏览器中显示为网页但您希望用户下载它时,请使用 as_attachment=True。如今,除了 HTML,您可能还想为图像、PDF 文件和 XML 设置该标志。