需求
用户需要在界面操作,可以导出数据库的数据,以CSV格式下载,后台框架使用的是Flask
考虑问题
- 数据量过大,需要使用流式传送
- 数据编码格式问题,使用gbk,用户操作系统一般都基于win
代码示例
import csv
import time
from datetime import datetime
import io
from flask import Flask
from flask import Response
app = Flask(__name__)
data = [
{"姓名": "小名,你哈", "班级": None, "排名": 1},
{"姓名": "小哈", "班级": 2, "排名": 6},
{"姓名": "你哈", "班级": None, "排名": 2},
{"姓名": "小你", "班级": 3, "排名": 3},
{"姓名": "小名", "班级": None, "排名": 4},
{"姓名": "hong", "班级": 3, "排名": 5},
{"姓名": "like", "班级": None, "排名": 6}
]
@app.route('/')
def download():
def generate():
# 创建io流字符串对象
out = io.StringIO()
# 将数据以csv格式写入io流
w = csv.DictWriter(out, fieldnames=[i for i in data[0].keys()])
w.writeheader()
for row in data:
w.writerow(row)
# 一行一行传输前端
yield out.getvalue().encode("gbk")
# 偏移,相当于csv文件写入增加newline=‘’参数
out.seek(0)
out.truncate(0)
response = Response(generate(), mimetype='text/csv')
# 文件命名
file_name = time.strftime('%Y%m%d', time.localtime(time.time())) + '.csv'
# 如果文件名含有中午,需要进行转码
file_name = file_name.encode('utf-8').decode('latin-1')
response.headers["Content-Disposition"] = "attachment; filename=%s" % file_name
response.headers["Content-type"] = "text/csv;charset=utf-8"
return response
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7017, debug=True)
网友评论