本文整理汇总了Python中oauthlib.oauth2.TokenExpiredError方法的典型用法代码示例。如果您正苦于以下问题:Python oauth2.TokenExpiredError方法的具体用法?Python oauth2.TokenExpiredError怎么用?Python oauth2.TokenExpiredError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类oauthlib.oauth2
的用法示例。
在下文中一共展示了oauth2.TokenExpiredError方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: request
# 需要导入模块: from oauthlib import oauth2 [as 别名]
# 或者: from oauthlib.oauth2 import TokenExpiredError [as 别名]
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)
示例2: request
# 需要导入模块: from oauthlib import oauth2 [as 别名]
# 或者: from oauthlib.oauth2 import TokenExpiredError [as 别名]
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)
示例3: get_resource_with_auto_refresh
# 需要导入模块: from oauthlib import oauth2 [as 别名]
# 或者: from oauthlib.oauth2 import TokenExpiredError [as 别名]
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
示例4: __post
# 需要导入模块: from oauthlib import oauth2 [as 别名]
# 或者: from oauthlib.oauth2 import TokenExpiredError [as 别名]
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)
示例5: _get_response
# 需要导入模块: from oauthlib import oauth2 [as 别名]
# 或者: from oauthlib.oauth2 import TokenExpiredError [as 别名]
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
示例6: _request
# 需要导入模块: from oauthlib import oauth2 [as 别名]
# 或者: from oauthlib.oauth2 import TokenExpiredError [as 别名]
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)
示例7: _need_new_credentials
# 需要导入模块: from oauthlib import oauth2 [as 别名]
# 或者: from oauthlib.oauth2 import TokenExpiredError [as 别名]
def _need_new_credentials(response):
return response.status_code == 401 \
and response.headers.get('TokenExpiredError')
示例8: request
# 需要导入模块: from oauthlib import oauth2 [as 别名]
# 或者: from oauthlib.oauth2 import TokenExpiredError [as 别名]
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')
示例9: __call__
# 需要导入模块: from oauthlib import oauth2 [as 别名]
# 或者: from oauthlib.oauth2 import TokenExpiredError [as 别名]
def __call__(self, r):
try:
return self._add_token(r)
except TokenExpiredError:
self._refresh_token()
return self._add_token(r)
示例10: request
# 需要导入模块: from oauthlib import oauth2 [as 别名]
# 或者: from oauthlib.oauth2 import TokenExpiredError [as 别名]
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)
示例11: __get
# 需要导入模块: from oauthlib import oauth2 [as 别名]
# 或者: from oauthlib.oauth2 import TokenExpiredError [as 别名]
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)
示例12: _retrieve_items
# 需要导入模块: from oauthlib import oauth2 [as 别名]
# 或者: from oauthlib.oauth2 import TokenExpiredError [as 别名]
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 []
示例13: request
# 需要导入模块: from oauthlib import oauth2 [as 别名]
# 或者: from oauthlib.oauth2 import TokenExpiredError [as 别名]
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)
示例14: request
# 需要导入模块: from oauthlib import oauth2 [as 别名]
# 或者: from oauthlib.oauth2 import TokenExpiredError [as 别名]
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