Skip to content

Commit 1fdbc90

Browse files
committed
Added try except and comments
1 parent cf15bd4 commit 1fdbc90

4 files changed

Lines changed: 73 additions & 66 deletions

File tree

drive/activity-v2/quickstart.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
from __future__ import print_function
1717
import os.path
1818
from googleapiclient.discovery import build
19+
from googleapiclient.errors import HttpError
1920
from google_auth_oauthlib.flow import InstalledAppFlow
2021
from google.auth.transport.requests import Request
2122
from google.oauth2.credentials import Credentials
@@ -72,8 +73,9 @@ def main():
7273
# Print the action occurred on drive with actor, target item and timestamp
7374
print(u'{0}: {1}, {2}, {3}'.format(time, action, actor_name, target_name))
7475

75-
except Exception as error:
76-
print('An error occurred: %s' % error)
76+
except HttpError as error:
77+
# TODO(developer) - Handleerrors from drive activity API.
78+
print(f'An error occurred: {error}')
7779

7880

7981
# Returns the name of a set property in an object, or else "unknown".

drive/driveapp/main.py

Lines changed: 31 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import six
1010
import httplib2
1111
from googleapiclient.discovery import build
12+
from googleapiclient.errors import HttpError
1213
import googleapiclient.http
1314
import oauth2client.client
1415

@@ -27,42 +28,44 @@
2728
TITLE = 'My New Text Document'
2829
DESCRIPTION = 'A shiny new text document about hello world.'
2930

31+
3032
# Perform OAuth2.0 authorization flow.
31-
try:
32-
flow = oauth2client.client.flow_from_clientsecrets(
33-
CLIENT_SECRETS, OAUTH2_SCOPE)
34-
flow.redirect_uri = oauth2client.client.OOB_CALLBACK_URN
35-
authorize_url = flow.step1_get_authorize_url()
36-
print('Go to the following link in your browser: ' + authorize_url)
37-
# `six` library supports Python2 and Python3 without redefining builtin input()
38-
code = six.moves.input('Enter verification code: ').strip()
39-
credentials = flow.step2_exchange(code)
33+
flow = oauth2client.client.flow_from_clientsecrets(
34+
CLIENT_SECRETS, OAUTH2_SCOPE)
35+
flow.redirect_uri = oauth2client.client.OOB_CALLBACK_URN
36+
authorize_url = flow.step1_get_authorize_url()
37+
print('Go to the following link in your browser: ' + authorize_url)
38+
# `six` library supports Python2 and Python3 without redefining builtin input()
39+
code = six.moves.input('Enter verification code: ').strip()
40+
credentials = flow.step2_exchange(code)
4041

41-
# Create an authorized Drive API client.
42-
http = httplib2.Http()
43-
credentials.authorize(http)
44-
drive_service = build('drive', 'v2', http=http)
42+
# Create an authorized Drive API client.
43+
http = httplib2.Http()
44+
credentials.authorize(http)
45+
drive_service = build('drive', 'v2', http=http)
4546

46-
# Insert a file. Files are comprised of contents and metadata.
47-
# MediaFileUpload abstracts uploading file contents from a file on disk.
48-
media_body = googleapiclient.http.MediaFileUpload(
49-
FILENAME,
50-
mimetype=MIMETYPE,
51-
resumable=True
52-
)
53-
# The body contains the metadata for the file.
54-
body = {
55-
'title': TITLE,
56-
'description': DESCRIPTION,
57-
}
47+
# Insert a file. Files are comprised of contents and metadata.
48+
# MediaFileUpload abstracts uploading file contents from a file on disk.
49+
media_body = googleapiclient.http.MediaFileUpload(
50+
FILENAME,
51+
mimetype=MIMETYPE,
52+
resumable=True
53+
)
54+
# The body contains the metadata for the file.
55+
body = {
56+
'title': TITLE,
57+
'description': DESCRIPTION,
58+
}
5859

59-
# Perform the request and print the result.
60+
# Perform the request and print the result.
61+
try:
6062
new_file = drive_service.files().insert(
6163
body=body, media_body=media_body).execute()
6264
file_title = new_file.get('title')
6365
file_desc = new_file.get('description')
6466
if file_title == TITLE and file_desc == DESCRIPTION:
6567
print(f"File is uploaded \nTitle : {file_title} \nDescription : {file_desc}")
6668

67-
except Exception as error:
68-
print('An error occurred: %s' % error)
69+
except HttpError as error:
70+
# TODO(developer) - Handleerrors from drive API.
71+
print(f'An error occurred: {error}')

drive/quickstart/quickstart.py

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
from __future__ import print_function
1717
import os.path
1818
from googleapiclient.discovery import build
19+
from googleapiclient.errors import HttpError
1920
from google_auth_oauthlib.flow import InstalledAppFlow
2021
from google.auth.transport.requests import Request
2122
from google.oauth2.credentials import Credentials
@@ -32,24 +33,23 @@ def main():
3233
# The file token.json stores the user's access and refresh tokens, and is
3334
# created automatically when the authorization flow completes for the first
3435
# time.
35-
try:
36-
if os.path.exists('token.json'):
37-
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
38-
# If there are no (valid) credentials available, let the user log in.
39-
if not creds or not creds.valid:
40-
if creds and creds.expired and creds.refresh_token:
41-
creds.refresh(Request())
42-
else:
43-
flow = InstalledAppFlow.from_client_secrets_file(
44-
'credentials.json', SCOPES)
45-
creds = flow.run_local_server(port=0)
46-
# Save the credentials for the next run
47-
with open('token.json', 'w') as token:
48-
token.write(creds.to_json())
36+
if os.path.exists('token.json'):
37+
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
38+
# If there are no (valid) credentials available, let the user log in.
39+
if not creds or not creds.valid:
40+
if creds and creds.expired and creds.refresh_token:
41+
creds.refresh(Request())
42+
else:
43+
flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
44+
creds = flow.run_local_server(port=0)
45+
# Save the credentials for the next run
46+
with open('token.json', 'w') as token:
47+
token.write(creds.to_json())
4948

50-
service = build('drive', 'v3', credentials=creds)
49+
service = build('drive', 'v3', credentials=creds)
5150

52-
# Call the Drive v3 API
51+
# Call the Drive v3 API
52+
try:
5353
results = service.files().list(
5454
pageSize=10, fields="nextPageToken, files(id, name)").execute()
5555
items = results.get('files', [])
@@ -62,8 +62,9 @@ def main():
6262
for item in items:
6363
print(u'{0} ({1})'.format(item['name'], item['id']))
6464

65-
except Exception as error:
66-
print('An error occurred: %s' % error)
65+
except HttpError as error:
66+
# TODO(developer) - Handleerrors from drive API.
67+
print(f'An error occurred: {error}')
6768

6869

6970
if __name__ == '__main__':

gmail/quickstart/quickstart.py

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
import os.path
1818
from googleapiclient.discovery import build
1919
from google_auth_oauthlib.flow import InstalledAppFlow
20+
from googleapiclient.errors import HttpError
2021
from google.auth.transport.requests import Request
2122
from google.oauth2.credentials import Credentials
2223

@@ -32,24 +33,23 @@ def main():
3233
# The file token.json stores the user's access and refresh tokens, and is
3334
# created automatically when the authorization flow completes for the first
3435
# time.
35-
try:
36-
if os.path.exists('token.json'):
37-
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
38-
# If there are no (valid) credentials available, let the user log in.
39-
if not creds or not creds.valid:
40-
if creds and creds.expired and creds.refresh_token:
41-
creds.refresh(Request())
42-
else:
43-
flow = InstalledAppFlow.from_client_secrets_file(
44-
'credentials.json', SCOPES)
45-
creds = flow.run_local_server(port=0)
46-
# Save the credentials for the next run
47-
with open('token.json', 'w') as token:
48-
token.write(creds.to_json())
36+
if os.path.exists('token.json'):
37+
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
38+
# If there are no (valid) credentials available, let the user log in.
39+
if not creds or not creds.valid:
40+
if creds and creds.expired and creds.refresh_token:
41+
creds.refresh(Request())
42+
else:
43+
flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
44+
creds = flow.run_local_server(port=0)
45+
# Save the credentials for the next run
46+
with open('token.json', 'w') as token:
47+
token.write(creds.to_json())
4948

50-
service = build('gmail', 'v1', credentials=creds)
49+
service = build('gmail', 'v1', credentials=creds)
5150

52-
# Call the Gmail API
51+
# Call the Gmail API
52+
try:
5353
results = service.users().labels().list(userId='me').execute()
5454
labels = results.get('labels', [])
5555

@@ -60,8 +60,9 @@ def main():
6060
for label in labels:
6161
print(label['name'])
6262

63-
except Exception as error:
64-
print('An error occurred: %s' % error)
63+
except HttpError as error:
64+
# TODO(developer) - Handleerrors from gmail API.
65+
print(f'An error occurred: {error}')
6566

6667

6768
if __name__ == '__main__':

0 commit comments

Comments
 (0)