swi*_*ikk 19 python file-io download flask python-2.7
我正在使用Flask和正在运行的工头.我在内存中构建的数据,我希望用户能够在文本文件中下载这些数据.我不想将数据写入本地磁盘上的文件并使其可供下载.
我是python的新手.我以为我会在内存中创建一些文件对象,然后设置响应头,也许?
Sea*_*ira 37
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"})
Run Code Online (Sandbox Code Playgroud)