原始响应的大小(以字节为单位) [英] Size of raw response in bytes

查看:36
本文介绍了原始响应的大小(以字节为单位)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要发出一个 HTTP 请求并确定响应大小(以字节为单位).我一直使用 request 来处理简单的 HTTP 请求,但我想知道是否可以使用 raw 来实现?

<预><代码>>>>r = requests.get('https://github.com/', stream=True)>>>r.raw

我唯一的问题是我不明白什么是原始返回或我如何以字节为单位计算这种数据类型?使用 request 和 raw 是正确的方法吗?

解决方案

只取响应内容的len():

<预><代码>>>>response = requests.get('https://github.com/')>>>len(响应.内容)51671

如果您想保持流式传输,例如如果内容(太大),您可以迭代数据块并总结它们的大小:

<预><代码>>>>使用 requests.get('https://github.com/', stream=True) 作为响应:... size = sum(len(chunk) for chunk in response.iter_content(8196))>>>尺寸51671

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?

>>> 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?

解决方案

Just take the len() of the content of the response:

>>> 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

这篇关于原始响应的大小(以字节为单位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆