简体   繁体   English

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

[英]In python using Flask, how can I write out an object for download?

I'm using Flask and running foreman. 我正在使用Flask和正在运行的工头。 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. 我是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 . Flask的文档的“模式”部分介绍了将文件流式传输到客户端而不将其保存到磁盘 - 特别是在流式传输部分 Basically, what you do is return a fully-fledged Response object wrapping your iterator: 基本上,你所做的是返回一个包含你的迭代器的完全成熟的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"})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM