下载前获取文件大小

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()参数详解

在这里插入图片描述


版权声明:本文为qq_44810930原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_44810930/article/details/117461603