将标头添加到python请求模块

问题:将标头添加到python请求模块

之前我使用httplib模块在请求中添加标头。现在,我正在对该requests模块尝试相同的操作。

这是我正在使用的python请求模块:http : //pypi.python.org/pypi/requests

如何向标头添加标题,request.postrequest.get说必须foobar在标头的每个请求中添加密钥。

Earlier I used httplib module to add a header in the request. Now I am trying the same thing with the requests module.

This is the python request module I am using: http://pypi.python.org/pypi/requests

How can I add a header to request.post() and request.get(). Say I have to add foobar key in each request in the header.


回答 0

http://docs.python-requests.org/en/latest/user/quickstart/

url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}

r = requests.post(url, data=json.dumps(payload), headers=headers)

您只需要用标题创建一个字典(键:值对,其中键是标题的名称,值是该对的值),然后将该字典传递给.getor .post方法的标题参数。

因此,更具体地针对您的问题:

headers = {'foobar': 'raboof'}
requests.get('http://himom.com', headers=headers)

From http://docs.python-requests.org/en/latest/user/quickstart/

url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}

r = requests.post(url, data=json.dumps(payload), headers=headers)

You just need to create a dict with your headers (key: value pairs where the key is the name of the header and the value is, well, the value of the pair) and pass that dict to the headers parameter on the .get or .post method.

So more specific to your question:

headers = {'foobar': 'raboof'}
requests.get('http://himom.com', headers=headers)

回答 1

您还可以执行此操作以为Session对象的所有将来获取设置标头,其中x-test将出现在所有s.get()调用中:

s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})

来自:http : //docs.python-requests.org/en/latest/user/advanced/#session-objects

You can also do this to set a header for all future gets for the Session object, where x-test will be in all s.get() calls:

s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})

from: http://docs.python-requests.org/en/latest/user/advanced/#session-objects