文件导出接口

文件导出接口

# -*- coding:utf-8 -*-
# Time:2022/8/16 14:58
# Author:Xue
# FileName:123456.py
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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值