将标头添加到python请求模块

时间:2011-12-31 02:02:09

标签: python http-headers python-requests

之前我使用httplib模块在​​请求中添加标头。现在我正在使用requests模块尝试相同的事情。

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

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

2 个答案:

答案 0 :(得分:123)

来自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)

你只需要用你的标题创建一个dict(键:值对,其中键是标题的名称,值是,该对的值),并将该dict传递给标题参数.get.post方法。

更具体的问题是:

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

答案 1 :(得分:21)

您也可以这样设置Session对象的所有未来获取的标头,其中x-test将在所有s.get()调用中:

memcpy

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

相关问题