在python中使用Flask,如何写出一个对象进行下载? [英] In python using Flask, how can I write out an object for download?

查看:114
本文介绍了在python中使用Flask,如何写出一个对象进行下载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Flask和工头。我在内存中构建的数据,我希望用户能够在文本文件中下载这些数据。我不想将数据写入本地磁盘上的文件,并使其可供下载。



我是新来的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆