在Python请求中缓存Bearer Auth令牌



我从api中提取了很多数据。就像这样。

session = requests.Session()
response = session.post(url, 'auth'), verify=False, json={CREDENTIALS HERE})
head = {'Authorization': 'Bearer %s' % (response.json()['token'])}
response = requests.get(url, headers=head)

有没有什么好的方法可以保存/缓存标头而不总是获取新的令牌?

您可以使用会话向站点发出一个请求,然后执行session.headers以获取从站点发回的标头并将其保存到变量中。

serverHeaders = r.headers
#r.headers is below
{'content-length': '56170', 'x-content-type-options': 'nosniff', 'x-cache':
'HIT from cp1006.eqiad.wmnet, MISS from cp1010.eqiad.wmnet', 'content-encoding':
'gzip', 'age': '3080', 'content-language': 'en', 'vary': 'Accept-Encoding,Cookie',
'server': 'Apache', 'last-modified': 'Wed, 13 Jun 2012 01:33:50 GMT',
'connection': 'close', 'cache-control': 'private, s-maxage=0, max-age=0,
must-revalidate', 'date': 'Thu, 14 Jun 2012 12:59:39 GMT', 'content-type':
'text/html; charset=UTF-8', 'x-cache-lookup': 'HIT from cp1006.eqiad.wmnet:3128,
MISS from cp1010.eqiad.wmnet:80'}

https://requests.readthedocs.io/en/master/user/advanced/#request-和响应对象

在文档中,他们有很多代码示例

最新更新