本文介绍了从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?

推荐答案

使用和。使用写入内存缓冲区,而不是生成中间文件

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.

以下是如何做到这一点的一个简单的例子。

The following is a short example of how to do this.

import csv
from datetime import datetime
from cstringio import StringIO
from flask import Flask, stream_with_context
from werkzeug.datastructures import Headers
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)

    # add a filename
    headers = Headers()
    headers.set('Content-Disposition', 'attachment', filename='log.csv')

    # stream the response as the data is generated
    return Response(
        stream_with_context(generate()),
        mimetype='text/csv', headers=headers
    )

app.run()

这篇关于从Flask视图创建并下载CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 21:45