Python oauthlib.oauth2.TokenExpiredError() Examples
The following are 15
code examples of oauthlib.oauth2.TokenExpiredError().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
oauthlib.oauth2
, or try the search function
.
Example #1
Source File: session.py From mendeley-python-sdk with Apache License 2.0 | 6 votes |
def request(self, method, url, data=None, headers=None, **kwargs): full_url = urljoin(self.host, url) if not headers: headers = {} headers['user-agent'] = self.__user_agent() try: rsp = self.__do_request(data, full_url, headers, kwargs, method) except TokenExpiredError: if self.refresher: self.refresher.refresh(self) rsp = self.__do_request(data, full_url, headers, kwargs, method) else: raise if rsp.ok: return rsp else: raise MendeleyApiException(rsp)
Example #2
Source File: abstractauth.py From pyLinky with Apache License 2.0 | 6 votes |
def request(self, path: str, arguments: Dict[str, str]) -> Response: """Make a request. We don't use the built-in token refresh mechanism of OAuth2 session because we want to allow overriding the token refresh logic. """ url = METERING_DATA_BASE_URL_PROD if (self.sandbox): url = METERING_DATA_BASE_URL_SANDBOX url = url + path # This header is required by v3/customers, v4/metering data is ok with the default */* headers = {'Accept': "application/json"} try: response = self._oauth.request("GET", url, params=arguments, headers=headers) if (response.status_code == 403): self._oauth.token = self.refresh_tokens() else: return response except TokenExpiredError: self._oauth.token = self.refresh_tokens() return self._oauth.request("GET", url, params=arguments, headers=headers)
Example #3
Source File: freesound_download.py From NeMo with Apache License 2.0 | 6 votes |
def get_resource_with_auto_refresh(session, download_url): """ Attempts download of audio with a token refresh if necessary. """ try: result = session.get(download_url) except TokenExpiredError as e: session = refresh_token(session) result = session.get(download_url) except Exception as e: result = None print(f"Skipping file {download_url} due to exception below\n\n") print(e) return result.content
Example #4
Source File: PyViCareService.py From PyViCare with Apache License 2.0 | 6 votes |
def __post(self,url,data): h = {"Content-Type":"application/json","Accept":"application/vnd.siren+json"} try: #if(self.oauth==None): # self.renewToken() j=self.oauth.post(url,data,headers=h) try: r=j.json() return r except JSONDecodeError: if j.status_code == 204: return json.loads("{\"statusCode\": 204, \"error\": \"None\", \"message\": \"SUCCESS\"}") else: return json.loads("{\"statusCode\":"+j.status_code+", \"error\": \"Unknown\", \"message\": \"UNKNOWN\"}") except TokenExpiredError as e: self.renewToken() return self._post(url,data)
Example #5
Source File: monzo_api.py From pymonzo with MIT License | 5 votes |
def _get_response(self, method, endpoint, params=None): """ Helper method to handle HTTP requests and catch API errors :param method: valid HTTP method :type method: str :param endpoint: API endpoint :type endpoint: str :param params: extra parameters passed with the request :type params: dict :returns: API response :rtype: Response """ url = urljoin(self.api_url, endpoint) try: response = getattr(self._session, method)(url, params=params) # Check if Monzo API returned HTTP 401, which could mean that the # token is expired if response.status_code == 401: raise TokenExpiredError except TokenExpiredError: # For some reason 'requests-oauthlib' automatic token refreshing # doesn't work so we do it here semi-manually self._refresh_oath_token() self._session = OAuth2Session( client_id=self._client_id, token=self._token, ) response = getattr(self._session, method)(url, params=params) if response.status_code != requests.codes.ok: raise MonzoAPIError( "Something went wrong: {}".format(response.json()) ) return response
Example #6
Source File: somfy_api.py From somfy-open-api with GNU General Public License v3.0 | 5 votes |
def _request(self, method: str, path: str, **kwargs: Any) -> Response: """Make a request. We don't use the built-in token refresh mechanism of OAuth2 session because we want to allow overriding the token refresh logic. """ url = BASE_URL + path try: return getattr(self._oauth, method)(url, **kwargs) except TokenExpiredError: self._oauth.token = self.refresh_tokens() return getattr(self._oauth, method)(url, **kwargs)
Example #7
Source File: util.py From exchangelib with BSD 2-Clause "Simplified" License | 5 votes |
def _need_new_credentials(response): return response.status_code == 401 \ and response.headers.get('TokenExpiredError')
Example #8
Source File: client.py From pokitdok-python with MIT License | 5 votes |
def request(self, path, method='get', data=None, files=None, **kwargs): """ General method for submitting an API request :param path: the API request path :param method: the http request method that should be used :param data: dictionary of request data that should be used for post/put requests :param files: dictionary of file information when the API accepts file uploads as input :param kwargs: optional keyword arguments to be relayed along as request parameters :return: """ if data and not files: headers = self.json_headers request_data = json.dumps(data) else: headers = self.base_headers request_data = data request_url = "{0}{1}".format(self.url_base, path) request_method = getattr(self.api_client, method) try: response = request_method(request_url, data=request_data, files=files, params=kwargs, headers=headers) self.status_code = response.status_code if self.status_code == 401: # if TokenExpiredError is not raised but it should have been, we'll raise it explicitly here # https://github.com/oauthlib/oauthlib/pull/506 could cause this code path to be followed. # this special handling can likely be removed once https://github.com/oauthlib/oauthlib/pull/506 # rolls into a new oauthlib release raise TokenExpiredError('Access Token has expired. Please, re-authenticate. ' 'Use auto_refresh=True to have your client auto refresh') return response.json() except (TokenUpdated, TokenExpiredError): if self.auto_refresh: # Re-fetch token and try request again self.fetch_access_token(self.code) return request_method(request_url, data=request_data, files=files, params=kwargs, headers=headers).json() else: self.status_code = 401 # UNAUTHORIZED raise TokenExpiredError('Access Token has expired. Please, re-authenticate. ' 'Use auto_refresh=True to have your client auto refresh')
Example #9
Source File: oauth.py From neptune-client with Apache License 2.0 | 5 votes |
def __call__(self, r): try: return self._add_token(r) except TokenExpiredError: self._refresh_token() return self._add_token(r)
Example #10
Source File: oauth2_session.py From Tautulli with GNU General Public License v3.0 | 5 votes |
def request(self, method, url, data=None, headers=None, withhold_token=False, **kwargs): """Intercept all requests and add the OAuth 2 token if present.""" if not is_secure_transport(url): raise InsecureTransportError() if self.token and not withhold_token: log.debug('Invoking %d protected resource request hooks.', len(self.compliance_hook['protected_request'])) for hook in self.compliance_hook['protected_request']: log.debug('Invoking hook %s.', hook) url, headers, data = hook(url, headers, data) log.debug('Adding token %s to request.', self.token) try: url, headers, data = self._client.add_token(url, http_method=method, body=data, headers=headers) # Attempt to retrieve and save new access token if expired except TokenExpiredError: if self.auto_refresh_url: log.debug('Auto refresh is set, attempting to refresh at %s.', self.auto_refresh_url) token = self.refresh_token(self.auto_refresh_url, **kwargs) if self.token_updater: log.debug('Updating token to %s using %s.', token, self.token_updater) self.token_updater(token) url, headers, data = self._client.add_token(url, http_method=method, body=data, headers=headers) else: raise TokenUpdated(token) else: raise log.debug('Requesting url %s using method %s.', url, method) log.debug('Supplying headers %s and data %s', headers, data) log.debug('Passing through key word arguments %s.', kwargs) return super(OAuth2Session, self).request(method, url, headers=headers, data=data, **kwargs)
Example #11
Source File: PyViCareService.py From PyViCare with Apache License 2.0 | 5 votes |
def __get(self,url): try: #if(self.oauth==None): # self.renewToken() logger.debug(self.oauth) r=self.oauth.get(url).json() logger.debug("Response to get request: "+str(r)) if(r=={'error': 'EXPIRED TOKEN'}): logger.warning("Abnormal token, renewing") # apparently forged tokens TODO investigate self.renewToken() r = self.oauth.get(url).json() return r except TokenExpiredError as e: self.renewToken() return self.__get(url)
Example #12
Source File: unimatrix.py From pygraphistry with BSD 3-Clause "New" or "Revised" License | 4 votes |
def _retrieve_items(self, num_items, params, item_type="events", page=0): """ Retrieve num_items from item_type :param int num_items: Max items to retrieve :param dict params: Additional params dictionary :param string item_type: 'events' or 'alarms' :returns list: list of items """ try: page = page retries = 0 item_list = [] remaining = num_items list_name = "eventResourceList" if item_type == "events" else "alarms" if not params: params = {} # Loop if num_items > MAX_EVENTS as that is the max number of items in one page while remaining and page < (num_items//MAX_EVENTS+1) and retries < MAX_RETRIES: params["page"] = page params["size"] = min(remaining, MAX_EVENTS) #response = self.client.get(self.url+item_type, params=params, verify=False) response = self.client.get(self.url+item_type, params=params) if response.status_code == 200: self.log.warning("Got 200. Page info: {}.".format(response.json()['page'])) page += 1 retries = 0 items = response.json()['_embedded'][list_name] item_list.extend(items) remaining = min(remaining, response.json()['page']['totalElements']) remaining -= len(items) else: retries += 1 self.log.error("Got response {response.status_code} for page {params['page']} " + \ "and size {params['size']}. Attempt {retries}.") time.sleep(1) return item_list except TokenExpiredError as e: self.log.error("ERROR: {e}. Token Expired.") self.client = self._connect() return self._retrieve_items(remaining, params, item_type, page) except KeyError as e: self.log.error("ERROR: {e}. {response.json()['_links']}") return []
Example #13
Source File: oauth2_session.py From Requester with MIT License | 4 votes |
def request(self, method, url, data=None, headers=None, withhold_token=False, client_id=None, client_secret=None, **kwargs): """Intercept all requests and add the OAuth 2 token if present.""" if not is_secure_transport(url): raise InsecureTransportError() if self.token and not withhold_token: log.debug('Invoking %d protected resource request hooks.', len(self.compliance_hook['protected_request'])) for hook in self.compliance_hook['protected_request']: log.debug('Invoking hook %s.', hook) url, headers, data = hook(url, headers, data) log.debug('Adding token %s to request.', self.token) try: url, headers, data = self._client.add_token(url, http_method=method, body=data, headers=headers) # Attempt to retrieve and save new access token if expired except TokenExpiredError: if self.auto_refresh_url: log.debug('Auto refresh is set, attempting to refresh at %s.', self.auto_refresh_url) # We mustn't pass auth twice. auth = kwargs.pop('auth', None) if client_id and client_secret and (auth is None): log.debug('Encoding client_id "%s" with client_secret as Basic auth credentials.', client_id) auth = requests.auth.HTTPBasicAuth(client_id, client_secret) token = self.refresh_token( self.auto_refresh_url, auth=auth, **kwargs ) if self.token_updater: log.debug('Updating token to %s using %s.', token, self.token_updater) self.token_updater(token) url, headers, data = self._client.add_token(url, http_method=method, body=data, headers=headers) else: raise TokenUpdated(token) else: raise log.debug('Requesting url %s using method %s.', url, method) log.debug('Supplying headers %s and data %s', headers, data) log.debug('Passing through key word arguments %s.', kwargs) return super(OAuth2Session, self).request(method, url, headers=headers, data=data, **kwargs)
Example #14
Source File: oauth.py From photoframe with GNU General Public License v3.0 | 4 votes |
def request(self, uri, destination=None, params=None, data=None, usePost=False): ret = RequestResult() result = None stream = destination != None tries = 0 while tries < 5: try: try: auth = self.getSession() if auth is None: logging.error('Unable to get OAuth session, probably expired') raise RequestExpiredToken if usePost: result = auth.post(uri, stream=stream, params=params, json=data, timeout=180) else: result = auth.get(uri, stream=stream, params=params, timeout=180) if result is not None: break except TokenExpiredError: auth = self.getSession(True) if auth is None: logging.error('Unable to get OAuth session, probably expired') raise RequestExpiredToken if usePost: result = auth.post(uri, stream=stream, params=params, json=data, timeout=180) else: result = auth.get(uri, stream=stream, params=params, timeout=180) if result is not None: break except InvalidGrantError: logging.error('Token is no longer valid, need to re-authenticate') raise RequestInvalidToken except: logging.exception('Issues downloading') time.sleep(tries / 10) # Back off 10, 20, ... depending on tries tries += 1 logging.warning('Retrying again, attempt #%d', tries) if tries == 5: logging.error('Failed to download due to network issues') raise RequestNoNetwork if destination is not None: try: with open(destination, 'wb') as handle: for chunk in result.iter_content(chunk_size=512): if chunk: # filter out keep-alive new chunks handle.write(chunk) ret.setResult(RequestResult.SUCCESS).setHTTPCode(result.status_code) ret.setHeaders(result.headers) except: logging.exception('Failed to download %s' % uri) ret.setResult(RequestResult.FAILED_SAVING) else: ret.setResult(RequestResult.SUCCESS).setHTTPCode(result.status_code) ret.setHeaders(result.headers) ret.setContent(result.content) return ret
Example #15
Source File: oauth2_session.py From bazarr with GNU General Public License v3.0 | 4 votes |
def request(self, method, url, data=None, headers=None, withhold_token=False, client_id=None, client_secret=None, **kwargs): """Intercept all requests and add the OAuth 2 token if present.""" if not is_secure_transport(url): raise InsecureTransportError() if self.token and not withhold_token: log.debug('Invoking %d protected resource request hooks.', len(self.compliance_hook['protected_request'])) for hook in self.compliance_hook['protected_request']: log.debug('Invoking hook %s.', hook) url, headers, data = hook(url, headers, data) log.debug('Adding token %s to request.', self.token) try: url, headers, data = self._client.add_token(url, http_method=method, body=data, headers=headers) # Attempt to retrieve and save new access token if expired except TokenExpiredError: if self.auto_refresh_url: log.debug('Auto refresh is set, attempting to refresh at %s.', self.auto_refresh_url) # We mustn't pass auth twice. auth = kwargs.pop('auth', None) if client_id and client_secret and (auth is None): log.debug('Encoding client_id "%s" with client_secret as Basic auth credentials.', client_id) auth = requests.auth.HTTPBasicAuth(client_id, client_secret) token = self.refresh_token( self.auto_refresh_url, auth=auth, **kwargs ) if self.token_updater: log.debug('Updating token to %s using %s.', token, self.token_updater) self.token_updater(token) url, headers, data = self._client.add_token(url, http_method=method, body=data, headers=headers) else: raise TokenUpdated(token) else: raise log.debug('Requesting url %s using method %s.', url, method) log.debug('Supplying headers %s and data %s', headers, data) log.debug('Passing through key word arguments %s.', kwargs) return super(OAuth2Session, self).request(method, url, headers=headers, data=data, **kwargs)