我正在使用 Flask 和运行工头。我在内存中构建的数据,我希望用户能够将这些数据下载到文本文件中。我不想将数据写入本地磁盘上的文件并使其可供下载。
我是 python 新手。我想我会在内存中创建一些文件对象,然后设置响应头,也许吧?
最佳答案
Flask 文档的“模式”部分介绍了将文件流式传输到客户端而不将它们保存到磁盘 - 具体来说,in the section on streaming .基本上,您所做的是返回一个成熟的 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"})
关于python - 在使用 Flask 的 python 中,如何写出一个对象以供下载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12166970/