Skip to content

feat: use raise ... from ... idiom #686

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions firebase_admin/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,11 +175,13 @@ def _load_from_environment(self):
with open(config_file, 'r') as json_file:
json_str = json_file.read()
except Exception as err:
raise ValueError('Unable to read file {}. {}'.format(config_file, err))
raise ValueError('Unable to read file {}. {}'.format(config_file, err)) from err
try:
json_data = json.loads(json_str)
except Exception as err:
raise ValueError('JSON string "{0}" is not valid json. {1}'.format(json_str, err))
raise ValueError(
'JSON string "{0}" is not valid json. {1}'.format(json_str, err)
) from err
return {k: v for k, v in json_data.items() if k in _CONFIG_VALID_KEYS}


Expand Down
2 changes: 1 addition & 1 deletion firebase_admin/_auth_providers.py
Original file line number Diff line number Diff line change
Expand Up @@ -379,7 +379,7 @@ def _make_request(self, method, path, **kwargs):
try:
return self.http_client.body(method, url, **kwargs)
except requests.exceptions.RequestException as error:
raise _auth_utils.handle_auth_backend_error(error)
raise _auth_utils.handle_auth_backend_error(error) from error


def _validate_oidc_provider_id(provider_id):
Expand Down
14 changes: 7 additions & 7 deletions firebase_admin/_token_gen.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ def signing_provider(self):
'Failed to determine service account: {0}. Make sure to initialize the SDK '
'with service account credentials or specify a service account ID with '
'iam.serviceAccounts.signBlob permission. Please refer to {1} for more '
'details on creating custom tokens.'.format(error, url))
'details on creating custom tokens.'.format(error, url)) from error
return self._signing_provider

def create_custom_token(self, uid, developer_claims=None, tenant_id=None):
Expand Down Expand Up @@ -203,7 +203,7 @@ def create_custom_token(self, uid, developer_claims=None, tenant_id=None):
return jwt.encode(signing_provider.signer, payload, header=header)
except google.auth.exceptions.TransportError as error:
msg = 'Failed to sign custom token. {0}'.format(error)
raise TokenSignError(msg, error)
raise TokenSignError(msg, error) from error


def create_session_cookie(self, id_token, expires_in):
Expand Down Expand Up @@ -233,7 +233,7 @@ def create_session_cookie(self, id_token, expires_in):
try:
body, http_resp = self.http_client.body_and_response('post', url, json=payload)
except requests.exceptions.RequestException as error:
raise _auth_utils.handle_auth_backend_error(error)
raise _auth_utils.handle_auth_backend_error(error) from error
else:
if not body or not body.get('sessionCookie'):
raise _auth_utils.UnexpectedResponseError(
Expand Down Expand Up @@ -397,19 +397,19 @@ def verify(self, token, request):
verified_claims['uid'] = verified_claims['sub']
return verified_claims
except google.auth.exceptions.TransportError as error:
raise CertificateFetchError(str(error), cause=error)
raise CertificateFetchError(str(error), cause=error) from error
except ValueError as error:
if 'Token expired' in str(error):
raise self._expired_token_error(str(error), cause=error)
raise self._invalid_token_error(str(error), cause=error)
raise self._expired_token_error(str(error), cause=error) from error
raise self._invalid_token_error(str(error), cause=error) from error

def _decode_unverified(self, token):
try:
header = jwt.decode_header(token)
payload = jwt.decode(token, verify=False)
return header, payload
except ValueError as error:
raise self._invalid_token_error(str(error), cause=error)
raise self._invalid_token_error(str(error), cause=error) from error


class TokenSignError(exceptions.UnknownError):
Expand Down
2 changes: 1 addition & 1 deletion firebase_admin/_user_mgt.py
Original file line number Diff line number Diff line change
Expand Up @@ -841,7 +841,7 @@ def _make_request(self, method, path, **kwargs):
try:
return self.http_client.body_and_response(method, url, **kwargs)
except requests.exceptions.RequestException as error:
raise _auth_utils.handle_auth_backend_error(error)
raise _auth_utils.handle_auth_backend_error(error) from error


class _UserIterator(_auth_utils.PageIterator):
Expand Down
2 changes: 1 addition & 1 deletion firebase_admin/app_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ def _decode_and_verify(self, token: str, signing_key: str):
except InvalidTokenError as exception:
raise ValueError(
f'Decoding App Check token failed. Error: {exception}'
)
) from exception

audience = payload.get('aud')
if not isinstance(audience, list) or self._scoped_project_id not in audience:
Expand Down
2 changes: 1 addition & 1 deletion firebase_admin/credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ def __init__(self, cert):
json_data, scopes=_scopes)
except ValueError as error:
raise ValueError('Failed to initialize a certificate credential. '
'Caused by: "{0}"'.format(error))
'Caused by: "{0}"'.format(error)) from error

@property
def project_id(self):
Expand Down
6 changes: 3 additions & 3 deletions firebase_admin/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@ def set_if_unchanged(self, expected_etag, value):
snapshot = http_response.json()
return False, snapshot, etag

raise error
raise

def push(self, value=''):
"""Creates a new child node.
Expand Down Expand Up @@ -470,7 +470,7 @@ def _listen_with_session(self, callback, session=None):
sse = _sseclient.SSEClient(url, session)
return ListenerRegistration(callback, sse)
except requests.exceptions.RequestException as error:
raise _Client.handle_rtdb_error(error)
raise _Client.handle_rtdb_error(error) from error


class Query:
Expand Down Expand Up @@ -928,7 +928,7 @@ def request(self, method, url, **kwargs):
try:
return super(_Client, self).request(method, url, **kwargs)
except requests.exceptions.RequestException as error:
raise _Client.handle_rtdb_error(error)
raise _Client.handle_rtdb_error(error) from error

def create_listener_session(self):
return _sseclient.KeepAuthSession(self.credential)
Expand Down
2 changes: 1 addition & 1 deletion firebase_admin/instance_id.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ def delete_instance_id(self, instance_id):
self._client.request('delete', path)
except requests.exceptions.RequestException as error:
msg = self._extract_message(instance_id, error)
raise _utils.handle_requests_error(error, msg)
raise _utils.handle_requests_error(error, msg) from error

def _extract_message(self, instance_id, error):
if error.response is None:
Expand Down
6 changes: 3 additions & 3 deletions firebase_admin/messaging.py
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,7 @@ def send(self, message, dry_run=False):
json=data
)
except requests.exceptions.RequestException as error:
raise self._handle_fcm_error(error)
raise self._handle_fcm_error(error) from error
else:
return resp['name']

Expand Down Expand Up @@ -390,7 +390,7 @@ def batch_callback(_, response, error):
try:
batch.execute()
except Exception as error:
raise self._handle_batch_error(error)
raise self._handle_batch_error(error) from error
else:
return BatchResponse(responses)

Expand Down Expand Up @@ -421,7 +421,7 @@ def make_topic_management_request(self, tokens, topic, operation):
headers=_MessagingService.IID_HEADERS
)
except requests.exceptions.RequestException as error:
raise self._handle_iid_error(error)
raise self._handle_iid_error(error) from error
else:
return TopicManagementResponse(resp)

Expand Down
12 changes: 6 additions & 6 deletions firebase_admin/ml.py
Original file line number Diff line number Diff line change
Expand Up @@ -855,7 +855,7 @@ def get_operation(self, op_name):
try:
return self._operation_client.body('get', url=op_name)
except requests.exceptions.RequestException as error:
raise _utils.handle_platform_error_from_requests(error)
raise _utils.handle_platform_error_from_requests(error) from error

def _exponential_backoff(self, current_attempt, stop_time):
"""Sleeps for the appropriate amount of time. Or throws deadline exceeded."""
Expand Down Expand Up @@ -932,7 +932,7 @@ def create_model(self, model):
return self.handle_operation(
self._client.body('post', url='models', json=model.as_dict(for_upload=True)))
except requests.exceptions.RequestException as error:
raise _utils.handle_platform_error_from_requests(error)
raise _utils.handle_platform_error_from_requests(error) from error

def update_model(self, model, update_mask=None):
_validate_model(model, update_mask)
Expand All @@ -943,7 +943,7 @@ def update_model(self, model, update_mask=None):
return self.handle_operation(
self._client.body('patch', url=path, json=model.as_dict(for_upload=True)))
except requests.exceptions.RequestException as error:
raise _utils.handle_platform_error_from_requests(error)
raise _utils.handle_platform_error_from_requests(error) from error

def set_published(self, model_id, publish):
_validate_model_id(model_id)
Expand All @@ -961,7 +961,7 @@ def get_model(self, model_id):
try:
return self._client.body('get', url='models/{0}'.format(model_id))
except requests.exceptions.RequestException as error:
raise _utils.handle_platform_error_from_requests(error)
raise _utils.handle_platform_error_from_requests(error) from error

def list_models(self, list_filter, page_size, page_token):
""" lists Firebase ML models."""
Expand All @@ -982,11 +982,11 @@ def list_models(self, list_filter, page_size, page_token):
try:
return self._client.body('get', url=path)
except requests.exceptions.RequestException as error:
raise _utils.handle_platform_error_from_requests(error)
raise _utils.handle_platform_error_from_requests(error) from error

def delete_model(self, model_id):
_validate_model_id(model_id)
try:
self._client.body('delete', url='models/{0}'.format(model_id))
except requests.exceptions.RequestException as error:
raise _utils.handle_platform_error_from_requests(error)
raise _utils.handle_platform_error_from_requests(error) from error
2 changes: 1 addition & 1 deletion firebase_admin/project_management.py
Original file line number Diff line number Diff line change
Expand Up @@ -661,4 +661,4 @@ def _body_and_response(self, method, url, json=None):
try:
return self._client.body_and_response(method=method, url=url, json=json)
except requests.exceptions.RequestException as error:
raise _utils.handle_platform_error_from_requests(error)
raise _utils.handle_platform_error_from_requests(error) from error
10 changes: 5 additions & 5 deletions firebase_admin/tenant_mgt.py
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ def get_tenant(self, tenant_id):
try:
body = self.client.body('get', '/tenants/{0}'.format(tenant_id))
except requests.exceptions.RequestException as error:
raise _auth_utils.handle_auth_backend_error(error)
raise _auth_utils.handle_auth_backend_error(error) from error
else:
return Tenant(body)

Expand All @@ -286,7 +286,7 @@ def create_tenant(
try:
body = self.client.body('post', '/tenants', json=payload)
except requests.exceptions.RequestException as error:
raise _auth_utils.handle_auth_backend_error(error)
raise _auth_utils.handle_auth_backend_error(error) from error
else:
return Tenant(body)

Expand Down Expand Up @@ -316,7 +316,7 @@ def update_tenant(
try:
body = self.client.body('patch', url, json=payload, params=params)
except requests.exceptions.RequestException as error:
raise _auth_utils.handle_auth_backend_error(error)
raise _auth_utils.handle_auth_backend_error(error) from error
else:
return Tenant(body)

Expand All @@ -329,7 +329,7 @@ def delete_tenant(self, tenant_id):
try:
self.client.request('delete', '/tenants/{0}'.format(tenant_id))
except requests.exceptions.RequestException as error:
raise _auth_utils.handle_auth_backend_error(error)
raise _auth_utils.handle_auth_backend_error(error) from error

def list_tenants(self, page_token=None, max_results=_MAX_LIST_TENANTS_RESULTS):
"""Retrieves a batch of tenants."""
Expand All @@ -349,7 +349,7 @@ def list_tenants(self, page_token=None, max_results=_MAX_LIST_TENANTS_RESULTS):
try:
return self.client.body('get', '/tenants', params=payload)
except requests.exceptions.RequestException as error:
raise _auth_utils.handle_auth_backend_error(error)
raise _auth_utils.handle_auth_backend_error(error) from error


class ListTenantsPage:
Expand Down