Home >Backend Development >Python Tutorial >How to Print the Raw HTTP Request with Python Requests?
Printing Raw HTTP Request in Python Requests
In Python's requests module, it's possible to print the unedited HTTP request, including the request line, headers, and content. This can be useful for debugging purposes or for inspecting the exact HTTP request being sent.
Starting from version 1.2.3 of the requests module, the PreparedRequest object was introduced. This object represents the fully constructed HTTP request, complete with all headers and content. Using the prepare method on a request object generates a PreparedRequest object.
To print the raw HTTP request using PreparedRequest, you can use the pretty_print_POST function shown below:
<code class="python">import requests # Example request req = requests.Request('POST', 'http://stackoverflow.com', headers={'X-Custom': 'Test'}, data='a=1&b=2') # Prepare the request prepared = req.prepare() def pretty_print_POST(req): print('{}\n{}\r\n{}\r\n\r\n{}'.format( '-----------START-----------', req.method + ' ' + req.url, '\r\n'.join('{}: {}'.format(k, v) for k, v in req.headers.items()), req.body, )) # Print the raw HTTP request pretty_print_POST(prepared) # Send the request (if desired) s = requests.Session() s.send(prepared)</code>
This function prints the request method, URL, headers, and content in a formatted manner.
To send the actual request after printing it, you can use the send method on a requests Session object, as shown in the example.
The above is the detailed content of How to Print the Raw HTTP Request with Python Requests?. For more information, please follow other related articles on the PHP Chinese website!