首页 > 解决方案 > 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'))

标签: pythonpython-3.x

解决方案


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']

推荐阅读