requests / requests-oauthlib

OAuthlib support for Python-Requests!
https://requests-oauthlib.readthedocs.org/
ISC License
1.71k stars 422 forks source link

Unable to catch TokenUpdated when subclassing #421

Open ace-e4s opened 4 years ago

ace-e4s commented 4 years ago

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?!