python下载前获取文件大小

下载前获取文件大小

from contextlib import closing

import requests
import time
import hashlib

# 关键代码 stream = True 参数,以流的方式读取
# 执行代码 直接给出文件大小
# from pip._internal.utils.parallel import closing

url = 'https://qd.myapp.com/myapp/qqteam/pcqq/PCQQ2019.exe'
re = requests.get(url, stream=True)
# print(re.headers)
print(re.headers.get('Content-Length'))


# 主要用在下载大文件

def request_url(url, headers, file_path):
    m = hashlib.md5()
    start_time = time.time()
    with open(file_path, 'wb') as code:
        with closing(requests.get(url, headers=headers, timeout=3, stream=True)) as res:
            file_size_str = res.headers.get('Content-Length')
            if int(file_size_str) > 300000000:
                return 'no', 'no', 'no'
            for chunk in res.iter_content(chunk_size=10240):
                if time.time() - start_time > 3:
                    return 'no', 'no', 'no'
                start_time = time.time()
                code.write(chunk)
                m.update(chunk)
    return m.hexdigest(), file_path, file_size_str

下载前获取文件大小

requests.get()参数详解

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值