从 Flask 视图创建和下载 CSV 文件

从 Flask 视图创建和下载 CSV 文件

问题描述:

我试图允许用户下载一个 CSV 文件,其中包含由他们的操作定义的数据.该文件不存在,它是动态创建的.我怎样才能在 Flask 中做到这一点?

I am trying to allow the user to download a CSV file with data defined by their actions. The file doesn't exist, it's created dynamically. How can I do this in Flask?

使用 csv.writer流式响应.使用 StringIO 写入内存缓冲区而不是生成一个中间文件.

Generate the data with csv.writer and stream the response. Use StringIO to write to an in-memory buffer rather than generating an intermediate file.

import csv
from datetime import datetime
from io import StringIO
from flask import Flask
from werkzeug.wrappers import Response

app = Flask(__name__)

# example data, this could come from wherever you are storing logs
log = [
    ('login', datetime(2015, 1, 10, 5, 30)),
    ('deposit', datetime(2015, 1, 10, 5, 35)),
    ('order', datetime(2015, 1, 10, 5, 50)),
    ('withdraw', datetime(2015, 1, 10, 6, 10)),
    ('logout', datetime(2015, 1, 10, 6, 15))
]

@app.route('/')
def download_log():
    def generate():
        data = StringIO()
        w = csv.writer(data)

        # write header
        w.writerow(('action', 'timestamp'))
        yield data.getvalue()
        data.seek(0)
        data.truncate(0)

        # write each log item
        for item in log:
            w.writerow((
                item[0],
                item[1].isoformat()  # format datetime as string
            ))
            yield data.getvalue()
            data.seek(0)
            data.truncate(0)

    # stream the response as the data is generated
    response = Response(generate(), mimetype='text/csv')
    # add a filename
    response.headers.set("Content-Disposition", "attachment", filename="log.csv")
    return response

如果generate函数需要来自当前request的信息,应该用stream_with_context修饰,否则你会得到一个working外部请求上下文"错误.其他一切都保持不变.

If the generate function will need information from the current request, it should be decorated with stream_with_context, otherwise you will get a "working outside request context" error. Everything else remains the same.

from flask import stream_with context

@stream_with_context
def generate():
    ...