python - Python请求oauth2访问令牌错误
问题描述
我在 python 中使用下面的代码来访问令牌,但遇到了 NameError。我正在传递客户端 ID、客户端密码、访问令牌 url 和检索令牌。使用令牌,我从 get 方法 api 查询字符串中检索数据。不确定是什么导致了 NameError。
Python:
import sys
import requests
import json
import logging
import time
logging.captureWarnings(True)
api_url = "https://webapi.com/api/v1/data"
def get_new_token():
acc_token_url = "https://webapi.com/connect/accesstoken"
client_id = 'client'
client_secret = 'secret'
token_req_payload = {'grant_type': 'client_credentials'}
token_response = requests.post(acc_token_url , data = token_req_payload, verify = False, allow_redirects = False, auth = (client_id, client_secret))
if token_response.status_code != 200:
print("Failed to obtain token from OAuth2 server", file = sys.stderr)
sys.exit(1)
print("Successfuly obtained a new token from OAuth2 server")
tokens = json.loads(token_response.text)
return tokens['access_token']
token = get_new_token()
while True:
api_call_headers = {'Authorization': 'Bearer ' + token}
api_call_response = requests.get(api_url, headers = api_call_headers, verify = False)
if api_call_response.status_code == 401:
token = get_new_token()
else:
print(api_call_response.text)
错误:
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='www.webapi.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError(': Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond'))
解决方案
def get_new_token():
acc_token_url = "https://webapi.com/connect/accesstoken"
client_id = 'client'
client_secret = 'secret'
token_req_payload = {'grant_type': 'client_credentials'}
token_response = requests.post(acc_token_url , data = token_req_payload, verify = False, allow_redirects = False, auth = (client_id, client_secret))
if token_response.status_code != 200:
print("Failed to obtain token from OAuth2 server", file = sys.stderr)
sys.exit(1)
print("Successfuly obtained a new token from OAuth2 server")
tokens = json.loads(token_response.text)
return tokens['access_token']
推荐阅读
- sql - 在 PostgreSQL 中使用 DATE_TRUNC 计算一周的结束日期
- azure-devops - Azure DevOps - 我可以按项目分隔工作项自动 ID 编号吗?
- html - 我想为我的网站加载我的简历的 html 版本。但它无法编译
- java - 为什么 3 sum 算法只查看特定数字右侧的子数组?
- java - 即使在运行配置中指定,Eclipse 也无法找到 adb
- python - 如何遵循提示:改用可调用对象,例如,使用 `dict` 代替 `{}`?
- git - 是否可以在提交时执行 git revert ,但只能在特定目录中执行?
- python-2.7 - Python 2.7.16+ 导入错误:没有名为 sillyLibrary 的模块
- r - R:前 100 次观察与后 100 次观察不同的颜色
- r - 在 R 中使用 gridExtra 制作多个 PDF 页面时出现问题