Python requests library pre_request hook

python, python-requests

Solution

You need to create the request object yourself, pass that to the hook, then call `.prepare()` on it:

import requests

request = requests.Request('POST', url, ...)
request = oauth_hook(request)
prepared = request.prepare()

then send:

session = requests.session()
resp = session.send(prepared)

Problem

I'm having an issue with trying to switch from an ancient version of python-requests (0.14) to a newer version (1.1, 1.2 whatever). The problem is that we have a system which posts images on twitter using the following library: https://github.com/maraujop/requests-oauth The main problem is with this line of code: ``` # This is taken from the documentation of the library mentioned above session = requests.session(hooks={'pre_request': oauth_hook}) session.post(...) ``` As the Session constructor no longer accepts the hooks parameter. I found that the post method accept the hooks argument though and chagned the code like this: ``` session = requests.session() session.post(..., hooks={'pre_request': oauth_hook}) ``` This is better than before, however the pre_request is no longer accepted in newer version of python-requests (you can find this hook in the documentation of requests 0.14 but not in any of the newer versions). Can somebody help on this?

Original source