Wie andere bereits erwähnt haben, gibt es eine schöne requests-toolbelt
Modul mit praktischen Funktionen zum Auslesen von Anfrage- und Antwortinhalten unter Verwendung von Request-Hooks. Leider gibt es (bis jetzt) nur einen Hook, der bei erfolgreichem Abschluss einer Anfrage aufgerufen wird. Das ist nicht immer der Fall. D.h. eine Anfrage könnte enden mit ConnectionError
o Timeout
Ausnahmen.
En requests-toolbelt
Modul selbst bietet auch öffentliche Funktionen, um nur abgeschlossene Anfragen auszulagern. Mit Hilfe von nicht-öffentlichen APIs und Session Sub-Classing ist es jedoch möglich, die Protokollierung von Anfragen vor dem Senden und die Protokollierung von Antworten nach dem Empfang zu implementieren.
HINWEIS: Der Code stützt sich auf Implementierungsdetails/nicht-öffentliche APIs von requests-toolbelt
Modul und damit in Zukunft unerwartet zu brechen:
import requests
from requests_toolbelt.utils import dump
class MySession(requests.Session):
def send(self, req, *args, **kwargs):
prefixes = dump.PrefixSettings(b'< ', b'> ')
data = bytearray()
try:
dump._dump_request_data(req, prefixes, data)
resp = super().send(req, *args, **kwargs)
dump._dump_response_data(resp, prefixes, data)
finally:
print(data.decode('utf-8'))
return resp
und hier ist ein Beispiel für die Verwendung:
>>> MySession().get('https://httpbin.org/headers')
< GET /headers HTTP/1.1
< Host: httpbin.org
< User-Agent: python-requests/2.25.1
< Accept-Encoding: gzip, deflate
< Accept: */*
< Connection: keep-alive
<
> HTTP/1.1 200 OK
> Date: Fri, 19 Aug 2022 10:43:51 GMT
> Content-Type: application/json
> Content-Length: 225
> Connection: keep-alive
> Server: gunicorn/19.9.0
> Access-Control-Allow-Origin: *
> Access-Control-Allow-Credentials: true
>
{
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.25.1"
}
}
>>> MySession().get('https://non.existent')
< GET / HTTP/1.1
< Host: non.existent
< User-Agent: python-requests/2.25.1
< Accept-Encoding: gzip, deflate
< Accept: */*
< Connection: keep-alive
<
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 169, in _new_conn
conn = connection.create_connection(
File "/usr/lib/python3/dist-packages/urllib3/util/connection.py", line 73, in create_connection
for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
File "/usr/lib/python3.10/socket.py", line 955, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known
...