Skip to content

Commit

Permalink
Fixing google api error parsing. Adding error handling for the CLI
Browse files Browse the repository at this point in the history
  • Loading branch information
eduardogr authored and egarcia committed Jan 20, 2021
1 parent 880fafa commit d71573a
Show file tree
Hide file tree
Showing 3 changed files with 96 additions and 40 deletions.
83 changes: 52 additions & 31 deletions googledrive/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from googledrive.mappers import GoogleFileDictToGoogleFile
from googledrive.exceptions import MissingGoogleDriveFolderException
from googledrive.exceptions import MissingGoogleDriveFileException
from googledrive.exceptions import GoogleApiClientHttpErrorException

class GoogleAuth:

Expand Down Expand Up @@ -109,9 +110,13 @@ def create_folder(self, name):
self.DRIVE_SERVICE_ID,
self.DRIVE_SERVICE_VERSION
)
folder = drive_service.files().create(
body=file_metadata,
fields=self.FIELDS_BASIC_FILE_METADATA).execute()
try:
folder = drive_service.files().create(
body=file_metadata,
fields=self.FIELDS_BASIC_FILE_METADATA).execute()
except HttpError as e:
http_error = GoogleApiClientHttpErrorBuilder().from_http_error(e)
raise GoogleApiClientHttpErrorException(http_error)

return GoogleFileDictToGoogleFile().google_file_dict_to_google_file(folder)

Expand All @@ -120,11 +125,15 @@ def update_file_parent(self, file_id, current_parent, new_parent):
self.DRIVE_SERVICE_ID,
self.DRIVE_SERVICE_VERSION
)
file_update = drive_service.files().update(
fileId=file_id,
addParents=new_parent,
removeParents=current_parent)
file_update.execute()
try:
file_update = drive_service.files().update(
fileId=file_id,
addParents=new_parent,
removeParents=current_parent)
file_update.execute()
except HttpError as e:
http_error = GoogleApiClientHttpErrorBuilder().from_http_error(e)
raise GoogleApiClientHttpErrorException(http_error)

def get_file_from_id(self, file_id: str):
drive_service = super().get_service(
Expand All @@ -146,13 +155,17 @@ def list_files(self, page_token: str, query: str):
self.DRIVE_SERVICE_ID,
self.DRIVE_SERVICE_VERSION
)
response = drive_service.files().list(
q=query,
pageSize=100,
spaces='drive',
corpora='user',
fields=f'nextPageToken, files({self.FIELDS_FILE_METADATA})',
pageToken=page_token).execute()
try:
response = drive_service.files().list(
q=query,
pageSize=100,
spaces='drive',
corpora='user',
fields=f'nextPageToken, files({self.FIELDS_FILE_METADATA})',
pageToken=page_token).execute()
except HttpError as e:
http_error = GoogleApiClientHttpErrorBuilder().from_http_error(e)
raise GoogleApiClientHttpErrorException(http_error)

google_files = [
GoogleFileDictToGoogleFile().google_file_dict_to_google_file(google_file_dict)
Expand All @@ -166,28 +179,36 @@ def copy_file(self, file_id, new_filename):
self.DRIVE_SERVICE_ID,
self.DRIVE_SERVICE_VERSION
)
results = drive_service.files().copy(
fileId=file_id,
body={
'name': new_filename,
'mimeType': self.MIMETYPE_DOCUMENT
}
).execute()
return results.get('id')
try:
results = drive_service.files().copy(
fileId=file_id,
body={
'name': new_filename,
'mimeType': self.MIMETYPE_DOCUMENT
}
).execute()
return results.get('id')
except HttpError as e:
http_error = GoogleApiClientHttpErrorBuilder().from_http_error(e)
raise GoogleApiClientHttpErrorException(http_error)

def create_permission(self, document_id: str, role: str, email_address):
drive_service = super().get_service(
self.DRIVE_SERVICE_ID,
self.DRIVE_SERVICE_VERSION
)
drive_service.permissions().create(
fileId=document_id,
body={
'type': 'user',
'emailAddress': email_address,
'role': role,
}
).execute()
try:
drive_service.permissions().create(
fileId=document_id,
body={
'type': 'user',
'emailAddress': email_address,
'role': role,
}
).execute()
except HttpError as e:
http_error = GoogleApiClientHttpErrorBuilder().from_http_error(e)
raise GoogleApiClientHttpErrorException(http_error)

#
# High level API access
Expand Down
45 changes: 39 additions & 6 deletions googledrive/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

from googledrive.api import GoogleAuth
from googledrive.api import GoogleDrive
from googledrive.exceptions import GoogleApiClientHttpErrorException

class Config:
# If modifying these scopes, delete the file token.pickle.
Expand Down Expand Up @@ -30,8 +31,19 @@ def login(credentials):
@click.argument('credentials', envvar='CREDENTIALS', type=click.Path(exists=True))
def ls(credentials, path):
"""List directory contents"""
google_drive = GoogleDrive(credentials, Config.SCOPES)
files = google_drive.googledrive_ls(path)
try:
google_drive = GoogleDrive(credentials, Config.SCOPES)
files = google_drive.googledrive_ls(path)
except GoogleApiClientHttpErrorException as e:
error = e.get_google_api_client_http_error()
print(f'An http exception occured requesting google\'s API:\n')
print(f' - Code: {error.code}')
print(f' - Message: {error.message}')
print(f' - Status: {error.status}')
print(f' - Details: {error.details}')
print(f' - Errors: {error.errors}\n')
return

for file in files:
print(f'- {file}') # TODO: nice print

Expand All @@ -40,8 +52,18 @@ def ls(credentials, path):
@click.argument('credentials', envvar='CREDENTIALS', type=click.Path(exists=True))
def get(id, credentials):
"""Get file metadata"""
google_drive = GoogleDrive(credentials, Config.SCOPES)
google_file = google_drive.get_file_from_id(id)
try:
google_drive = GoogleDrive(credentials, Config.SCOPES)
google_file = google_drive.get_file_from_id(id)
except GoogleApiClientHttpErrorException as e:
error = e.get_google_api_client_http_error()
print(f'An http exception occured requesting google\'s API:\n')
print(f' - Code: {error.code}')
print(f' - Message: {error.message}')
print(f' - Status: {error.status}')
print(f' - Details: {error.details}')
print(f' - Errors: {error.errors}\n')
return

print('\nFile Metadata:\n==')
print(f'id: {google_file.id}')
Expand All @@ -58,8 +80,19 @@ def get(id, credentials):
@click.argument('credentials', envvar='CREDENTIALS', type=click.Path(exists=True))
def mkdir(credentials, name):
"""Make directory"""
google_drive = GoogleDrive(credentials, Config.SCOPES)
folder = google_drive.create_folder(name)
try:
google_drive = GoogleDrive(credentials, Config.SCOPES)
folder = google_drive.create_folder(name)
except GoogleApiClientHttpErrorException as e:
error = e.get_google_api_client_http_error()
print(f'An http exception occured requesting google\'s API:\n')
print(f' - Code: {error.code}')
print(f' - Message: {error.message}')
print(f' - Status: {error.status}')
print(f' - Details: {error.details}')
print(f' - Errors: {error.errors}\n')
return

print(folder) # TODO: nice print

@click.group()
Expand Down
8 changes: 5 additions & 3 deletions googledrive/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,12 @@ def __str__(self):
@dataclass
class GoogleApiClientHttpError:

def __init__(self, code, message, status, details):
def __init__(self, code, message, status, details, errors):
self.code = code
self.message = message
self.status = status
self.details = details
self.errors = errors

class GoogleApiClientHttpErrorBuilder:

Expand All @@ -52,6 +53,7 @@ def from_http_error(self, http_error: HttpError):
return GoogleApiClientHttpError(
error['code'],
error['message'],
error['status'],
error['details'] if 'details' in error else []
error.get('status', ''),
error.get('details', []),
error.get('errors', [])
)

0 comments on commit d71573a

Please sign in to comment.