文件导出接口
from zipfile import ZIP_DEFLATED
import flask
import os
import sys
import zipstream
from django.utils.encoding import escape_uri_path
from flask import Response
interface_path = os.path.dirname(__file__)
sys.path.insert(0, interface_path)
app = flask.Flask(__name__)
file_path = 'D:\\python\\项目\\jiekou\\file'
def file_iterator(file_name, chunk_size=512):
"""
文件读取迭代器
:param file_name:文件名称
:param chunk_size: 每次读取流大小
:return:
"""
with open(file_path + "\\" + file_name, 'rb') as target_file:
while True:
chunk = target_file.read(chunk_size)
if chunk:
yield chunk
else:
break
@app.route('/export', methods=['GET'], endpoint='zipball')
def export():
"""
文件导出
:return:
"""
z = zipstream.ZipFile(compression=ZIP_DEFLATED)
file_name = os.listdir(file_path)
if len(file_name) == 1:
file_name = file_name[0]
response = Response(file_iterator(str(file_name)))
response.headers['Content-Type'] = 'application/octet-stream'
response.headers["Content-Disposition"] = 'attachment;filename="{}"'.format(escape_uri_path(file_name))
return response
else:
for i in file_name:
filefullpath = os.path.join(file_path, i)
z.write(filefullpath, i)
response = Response(z, mimetype='application/zip')
response.headers['Content-Disposition'] = 'attachment; filename={}'.format(escape_uri_path('测试结果.zip'))
return response
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000)