Python 原始响应的大小(以字节为单位)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24688479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Size of raw response in bytes
提问by ewhitt
I need to make a HTTP request and determine the response size in bytes. I have always used request
for simple HTTP requests, but I am wondering if I can achieve this using raw?
我需要发出一个 HTTP 请求并确定响应大小(以字节为单位)。我一直用于request
简单的 HTTP 请求,但我想知道是否可以使用 raw 来实现这一点?
>>> r = requests.get('https://github.com/', stream=True)
>>> r.raw
My only problem is I don't understand what raw returns or how I could count this data-type in bytes? Is using request
and raw the right approach?
我唯一的问题是我不明白什么是原始返回或我如何以字节为单位计算这种数据类型?使用request
和 raw 是正确的方法吗?
采纳答案by BlackHyman
Just take the len()
of the content of the response:
只需获取len()
响应的内容:
>>> response = requests.get('https://github.com/')
>>> len(response.content)
51671
If you want to keep the streaming, for instance if the content is (too) large you can iterate over chunks of the data and sum their sizes:
如果你想保持流式传输,例如如果内容(太大)你可以迭代数据块并总结它们的大小:
>>> with requests.get('https://github.com/', stream=True) as response:
... size = sum(len(chunk) for chunk in response.iter_content(8196))
>>> size
51671
回答by defool
r.raw
is an instance of urllib3.response.HTTPResponse. We can count the length of response by looking up the response's header Content-length
or use built-in function len()
.
r.raw
是urllib3.response.HTTPResponse 的一个实例。我们可以通过查找响应的标头Content-length
或使用内置函数来计算响应的长度len()
。