我试图允许用户下载包含其操作定义的数据的CSV文件。该文件不存在,它是动态创建的。如何在Flask中做到这一点?
使用生成数据csv.writer并传输响应。使用StringIO写入内存缓冲区,而不是生成中间文件。
csv.writer
StringIO
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函数需要从current中获取信息request,则应使用修饰stream_with_context,否则您将收到“在外部请求上下文中工作”错误。其他所有内容保持不变。
from flask import stream_with context @stream_with_context def generate(): ...