Nota: questa risposta è obsoleta. Versioni più recenti di requests supporto ricevono direttamente il contenuto della richiesta, come i documenti di risposta di AntonioHerraizS .
Non è possibile estrarre il vero contenuto non elaborato della richiesta requests, poiché si occupa solo di oggetti di livello superiore, come intestazioni e tipo di metodo . requestsusi urllib3di inviare richieste, ma urllib3 anche non tratta dati grezzi - usa httplib. Ecco una traccia dello stack rappresentativa di una richiesta:
-> r= requests.get("http://google.com")
/usr/local/lib/python2.7/dist-packages/requests/api.py(55)get()
-> return request('get', url, **kwargs)
/usr/local/lib/python2.7/dist-packages/requests/api.py(44)request()
-> return session.request(method=method, url=url, **kwargs)
/usr/local/lib/python2.7/dist-packages/requests/sessions.py(382)request()
-> resp = self.send(prep, **send_kwargs)
/usr/local/lib/python2.7/dist-packages/requests/sessions.py(485)send()
-> r = adapter.send(request, **kwargs)
/usr/local/lib/python2.7/dist-packages/requests/adapters.py(324)send()
-> timeout=timeout
/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/connectionpool.py(478)urlopen()
-> body=body, headers=headers)
/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/connectionpool.py(285)_make_request()
-> conn.request(method, url, **httplib_request_kw)
/usr/lib/python2.7/httplib.py(958)request()
-> self._send_request(method, url, body, headers)
All'interno del httplibmacchinario, possiamo vedere gli HTTPConnection._send_requestusi indiretti HTTPConnection._send_output, che alla fine creano la richiesta e il corpo grezzi (se esistenti) e li usano HTTPConnection.sendper inviarli separatamente. sendraggiunge finalmente la presa.
Dal momento che non ci sono ganci per fare quello che vuoi, come ultima risorsa puoi scimmiettare patch httplibper ottenere il contenuto. È una soluzione fragile e potrebbe essere necessario adattarla se httplibviene modificata. Se hai intenzione di distribuire software usando questa soluzione, potresti prendere in considerazione la creazione httplibdi pacchetti invece di usare il sistema, il che è facile, dal momento che è un modulo Python puro.
Purtroppo, senza ulteriori indugi, la soluzione:
import requests
import httplib
def patch_send():
old_send= httplib.HTTPConnection.send
def new_send( self, data ):
print data
return old_send(self, data) #return is not necessary, but never hurts, in case the library is changed
httplib.HTTPConnection.send= new_send
patch_send()
requests.get("http://www.python.org")
che produce l'output:
GET / HTTP/1.1
Host: www.python.org
Accept-Encoding: gzip, deflate, compress
Accept: */*
User-Agent: python-requests/2.1.0 CPython/2.7.3 Linux/3.2.0-23-generic-pae