29 Mar 2012, 08:23

Python Requests hooks


Python requests is the de facto HTTP package for Python, nice API, wonderful documentation.

I had the need to sign my requests and to change the header after the request was built, here is hooks, simply call a function pre_request and your are done:

def auth_sign(req):
user_id = '4f47a5f21aebcedff3001234'
secret_key = 'C21LHQ5R4RVO2U2UMTEZ'
timestamp = str(int(time.mktime(time.gmtime())))
string_to_sign = req.method + '\n' + user_id + '\n' + timestamp + '\n' + req.path_url + '\n' + req._enc_data

sign = base64.b64encode(hmac.new(secret_key, string_to_sign,

headers = {'X-User-ID':user_id, 'X-Expires':timestamp, 'X-Signature':sign}
payload = {'name':'Test event', 'description':'Description blabla', 'category':'1'}
r = requests.post(API_URL + 'event', data=payload, hooks={'pre_request':auth_sign})

And remember to use httpie Curl for human which is using requests