使用生成数据
csv.writer并传输响应。使用StringIO写入内存缓冲区,而不是生成中间文件。
import csvfrom datetime import datetimefrom io import StringIOfrom flask import Flaskfrom werkzeug.wrappers import Responseapp = Flask(__name__)# example data, this could come from wherever you are storing logslog = [ ('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_contextdef generate(): ...
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)