【发布时间】:2019-11-26 10:18:18
【问题描述】:
我正在使用 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)
我的问题是,如何在代码中设置我的 TOKEN 值?
【问题讨论】:
-
Python 有字符串插值,就像你的 shell 一样。例如
f'Bearer {token}",将变量token的值放入标题Authorization的字符串值中。 -
或者只是使用连接,所以
'Bearer ' + token。这些都不是特定于 Python 请求的,这只是 只是 字符串操作。 -
您是否(至少部分地)询问如何从 Python 中的 TOKEN 环境变量中获取 token 的值?
-
哦,所以只使用 'Authorization': 'Bearer' +
就可以了? -
是的..谢谢它的工作。我正在尝试 {'Authorization': 'Bearer=
'}。对不起这个愚蠢的问题。我的想法完全失去了..
标签: python python-3.x