关于webserver大文件下载之客户端和服务端

直接贴示例代码:

 1. 服务端代码:
from rest_framework.response import Response
from django.http.response import StreamingHttpResponse

def file_iterator(file_name, chunk_size=512):
    with open(file_name, 'rb') as f:
        while True:
            c = f.read(chunk_size)
            if c:
                yield c
            else:
                break

@api_view(['GET'])
@permission_classes((TokenHasReadWriteScope, ))
def download_view(request, format=None):
    file_name= request.query_params.get('file_name', None)
    if not file_name:
        return Response(None, status=status.HTTP_400_BAD_REQUEST)
    found = [p for p in glob.glob('{0}/*'.format(file_dir)) if p.endswith('.rpm')]
    file_path = YOUR_DIR + file_name
    response = StreamingHttpResponse(file_iterator(file_path)) # 切片
    response['Content-Type'] = 'application/octet-stream'
    response['File-Name'] = os.path.basename(file_path)
    try:
        with open('{}.md5'.format(file_path), 'r') as f:  # MD5值校验
            md5sum = f.read().strip()
    except FileNotFoundError:
        md5sum = 'no file'
    response['Md5sum'] = md5sum
    return response
 2. 客户端代码:
def hash_file(file, buf_size=65536):
    md5 = hashlib.md5()
    if os.path.exists(file):
        with open(file, 'rb') as f:
            while True:
                data = f.read(buf_size)
                if not data:
                    break
                md5.update(data)
        return md5.hexdigest()

def download_from_agent(file_name):
    res = requests.get(STATION_DOWNLOAD_URI + '?file_name={0}'.format(file_name)
    if res.status_code != 200:
        raise IOError('Download faild.')
    else:
        file_name = res.headers['File-Name']
        file_path = '{0}/{3}'.format(YOUR_DIR, file_name)
        if not os.path.exists(YOUR_DIR):
            os.mkdir(YOUR_DIR)
        with open(file_path, 'wb+') as f:
            for chunk in res.iter_content(chunk_size=1024): # 切片
                if chunk:
                    f.write(chunk)
        if res.headers['Md5sum'] != hash_file(file_path):
            raise IOError('Broken file.')
        return file_path
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值