Python Requests hooks
- python requests
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](http://docs.python- requests.org/en/v0.10.7/user/advanced/#event-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,
hashlib.sha256).digest())
headers = {'X-User-ID':user_id, 'X-Expires':timestamp, 'X-Signature':sign}
req.headers.update(headers)
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