149

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

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

如何向request.post()和添加标题request.get()。假设我必须foobar在标题中的每个请求中添加密钥。

4

2 回答 2

271

来自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 参数。

所以更具体到你的问题:

headers = {'foobar': 'raboof'}
requests.get('http://himom.com', headers=headers)
于 2011-12-31T02:07:16.843 回答
67

您还可以这样做为 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

于 2016-04-14T21:20:45.900 回答