在使用 Flask 的 python 中,如何写出要下载的对象? [英] In python using Flask, how can I write out an object for download?
问题描述
我正在使用 Flask 并运行工头.我在内存中构建的数据,我希望用户能够将这些数据下载到文本文件中.我不想将数据写入本地磁盘上的文件并使其可供下载.
I'm using Flask and running foreman. I data that I've constructed in memory and I want the user to be able to download this data in a text file. I don't want write out the data to a file on the local disk and make that available for download.
我是 Python 新手.我想我会在内存中创建一些文件对象,然后设置响应头,也许?
I'm new to python. I thought I'd create some file object in memory and then set response header, maybe?
推荐答案
Flask 文档的模式"部分涵盖了将文件流式传输到客户端而不将它们保存到磁盘 - 特别是 在流式传输部分.基本上,您所做的是返回一个完整的 Response
包装迭代器的对象:
Streaming files to the client without saving them to disk is covered in the "pattern" section of Flask's docs - specifically, in the section on streaming. Basically, what you do is return a fully-fledged Response
object wrapping your iterator:
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"})
这篇关于在使用 Flask 的 python 中,如何写出要下载的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!