【问题标题】:Adding headers to requests module向请求模块添加标头
【发布时间】:2012-01-30 22:18:57
【问题描述】:

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

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

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

【问题讨论】:

标签: python http-headers python-requests


【解决方案1】:

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

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

所以更具体到你的问题:

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

【讨论】:

  • 查看您发送和/或收到的回复可能会有所帮助。根据Requests Advanced Usage docs,使用r.headers 访问服务器发回的标头,使用r.request.headers 查看您发送到服务器的标头。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-22
    • 2016-04-10
    • 1970-01-01
    • 1970-01-01
    • 2013-10-28
    • 1970-01-01
    • 2020-12-14
    • 2017-12-27
    相关资源
    最近更新 更多