繁体   English   中英

文件下载的 Flask 代理响应

[英]Flask proxy response for file download

我使用 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"])

它工作正常,但是,呈现给客户端的文件名是传递给端点的任何文件号。 例如,如果我将http://127.0.0.1:5000/esa/data/0/0用于下载第一个文件,它会下载,但 Chrome/Firefox/IE/Edge 提供使用文件名保存文件作为“0”。 虽然这没有错,但我想要更好的用户体验。

如何拦截响应以根据请求的 URL 提供文件名?

这可以通过Content-Disposition HTTP 标头来完成。 您可以在此处为新下载的文件指定文件名。

这可以添加到 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)

注意:为简单起见, Content-Type被移到headers

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM