起因
使用环境受限,只能与平台层面合作不能在防火墙上开新的接口,只好使用http协议,依托于web服务上
流式发送二进制文件
import os
import sys
from flask import Response, jsonfy
def streaming_file(params):
"""
流式发送文件
@return:
"""
UPDATE_PACKAGE_PATH = '/tools/package/'
out = os.path.join(UPDATE_PACKAGE_PATH, params.get("filename"))
if not os.path.isfile(out):
return None
# 文件大小
fsize = os.path.getsize(out)
def send_file_fp():
store_path = out
send_size = 0
with open(store_path, "rb") as target_file:
while 1:
data = target_file.read(2 * 1024 * 1024) # 每次读取2M
if not data:
break
yield data
response = Response(send_file_fp(), content_type='multipart/form-data; boundary=something')
response.headers["Content-disposition"] = 'attachment; filename={}'.format(params.get("filename"))
response.headers["Content-length"] = fsize
return response
流式接收文件
def save_streaming_file(params, ip, port):
"""
接收流式文件
@return:
"""
url = 'https://{}:{}/streaming_file?filename={}'.format(ip, port, params.get("filename"))
save_package_path = os.path.join('/tools', datetime.today().strftime('%Y%m%d'))
save_package_file = os.path.join(save_package_path, params.get("filename"))
# 判断文件夹是否存在,不存在则创建
if not os.path.exists(save_package_path):
os.makedirs(save_package_path)
with closing(requests.get(url, stream=True, verify=False)) as res, open(save_package_file, "wb") as f:
# 下载文件大小
total_size = int(res.headers["content-length"])
content_size = 0
for content in res.iter_content(chunk_size=1024):
f.write(content)
content_size += len(content)
data = {"recv_size": content_size, "total_size": total_size}
if content_size == total_size:
return jsonify(code=200, status=1, message=u"接收成功", data=data)
return jsonify(code=400, status=0, message=u"接收失败", data=data)