创建和下载一个csv文件 [英] Create and download a csv file

查看:280
本文介绍了创建和下载一个csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Flask应用程序部署在Google App Engine上。我试图允许用户下载一个csv文件,其数据由他们的操作定义。如何在Flask中执行此操作?

解决方案

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



以下是一个简单的例子。

  import csv 
from datetime import datetime
from cstringio import StringIO
从烧瓶导入Flask,stream_with_context
from werkzeug.datastructures import标题
from werkzeug.wrappers import Response

app = Flask(__ name__)

#示例数据,这可能来自存储日志的任何位置
log = [
('login'日期时间(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,
]

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

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

#写每个日志项
对于日志中的项:
w .writerow((
item [0],
item [1] .isoformat()#format datetime as string
))
yield data.getvalue()
data.seek(0)
data.truncate(0)

#添加文件名
headers = Headers()
headers.set('Content-Disposition' ,'attachment',filename ='log.csv')

#生成数据时生成的响应
返回响应(
stream_with_context(generate()),
mimetype ='text / csv',headers = headers


app.run()


My Flask application is deployed on Google App Engine. I am trying to allow the user to download a csv file with data defined by their actions. 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()

这篇关于创建和下载一个csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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