Python 3.6.5:即使指定了 chunk_length,带流的请求也会卡在 iter_content

Python 3.6.5: Requests with streaming getting stuck in iter_content even if chunk_length is specified

我一直在尝试使用 python 3.6.5 中的请求 v2.19.1 从远程 URL 下载一个 ~2GB 的文件。但是,我一直反复遇到这个问题,代码似乎永远卡在 for 循环中以尝试下载数据。

我的代码片段:

        with requests.get(self.model_url, stream=True, headers=headers) as response:

            if response.status_code not in [200, 201]:
                raise Exception(
                    'Error downloading model({}). Got response code {} with content {}'.format(
                        self.model_id,
                        response.status_code,
                        response.content
                    )
                )
            with open(self.download_path, 'wb') as f:
                for chunk in response.iter_content(chunk_size=1024):
                    if chunk:
                        f.write(chunk)

每次我尝试 运行 此代码时,下载似乎都在不同的点停止,而且很少能完成。 我试过使用不同的块大小,但我仍然看到这个问题。

一些额外的细节:

    python -m requests.help
{
  "chardet": {
    "version": "3.0.4"
  },
  "cryptography": {
    "version": "2.3.1"
  },
  "idna": {
    "version": "2.7"
  },
  "implementation": {
    "name": "CPython",
    "version": "3.6.5"
  },
  "platform": {
    "release": "3.10.0-693.11.1.el7.x86_64",
    "system": "Linux"
  },
  "pyOpenSSL": {
    "openssl_version": "1010009f",
    "version": "18.0.0"
  },
  "requests": {
    "version": "2.19.1"
  },
  "system_ssl": {
    "version": "100020bf"
  },
  "urllib3": {
    "version": "1.23"
  },
  "using_pyopenssl": true
}

有没有其他人遇到过类似的问题?如果有,你是怎么解决的?

好像下载过程中如果网络中断,就会挂流,断线。然而,因为没有指定超时,代码似乎期望更多的数据包通过死连接到达。我发现处理此问题的最佳方法是设置合理的超时时间。一旦在最后一个接收到的包之后达到超时,代码将退出 for 循环并出现可以处理的异常。