[英]Flask proxy response for file download
I am using a Flask route as a proxy to download a file, like this:我使用 Flask 路由作为代理下载文件,如下所示:
@esa_handler.route("/data/<int:series>/<int:file_num>", methods=["GET"])
def DownloadRemote(series, file_num):
"""
Downloads the remote files from the ESA.
:param series: 0-20.
:param file_num: File within the series, 0-255
:return: Compressed CSV file.
"""
# if the file is bad.
if series >= 20 and file_num > 110:
return jsonify({"error": "file does not exist."})
url = "http://cdn.gea.esac.esa.int/Gaia/gaia_source/csv/GaiaSource_000-{:03d}-{:03d}.csv.gz".format(series,
file_num)
req = requests.get(url, stream=True)
return Response(stream_with_context(req.iter_content(chunk_size=2048)), content_type=req.headers["content-type"])
It works fine, however, the filename that is presented to the client is whatever the file number that is passed to the endpoint.它工作正常,但是,呈现给客户端的文件名是传递给端点的任何文件号。 For example, if I put http://127.0.0.1:5000/esa/data/0/0
to download the very first file, it downloads, but Chrome/Firefox/IE/Edge are offering to save the file with a filename as "0".例如,如果我将http://127.0.0.1:5000/esa/data/0/0
用于下载第一个文件,它会下载,但 Chrome/Firefox/IE/Edge 提供使用文件名保存文件作为“0”。 While there is nothing wrong with that, I would like a better user experience.虽然这没有错,但我想要更好的用户体验。
How can I intercept the response to proffer a filename based off the URL requested?如何拦截响应以根据请求的 URL 提供文件名?
This can be done with the Content-Disposition
HTTP header.这可以通过Content-Disposition
HTTP 标头来完成。 Here you can specify a filename for the newly downloaded file.您可以在此处为新下载的文件指定文件名。
This can be added to a FlaskResponse
as follows:这可以添加到 FlaskResponse
,如下所示:
url = "http://cdn.gea.esac.esa.int/Gaia/gaia_source/csv/GaiaSource_000-{:03d}-{:03d}.csv.gz".format(series,
req = requests.get(url, stream=True)
headers = Headers()
headers .add('Content-Type', req.headers["content-type"])
headers .add('Content-Disposition', 'attachment; filename="filename.txt"')
return Response(stream_with_context(req.iter_content(chunk_size=2048)), headers=headers)
Note: The Content-Type
was moved into headers
for simplicity注意:为简单起见, Content-Type
被移到headers
中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.