Flask has a method to return a file: http://flask.pocoo.org/docs/1.0/api/#flask.send_file
There is a parameter called as_attachment
with a default of False, and there is a handwaavy statement about it: "For extra security you probably want to send certain files as attachment (HTML for instance)"
How do I know if my use case is "those certain files"? Or alternatively stated, what does this do as opposed to leaving this as False?
You'll find a clue in the same documentation, further down in the parameter list:
as_attachment
– set toTrue
if you want to send this file with aContent-Disposition: attachment
header.
So when the flag is set, an extra header is added to the response, which controls how the browser will handle the response. From the 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.
Without an explicit Content-Disposition
header, a text/html
response from your Flask server will be shown as a web page in the browser. If you needed the file to be saved to disk instead (the browser prompting you what to do with the file), then you need to have a Content-Disposition: attachment
set.
So when your response content type is likely to be shown in the browser as a web page but you want the user to download it instead, use as_attachment=True
. These days, in addition to HTML, you probably want to set that flag for images, PDF files, and XML as well.