已知数据入库,存在数据表,model层读取了数据库查询结果。将查询结果转为excel,放入内存中。

# model.py
from io import BytesIO
import pandas as pd

def to_excel(sql_return):
	df = pd.DataFrame(sql_return)
	f = BytesIO()  # 内存文件
	with pd.ExcelWriter(f, engine='openpyxl') as w:
	    df.to_excel(w, index=None)
	f.seek(0)  # 文件指针
	return f

将内存中的数据放入返回体。

# view.py
import arrow
from flask import Flask, request, make_reponse
from model import to_excel

app = Flask(__name__)
...

@app.route('/api/v1/xxx/export')
def export_content():
	data = request.data
	...
	f = to_excel(sql_return)
	rv = make_response(f.getvalue())
    f.close()
    rv.headers['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    rv.headers['Cache-Control'] = 'no-cache'
    rv.headers['Content-Disposition'] = 'attachment; filename=export-{}.xlsx'.format(int(arrow.now().timestamp()*1000))
    return rv

如上。

更多推荐