gpt4 book ai didi

python-3.x - 如何在使用 oauthlib.oauth2 fetch_token 时捕获 API 失败

转载 作者:行者123 更新时间:2023-12-03 07:38:43 26 4
gpt4 key购买 nike

Python3 fetch_token此库中的方法在使用响应之前不会检查响应状态。如果它进行的 API 调用失败,那么响应将无效并且脚本崩溃。有什么我可以设置的,以便在库可以读取响应之前在非成功响应上引发异常?

import requests
from requests.auth import HTTPBasicAuth
from requests_oauthlib import OAuth2Session
from oauthlib.oauth2 import BackendApplicationClient
from oauthlib.oauth2 import OAuth2Error

AUTH_TOKEN_URL = "https://httpstat.us/500" # For testing
AUTH = HTTPBasicAuth("anID", "aSecret")
CLIENT = BackendApplicationClient(client_id="anID")
SCOPES = "retailer.orders.write"
MAX_API_RETRIES = 4

class MyApp:
def __init__(self):
"""Initialize ... and obtain initial auth token for request"""
self.client = OAuth2Session(client=CLIENT)
self.client.headers.update(
{
"Content-Type": "application/json"
}
)

self.__authenticate()

def __authenticate(self):
"""Obtain auth token."""
server_errors = 0

# This needs more work. fetch_token is not raising errors but failing
# instead.
while True:
try:
self.token = self.client.fetch_token(
token_url=AUTH_TOKEN_URL, auth=AUTH, scope=SCOPES
)
break

except (OAuth2Error, requests.exceptions.RequestException) as e:
server_errors = MyApp.__process_retry(
server_errors, e, None, MAX_API_RETRIES
)

@staticmethod
def __process_retry(errors, exception, resp, max_retries):
# Log and process retries
# ...

return errors + 1

MyApp() # Try it out

最佳答案

您可以添加一个“合规 Hook ”,它将通过 Response在库尝试解析它之前从请求中获取对象,如下所示:

def raise_on_error(response):
response.raise_for_status()
return response

self.client.register_compliance_hook('access_token_response', raise_on_error)

根据您可能出现错误的确切时间,您可能希望使用 'refresh_token_response' 执行此操作。和/或 'protected_request'以及。见 docstring for the register_compliance_hook method了解更多信息。

关于python-3.x - 如何在使用 oauthlib.oauth2 fetch_token 时捕获 API 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48472298/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com