Skip to content

Commit cf15bd4

Browse files
authored
Merge pull request googleworkspace#6 from anuraggoogler/anurag-patch
Added try except and comments Updated activity loop and added try except Removed pprint and added try except
2 parents 67b332b + 3c70d52 commit cf15bd4

6 files changed

Lines changed: 177 additions & 151 deletions

File tree

‎calendar/quickstart/quickstart.py‎

Lines changed: 31 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -33,35 +33,40 @@ def main():
3333
# The file token.json stores the user's access and refresh tokens, and is
3434
# created automatically when the authorization flow completes for the first
3535
# time.
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+
try:
37+
if os.path.exists('token.json'):
38+
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
39+
# If there are no (valid) credentials available, let the user log in.
40+
if not creds or not creds.valid:
41+
if creds and creds.expired and creds.refresh_token:
42+
creds.refresh(Request())
43+
else:
44+
flow = InstalledAppFlow.from_client_secrets_file(
45+
'credentials.json', SCOPES)
46+
creds = flow.run_local_server(port=0)
47+
# Save the credentials for the next run
48+
with open('token.json', 'w') as token:
49+
token.write(creds.to_json())
4950

50-
service = build('calendar', 'v3', credentials=creds)
51+
service = build('calendar', 'v3', credentials=creds)
5152

52-
# Call the Calendar API
53-
now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
54-
print('Getting the upcoming 10 events')
55-
events_result = service.events().list(calendarId='primary', timeMin=now,
56-
maxResults=10, singleEvents=True,
57-
orderBy='startTime').execute()
58-
events = events_result.get('items', [])
53+
# Call the Calendar API
54+
now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
55+
print('Getting the upcoming 10 events')
56+
events_result = service.events().list(calendarId='primary', timeMin=now,
57+
maxResults=10, singleEvents=True,
58+
orderBy='startTime').execute()
59+
events = events_result.get('items', [])
5960

60-
if not events:
61-
print('No upcoming events found.')
62-
for event in events:
63-
start = event['start'].get('dateTime', event['start'].get('date'))
64-
print(start, event['summary'])
61+
# Prints the start and name of the next 10 events
62+
if not events:
63+
print('No upcoming events found.')
64+
for event in events:
65+
start = event['start'].get('dateTime', event['start'].get('date'))
66+
print(start, event['summary'])
67+
68+
except Exception as error:
69+
print('An error occurred: %s' % error)
6570

6671

6772
if __name__ == '__main__':

‎classroom/quickstart/quickstart.py‎

Lines changed: 28 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -32,32 +32,37 @@ def main():
3232
# The file token.json stores the user's access and refresh tokens, and is
3333
# created automatically when the authorization flow completes for the first
3434
# time.
35-
if os.path.exists('token.json'):
36-
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
37-
# If there are no (valid) credentials available, let the user log in.
38-
if not creds or not creds.valid:
39-
if creds and creds.expired and creds.refresh_token:
40-
creds.refresh(Request())
41-
else:
42-
flow = InstalledAppFlow.from_client_secrets_file(
43-
'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())
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())
49+
50+
service = build('classroom', 'v1', credentials=creds)
4851

49-
service = build('classroom', 'v1', credentials=creds)
52+
# Call the Classroom API
53+
results = service.courses().list(pageSize=10).execute()
54+
courses = results.get('courses', [])
5055

51-
# Call the Classroom API
52-
results = service.courses().list(pageSize=10).execute()
53-
courses = results.get('courses', [])
56+
# Prints the names of the first 10 courses.
57+
if not courses:
58+
print('No courses found.')
59+
else:
60+
print('Courses:')
61+
for course in courses:
62+
print(course['name'])
5463

55-
if not courses:
56-
print('No courses found.')
57-
else:
58-
print('Courses:')
59-
for course in courses:
60-
print(course['name'])
64+
except Exception as error:
65+
print('An error occurred: %s' % error)
6166

6267

6368
if __name__ == '__main__':

‎drive/activity-v2/quickstart.py‎

Lines changed: 24 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -50,29 +50,30 @@ def main():
5050
service = build('driveactivity', 'v2', credentials=creds)
5151

5252
# Call the Drive Activity API
53-
results = service.activity().query(body={
54-
'pageSize': 10
55-
}).execute()
56-
activities = results.get('activities', [])
57-
58-
if not activities:
59-
print('No activity.')
60-
else:
61-
print('Recent activity:')
62-
for activity in activities:
63-
time = getTimeInfo(activity)
64-
action = getActionInfo(activity['primaryActionDetail'])
65-
actors = map(getActorInfo, activity['actors'])
66-
targets = map(getTargetInfo, activity['targets'])
67-
print(u'{0}: {1}, {2}, {3}'.format(time, truncated(actors), action,
68-
truncated(targets)))
69-
70-
71-
# Returns a string representation of the first elements in a list.
72-
def truncated(array, limit=2):
73-
contents = ', '.join(array[:limit])
74-
more = '' if len(array) <= limit else ', ...'
75-
return u'[{0}{1}]'.format(contents, more)
53+
try:
54+
results = service.activity().query(body={
55+
'pageSize': 10
56+
}).execute()
57+
activities = results.get('activities', [])
58+
59+
if not activities:
60+
print('No activity.')
61+
else:
62+
print('Recent activity:')
63+
for activity in activities:
64+
time = getTimeInfo(activity)
65+
action = getActionInfo(activity['primaryActionDetail'])
66+
actors = map(getActorInfo, activity['actors'])
67+
targets = map(getTargetInfo, activity['targets'])
68+
actors_str, targets_str = "", ""
69+
actor_name = actors_str.join(actors)
70+
target_name = targets_str.join(targets)
71+
72+
# Print the action occurred on drive with actor, target item and timestamp
73+
print(u'{0}: {1}, {2}, {3}'.format(time, action, actor_name, target_name))
74+
75+
except Exception as error:
76+
print('An error occurred: %s' % error)
7677

7778

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

‎drive/driveapp/main.py‎

Lines changed: 38 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
"""
77

88
from __future__ import print_function
9-
import pprint
109
import six
1110
import httplib2
1211
from googleapiclient.discovery import build
@@ -29,34 +28,41 @@
2928
DESCRIPTION = 'A shiny new text document about hello world.'
3029

3130
# Perform OAuth2.0 authorization flow.
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)
40-
41-
# Create an authorized Drive API client.
42-
http = httplib2.Http()
43-
credentials.authorize(http)
44-
drive_service = build('drive', 'v2', http=http)
45-
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-
}
58-
59-
# Perform the request and print the result.
60-
new_file = drive_service.files().insert(
61-
body=body, media_body=media_body).execute()
62-
pprint.pprint(new_file)
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)
40+
41+
# Create an authorized Drive API client.
42+
http = httplib2.Http()
43+
credentials.authorize(http)
44+
drive_service = build('drive', 'v2', http=http)
45+
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+
}
58+
59+
# Perform the request and print the result.
60+
new_file = drive_service.files().insert(
61+
body=body, media_body=media_body).execute()
62+
file_title = new_file.get('title')
63+
file_desc = new_file.get('description')
64+
if file_title == TITLE and file_desc == DESCRIPTION:
65+
print(f"File is uploaded \nTitle : {file_title} \nDescription : {file_desc}")
66+
67+
except Exception as error:
68+
print('An error occurred: %s' % error)

‎drive/quickstart/quickstart.py‎

Lines changed: 29 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -32,33 +32,38 @@ def main():
3232
# The file token.json stores the user's access and refresh tokens, and is
3333
# created automatically when the authorization flow completes for the first
3434
# time.
35-
if os.path.exists('token.json'):
36-
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
37-
# If there are no (valid) credentials available, let the user log in.
38-
if not creds or not creds.valid:
39-
if creds and creds.expired and creds.refresh_token:
40-
creds.refresh(Request())
41-
else:
42-
flow = InstalledAppFlow.from_client_secrets_file(
43-
'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())
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())
49+
50+
service = build('drive', 'v3', credentials=creds)
4851

49-
service = build('drive', 'v3', credentials=creds)
52+
# Call the Drive v3 API
53+
results = service.files().list(
54+
pageSize=10, fields="nextPageToken, files(id, name)").execute()
55+
items = results.get('files', [])
5056

51-
# Call the Drive v3 API
52-
results = service.files().list(
53-
pageSize=10, fields="nextPageToken, files(id, name)").execute()
54-
items = results.get('files', [])
57+
# Prints the names and ids of the first 10 files in drive
58+
if not items:
59+
print('No files found.')
60+
else:
61+
print('Files:')
62+
for item in items:
63+
print(u'{0} ({1})'.format(item['name'], item['id']))
5564

56-
if not items:
57-
print('No files found.')
58-
else:
59-
print('Files:')
60-
for item in items:
61-
print(u'{0} ({1})'.format(item['name'], item['id']))
65+
except Exception as error:
66+
print('An error occurred: %s' % error)
6267

6368

6469
if __name__ == '__main__':

‎gmail/quickstart/quickstart.py‎

Lines changed: 27 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -32,32 +32,36 @@ def main():
3232
# The file token.json stores the user's access and refresh tokens, and is
3333
# created automatically when the authorization flow completes for the first
3434
# time.
35-
if os.path.exists('token.json'):
36-
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
37-
# If there are no (valid) credentials available, let the user log in.
38-
if not creds or not creds.valid:
39-
if creds and creds.expired and creds.refresh_token:
40-
creds.refresh(Request())
41-
else:
42-
flow = InstalledAppFlow.from_client_secrets_file(
43-
'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())
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())
49+
50+
service = build('gmail', 'v1', credentials=creds)
4851

49-
service = build('gmail', 'v1', credentials=creds)
52+
# Call the Gmail API
53+
results = service.users().labels().list(userId='me').execute()
54+
labels = results.get('labels', [])
5055

51-
# Call the Gmail API
52-
results = service.users().labels().list(userId='me').execute()
53-
labels = results.get('labels', [])
56+
if not labels:
57+
print('No labels found.')
58+
else:
59+
print('Labels:')
60+
for label in labels:
61+
print(label['name'])
5462

55-
if not labels:
56-
print('No labels found.')
57-
else:
58-
print('Labels:')
59-
for label in labels:
60-
print(label['name'])
63+
except Exception as error:
64+
print('An error occurred: %s' % error)
6165

6266

6367
if __name__ == '__main__':

0 commit comments

Comments
 (0)