小编典典

在使用Flask的python中,如何写出要下载的对象?

flask

我正在使用Flask并正在运行领班。我将数据存储在内存中,希望用户能够将其下载到文本文件中。我不想将数据写到本地磁盘上的文件中并使其可供下载。


阅读 482

收藏
2020-04-06

共1个答案

小编典典

Flask文档的“样式”部分介绍了将文件流传输到客户端而不将其保存到磁盘的过程,特别是在流传输部分。基本上,您要做的是返回一个Response包装了迭代器的完整对象:

from flask import Response

# construct your app

@app.route("/get-file")
def get_file():
    results = generate_file_data()
    generator = (cell for row in results
                    for cell in row)

    return Response(generator,
                       mimetype="text/plain",
                       headers={"Content-Disposition":
                                    "attachment;filename=test.txt"})
2020-04-06