在python中使用Flask,如何写出一个对象进行下载? [英] In python using Flask, how can I write out an object for download?
问题描述
我是新来的python。我以为我会在内存中创建一些文件对象,然后设置响应头,也许?
将其保存到磁盘中,在Flask的文档的模式部分中包含 - 具体来说,在流。基本上,您所做的是返回一个完整的 响应
对象包装您的迭代器:
从烧瓶导入响应
#构造你的应用程序
@ app.route(/ get-file)
def get_file():
results = generate_file_data()
generator =(cell
返回响应(生成器,
mimetype =text / plain,
headers = {Content-Disposition :
attachment; filename = test.txt})
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.
I'm new to python. I thought I'd create some file object in memory and then set response header, maybe?
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"})
这篇关于在python中使用Flask,如何写出一个对象进行下载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!