在Python请求中设置令牌头

时间:2019-07-17 14:27:52

标签: python python-3.x

我正在使用curl使用以下命令调用我的REST服务

export TOKEN= '<random>'
curl -X "GET" -H "Content-Type:application/json" -H "Authorization:Bearer ${TOKEN}" http://my-server.com

我正在尝试使用Python的请求库映射相同的代码

import requests

url = 'https://httpbin.org/bearer'
headers = {'Authorization': 'Bearer', 'Content-Type':'application/json'}

r = requests.get(url, headers=headers)
print(r.status_code)

我的问题是,如何在代码中设置我的令牌值?

2 个答案:

答案 0 :(得分:1)

可以以dict形式将授权令牌添加到headers参数,如下所示:

hed = {'Authorization': 'Bearer ' + auth_token,
       'Content-Type': 'application/json'}
r = requests.post(url=url, headers=hed)

我建议阅读此https://2.python-requests.org/en/master/user/quickstart/

答案 1 :(得分:1)

只需替换当前行即可

headers = {'Authorization': 'Bearer ' + token, 'Content-Type':'application/json'}

现在取决于您从何处获取令牌,但要包括这样的令牌。