基于Flask框架从mysql导出CSV格式的数据

2020-03-19  本文已影响0人  洛奇lodge

需求

用户需要在界面操作,可以导出数据库的数据,以CSV格式下载,后台框架使用的是Flask

考虑问题

代码示例

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)
上一篇 下一篇

猜你喜欢

热点阅读