Is there any other elegant way to add header to requests :
import requests
requests.get(url,headers={'Authorization', 'GoogleLogin auth=%s' % authorization_token})
doesn't work, while urllib2 worked :
import urllib2
request = urllib2.Request('http://maps.google.com/maps/feeds/maps/default/full')
request.add_header('Authorization', 'GoogleLogin auth=%s' % authorization_token)
urllib2.urlopen(request).read()
In the Home pane, double-click HTTP Response Headers. In the HTTP Response Headers pane, click Add... in the Actions pane. In the Add Custom HTTP Response Header dialog box, set the name and value for your custom header, and then click OK.
In order to pass HTTP headers into a POST request using the Python requests library, you can use the headers= parameter in the . post() function. The headers= parameter accepts a Python dictionary of key-value pairs, where the key represents the header type and the value is the header value.
You can add headers by passing a dictionary as an argument.
This should work:
requests.get(url,headers={'Authorization': 'GoogleLogin auth=%s' % authorization_token})
Why your code not worked?
You were not passing a dictionary to the headers argument. You were passing values according to the format defined in add_header()
function.
According to docs,
requests.get(url, params=None, headers=None, cookies=None, auth=None, timeout=None)
headers – (optional) Dictionary of HTTP Headers to send with the Request.
Why request.add_header() worked?
Your way of adding headers using request.add_header()
worked because the function is defined as such in the urllib2
module.
Request.add_header(key, val)
It accepts two arguments -
You can pass dictionary through headers
keyword. This is very elegant in Python :-)
headers = {
"header_name": "header_value",
}
requests.get(url, headers=headers)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With