首页 > 解决方案 > requests.get 大文件成功,但文件大小随机小于实际大小

问题描述

我的代码:

    authentication = (myUsername, myPassword)
    r = requests.get(source_url, stream=True, auth=authentication)
    if r.status_code == 200:
        with open(target_file, 'wb') as f:
            right_size = int(r.headers['Content-Length'])
            for chunk in r.iter_content(chunk_size=512 * 1024):
                if chunk:
                    f.write(chunk)
            file_size = f.tell()
        if right_size > file_size:
            print("File {0} downloading issue: right size: {1}, end size: {2} ".format(filename, right_size, file_size))
        else:
            print("Succeeded")
    ...

当我用一个大的 jar 文件进行测试时,它报告了

File XXX.jar downloading problem: right size: 112835860, end size: 6564711

此问题随机出现,因此,它不是网络服务器配置问题。

我尝试使用 shutil.copyfileobj(full_url, filename, length=512 * 1024) 来获取文件,但仍然随机遇到相同的问题。

有什么建议吗?

标签: python-requests

解决方案


推荐阅读