如何在使用oauthlib.oauth2 fetch_token时捕获API失败

时间:2018-01-27 03:30:55

标签: python-3.x oauth error-handling

此库中的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

1 个答案:

答案 0 :(得分:1)

您可以添加一个“合规性挂钩”,它将在库尝试解析之前从请求传递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