I need to get the bytes that I will send to the server via the Request module. I need to get the bytes because I want to send them separately via the Socket module to a special server. How can I do this?
Sample code:
import requests
x = requests.get('http://example.com')
# Here I want to get the bytes of the request.
You can override the send()
method of the HTTPConnection
like the following example.
import requests
import urllib3
class DummyConnection(urllib3.connection.HTTPConnection):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.data = []
def send(self, data):
self.data.append(data)
def get_request_bytes(session, req):
req = req.prepare()
pool = session.get_adapter(req.url).get_connection(req.url)
conn = DummyConnection(pool.host, pool.port)
conn.request(req.method, req.url, headers=req.headers)
return b''.join(conn.data)
session= requests.Session()
req = requests.Request('GET',
url='http://a.b.c',
headers={'a': 'b'},
)
print(get_request_bytes(session, req))