我需要获取将通过请求模块发送到服务器的字节。我需要获取字节,因为我想通过套接字模块将它们单独发送到特殊服务器。我该怎么做?
示例代码:
import requests
x = requests.get('http://example.com')
# Here I want to get the bytes of the request.
您可以重写
send()
的 HTTPConnection
方法,如下例所示。
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))