requests-oauthlib icon indicating copy to clipboard operation
requests-oauthlib copied to clipboard

Unable to catch TokenUpdated when subclassing

Open ali-cetin-4ss opened this issue 5 years ago • 0 comments

I needed to overwrite the refresh_token method as my backend do not provide a refresh token. Instead, fetch_token is called. But since I do not want a token_updater, I just want to catch and ignore the TokenUpdated exception. Howerver, I'm unable to catch the exception; it is raised when the entire method call is completed. I can't wrap my head around what's actually going on here!

Workaround: provide a dummy token_updater, e.g. lambda token: None

Example:

import time

from oauthlib.oauth2 import BackendApplicationClient
from requests.auth import HTTPBasicAuth
from requests_oauthlib import OAuth2Session, TokenUpdated


client_id = "my_client_id"
client_secret = "my_client_secret"
token_url = "my_token_url"
scope = ["some_scope"]

url ="my_url"


class MyOAuth2Session(OAuth2Session):

    def refresh_token(self, *args, **kwargs):
        # catch  and ignore TokenUpdated exception since token_updater is not provided
        try:
            token = super().fetch_token(token_url=token_url, auth=auth, scope=scope)
        except:
            pass

auth = HTTPBasicAuth(client_id, client_secret)
client = BackendApplicationClient(client_id=client_id)
oauth = MyOAuth2Session(client=client, auto_refresh_url=token_url)
token = oauth.fetch_token(token_url=token_url, auth=auth, scope=scope)


oauth._client._expires_at = time.time() - 100
response = oauth.request("GET", url)  # TokenUpdated raise?!

ali-cetin-4ss avatar Aug 17 '20 11:08 ali-cetin-4ss