How to get size of request message in python?

Viewed 465

I am trying to see how many bytes were sent out to the server when making an HTTP request.

import requests

resp = requests.get("http://www.example.com")

print(resp.request)
>>> <PreparedRequest [GET]>

How can I get the number of bytes contained in <PreparedRequest [GET]> including any files/payloads/etc.

2 Answers

I'm just going to answer my own question. This isn't perfect and has a bunch of edge cases where it fails - but it does the job for me atleast.

def rlen(response):
    """
    approximate request size sent to server
    """
    len_of_meth = len(response.request.method)
    len_of_addr = len(response.request.url)
    len_of_head = len('\r\n'.join('{}{}'.format(k, v) for k, v in response.request.headers.items()))
    len_of_body = len(response.request.body if response.request.body else [])

    return len_of_meth + len_of_addr + len_of_head + len_of_body
Related