首页 > 解决方案 > 内容长度在 Curl、Wget 中可用,但在 Python 请求中不可用

问题描述

我有一个指向二进制文件的 URL,我需要在检查其大小后下载该文件,因为只有在本地文件大小与远程文件大小不同时才应(重新)执行下载。

这就是它的工作方式wget(匿名主机名和 IP):

$ wget <URL>
--2020-02-17 11:09:18--  <URL>
Resolving <URL> (<host>)... <IP>
Connecting to <host> (<host>)|<ip>|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 31581872 (30M) [application/x-gzip]
Saving to: ‘[...]’

这也适用于该--continue标志以恢复下载,包括如果文件之前已完全下载则跳过。

我可以对 做同样的事情curlcontent-length也存在:

$ curl -I <url>
HTTP/2 200 
date: Mon, 17 Feb 2020 13:11:55 GMT
server: Apache/2.4.25 (Debian)
strict-transport-security: max-age=15768000
last-modified: Fri, 14 Feb 2020 15:42:29 GMT
etag: "[...]"
accept-ranges: bytes
content-length: 31581872
vary: Accept-Encoding
content-type: application/x-gzip

在 Python 中,我尝试通过Content-length使用requests 库检查标头来实现相同的逻辑:

        with requests.get(url, stream=True) as response:
            total_size = int(response.headers.get("Content-length"))

            if not response.ok:
                logger.error(
                    f"Error {response.status_code} when downloading file from {url}"
                )
            elif os.path.exists(file) and os.stat(file).st_size == total_size:
                logger.info(f"File '{file}' already exists, skipping download.")
            else:
                [...] # download file

事实证明,Content-length标头从不存在,即在None这里得到一个值。我知道这应该通过将默认值传递给get()调用来解决,但出于调试的目的,此示例因此触发了异常:

TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' 

我可以手动确认Content-length标题不存在:

requests.get(url, stream=True).headers
{'Date': '[...]', 'Server': '[...]', 'Strict-Transport-Security': '[...]', 'Upgrade': '[...]', 'Connection': 'Upgrade, Keep-Alive', 'Last-Modified': '[...]', 'ETag': ''[...]'', 'Accept-Ranges': 'bytes', 'Vary': 'Accept-Encoding', 'Content-Encoding': 'gzip', 'Keep-Alive': 'timeout=15, max=100', 'Transfer-Encoding': 'chunked', 'Content-Type': 'application/x-gzip'}

这个逻辑虽然适用于其他 URL,但我确实得到了Content-length标题。

使用requests.head(url)(省略stream=True)时,除了Transfer-Encoding.

我了解服务器不必发送Content-length标头。但是,wget显然curl确实得到了那个标题。它们与我的 Python 实现有什么不同?

标签: pythonhttpcurlwget

解决方案


不是关于缺少标题的问题的真正答案Content-length,而是对潜在问题的解决方案:

我没有检查本地文件大小与远程文件的内容长度,而是检查了Last-modified标题并将其mtime与本地文件的标题进行了比较。这在远程文件已更新但仍具有完全相同大小的(不太可能的)情况下也更安全。


推荐阅读