Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python请求/urllib—;监视带宽使用情况_Python_Python Requests_Bandwidth - Fatal编程技术网

Python请求/urllib—;监视带宽使用情况

Python请求/urllib—;监视带宽使用情况,python,python-requests,bandwidth,Python,Python Requests,Bandwidth,我想记录Python脚本下载和上传的总字节数 total_downloaded_bytes = 0 def bandwidth_hook(r, *args, **kwargs): global total_downloaded_bytes total_downloaded_bytes += len(r.content) req = requests.session() req.hooks = {'response': bandwidth_hook} 上面的代码没有考虑HTTP压

我想记录Python脚本下载和上传的总字节数

total_downloaded_bytes = 0
def bandwidth_hook(r, *args, **kwargs):
    global total_downloaded_bytes
    total_downloaded_bytes += len(r.content)
req = requests.session()
req.hooks = {'response': bandwidth_hook}
上面的代码没有考虑HTTP压缩(如果我是对的)和头的大小


有没有办法计算requests.session上传和下载的总字节数?如果不是,那么脚本范围的计数呢?

您可以访问
r.request
对象来计算传出字节,并且您可以通过查看传入请求的
内容长度
头来确定传入字节(压缩或未压缩)。这应该足以满足您通常会提出的所有请求的99%

计算头的字节大小非常简单;只需添加键值和值长度,为冒号和空白添加4个字节,再加上空白行的2个字节:

 def header_size(headers):
     return sum(len(key) + len(value) + 4 for key, value in headers.items()) + 2
还有最初的路线;这是请求的
{method}{path\u url}HTTP/1.1{CRLF}
,响应的
HTTP/1.x{status\u code}{reason}{CRLF}
。这些长度也可供您选择

那么总尺寸是:

 request_line_size = len(r.request.method) + len(r.request.path_url) + 12
 request_size = request_line_size + header_size(r.request.headers) + int(r.request.headers.get('content-length', 0))
 response_line_size = len(r.response.reason) + 15
 response_size = response_line_size + header_size(r.headers) + int(r.headers.get('content-length', 0))
 total_size = request_size + response_size

哇,对于一些简单的东西来说,这看起来很复杂。谢谢你的回答@Elmo:respone对象是HTTP信息的高级建模,它从来都不是完全重构底层HTTP协议字节的用例。你不能挂接更深的地方吗?实际的tcp流还是在什么地方?@Elmo:您必须修补
请求附带的打包
urllib3
库,没有用于此的ootb挂钩。