如果您已经下载了 URL(使用requests
GET
不带该选项的请求stream
,则在下载和解压缩整个响应时,您已经拥有两种大小,并且原始长度在标头中可用:
from __future__ import division
r = requests.get(url, headers=headers)
compressed_length = int(r.headers['content-length'])
decompressed_length = len(r.content)
ratio = compressed_length / decompressed_length
您可以将Accept-Encoding: identity
HEAD 请求内容长度标头与设置进行比较Accept-Encoding: gzip
:
no_gzip = {'Accept-Encoding': 'identity'}
no_gzip.update(headers)
uncompressed_length = int(requests.get(url, headers=no_gzip).headers['content-length'])
force_gzip = {'Accept-Encoding': 'gzip'}
force_gzip.update(headers)
compressed_length = int(requests.get(url, headers=force_gzip).headers['content-length'])
但是,这可能不适用于所有服务器,因为动态生成的内容服务器通常会在这种情况下使用 Content-Length 标头来避免必须首先呈现内容。
如果您正在请求分块传输编码资源,则不会有content-length 标头,在这种情况下,HEAD 请求可能会也可能不会为您提供正确的信息。
在这种情况下,您必须流式传输整个响应并从流的末尾提取解压缩的大小(GZIP 格式在最后将其包含为 little-endian 4-byte unsigned int)。使用原始 urllib3 响应对象上的stream()
方法:
import requests
from collections import deque
if hasattr(int, 'from_bytes'):
# Python 3.2 and up
_extract_size = lambda q: int.from_bytes(bytes(q), 'little')
else:
import struct
_le_int = struct.Struct('<I').unpack
_extract_size = lambda q: _le_int(b''.join(q))[0]
def get_content_lengths(url, headers=None, chunk_size=2048):
"""Return the compressed and uncompressed lengths for a given URL
Works for all resources accessible by GET, regardless of transfer-encoding
and discrepancies between HEAD and GET responses. This does have
to download the full request (streamed) to determine sizes.
"""
only_gzip = {'Accept-Encoding': 'gzip'}
only_gzip.update(headers or {})
# Set `stream=True` to ensure we can access the original stream:
r = requests.get(url, headers=only_gzip, stream=True)
r.raise_for_status()
if r.headers.get('Content-Encoding') != 'gzip':
raise ValueError('Response not gzip-compressed')
# we only need the very last 4 bytes of the data stream
last_data = deque(maxlen=4)
compressed_length = 0
# stream directly from the urllib3 response so we can ensure the
# data is not decompressed as we iterate
for chunk in r.raw.stream(chunk_size, decode_content=False):
compressed_length += len(chunk)
last_data.extend(chunk)
if compressed_length < 4:
raise ValueError('Not enough data loaded to determine uncompressed size')
return compressed_length, _extract_size(last_data)
演示:
>>> compressed_length, decompressed_length = get_content_lengths('http://httpbin.org/gzip')
>>> compressed_length
179
>>> decompressed_length
226
>>> compressed_length / decompressed_length
0.7920353982300885