From 8ac49945ec63d9fc1efbe338a9bdb788b3c6856b Mon Sep 17 00:00:00 2001 From: Justin Poehnelt Date: Mon, 6 Nov 2023 12:42:34 -0700 Subject: [PATCH] fix: run pyink, autoflake, flynt and remove from __future__ --- admin_sdk/directory/quickstart.py | 77 ++--- admin_sdk/reports/quickstart.py | 83 ++--- admin_sdk/reseller/quickstart.py | 78 ++--- apps_script/execute/execute.py | 87 +++--- apps_script/quickstart/quickstart.py | 101 +++---- calendar/quickstart/quickstart.py | 93 +++--- classroom/quickstart/quickstart.py | 77 +++-- classroom/snippets/base_test.py | 65 ++-- .../snippets/classroom_add_alias_existing.py | 54 ++-- classroom/snippets/classroom_add_alias_new.py | 94 +++--- .../snippets/classroom_add_attachment.py | 72 +++-- classroom/snippets/classroom_add_student.py | 101 +++---- classroom/snippets/classroom_add_teacher.py | 61 ++-- .../snippets/classroom_all_submissions.py | 89 +++--- classroom/snippets/classroom_create_course.py | 65 ++-- .../snippets/classroom_create_coursework.py | 73 ++--- classroom/snippets/classroom_get_course.py | 52 ++-- .../snippets/classroom_invite_guardian.py | 72 ++--- .../snippets/classroom_list_course_aliases.py | 79 +++-- classroom/snippets/classroom_list_courses.py | 80 +++-- .../classroom_list_student_submissions.py | 83 ++--- .../snippets/classroom_list_submissions.py | 85 +++--- classroom/snippets/classroom_patch_course.py | 61 ++-- classroom/snippets/classroom_update_course.py | 63 ++-- .../snippets/test_classroom_create_course.py | 15 +- .../snippets/test_classroom_get_course.py | 21 +- .../test_classroom_list_course_aliases.py | 19 +- .../snippets/test_classroom_list_courses.py | 20 +- .../snippets/test_classroom_patch_course.py | 22 +- .../snippets/test_classroom_update_course.py | 20 +- docs/mail-merge/docs_mail_merge.py | 227 +++++++------- docs/mail-merge/docs_mail_merge_test.py | 68 ++--- docs/output-json/output-json.py | 23 +- docs/output-json/output_json.py | 17 +- docs/quickstart/quickstart.py | 65 ++-- drive/activity-v2/quickstart.py | 167 +++++------ drive/driveapp/main.py | 50 ++-- drive/quickstart/quickstart.py | 82 ++--- .../app data snippet/fetch_appdata_folder.py | 42 ++- .../drive-v2/app data snippet/list_appdata.py | 71 ++--- .../test_fetch_appdata_folder.py | 17 +- .../app data snippet/test_list_appdata.py | 17 +- .../app data snippet/test_upload_appdata.py | 25 +- .../app data snippet/upload_app_data.py | 71 ++--- .../drive-v2/change snippet/fetch_changes.py | 85 +++--- .../change snippet/fetch_start_page_token.py | 42 ++- .../change snippet/test_fetch_changes.py | 18 +- .../test_fetch_start_page_token.py | 17 +- .../drive-v2/drive_snippet/create_drive.py | 68 ++--- .../drive-v2/drive_snippet/recover_drives.py | 128 ++++---- .../drive-v2/file snippet/create_folder.py | 63 ++-- .../drive-v2/file snippet/create_shortcut.py | 57 ++-- .../drive-v2/file snippet/download_file.py | 58 ++-- .../drive-v2/file snippet/export_pdf.py | 77 +++-- .../file snippet/move_file_to_folder.py | 81 ++--- .../drive-v2/file snippet/search_file.py | 83 ++--- .../drive-v2/file snippet/share_file.py | 110 +++---- .../file snippet/test_create_folder.py | 17 +- .../file snippet/test_create_shortcut.py | 17 +- .../file snippet/test_download_file.py | 21 +- .../drive-v2/file snippet/test_export_pdf.py | 21 +- .../file snippet/test_move_file_to_folder.py | 24 +- .../drive-v2/file snippet/test_search_file.py | 17 +- .../drive-v2/file snippet/test_share_file.py | 33 +- .../drive-v2/file snippet/test_touch_file.py | 32 +- .../file snippet/test_upload_basic.py | 17 +- .../file snippet/test_upload_revision.py | 19 +- .../file snippet/test_upload_to_folder.py | 20 +- .../test_upload_with_conversion.py | 17 +- .../drive-v2/file snippet/touch_file.py | 87 +++--- .../drive-v2/file snippet/upload_basic.py | 66 ++-- .../drive-v2/file snippet/upload_revision.py | 67 ++--- .../drive-v2/file snippet/upload_to_folder.py | 69 ++--- .../file snippet/upload_with_conversion.py | 72 ++--- .../team_drive_snippets/create_team_drive.py | 65 ++-- .../recover_team_drives.py | 128 ++++---- .../app_data_snippet/fetch_appdata_folder.py | 42 ++- .../drive-v3/app_data_snippet/list_appdata.py | 71 ++--- .../test_fetch_appdata_folder.py | 17 +- .../app_data_snippet/test_list_appdata.py | 17 +- .../app_data_snippet/test_upload_appdata.py | 25 +- .../app_data_snippet/upload_appdata.py | 69 ++--- .../drive-v3/change_snippet/fetch_changes.py | 75 +++-- .../change_snippet/fetch_start_page_token.py | 42 ++- .../change_snippet/test_fetch_changes.py | 18 +- .../test_fetch_start_page_token.py | 17 +- .../drive-v3/drive_snippet/create_drive.py | 68 ++--- .../drive-v3/drive_snippet/recover_drives.py | 127 ++++---- .../drive-v3/file_snippet/create_folder.py | 63 ++-- .../drive-v3/file_snippet/create_shortcut.py | 59 ++-- .../drive-v3/file_snippet/download_file.py | 58 ++-- .../drive-v3/file_snippet/export_pdf.py | 77 +++-- .../file_snippet/move_file_to_folder.py | 82 ++--- .../drive-v3/file_snippet/search_file.py | 83 ++--- .../drive-v3/file_snippet/share_file.py | 124 ++++---- .../file_snippet/test_create_folder.py | 17 +- .../file_snippet/test_create_shortcut.py | 17 +- .../file_snippet/test_download_file.py | 21 +- .../drive-v3/file_snippet/test_export_pdf.py | 21 +- .../file_snippet/test_move_file_to_folder.py | 24 +- .../drive-v3/file_snippet/test_search_file.py | 17 +- .../drive-v3/file_snippet/test_share_file.py | 33 +- .../drive-v3/file_snippet/test_touch_file.py | 32 +- .../file_snippet/test_upload_basic.py | 17 +- .../file_snippet/test_upload_revision.py | 19 +- .../file_snippet/test_upload_to_folder.py | 20 +- .../test_upload_with_conversion.py | 17 +- .../drive-v3/file_snippet/touch_file.py | 65 ++-- .../drive-v3/file_snippet/upload_basic.py | 66 ++-- .../drive-v3/file_snippet/upload_revision.py | 69 +++-- .../drive-v3/file_snippet/upload_to_folder.py | 71 +++-- .../file_snippet/upload_with_conversion.py | 72 ++--- .../team_drive_snippets/create_team_drive.py | 65 ++-- .../recover_team_drives.py | 133 ++++---- events/next18/customer_data_service.py | 208 ++++++------- events/next18/customer_spreadsheet_reader.py | 90 +++--- events/next18/presentation_reader.py | 95 +++--- events/next18/presentation_writer.py | 72 ++--- events/next18/qbr_tool.py | 278 +++++++++-------- events/next18/spreadsheet_writer.py | 209 +++++++------ forms/quickstart/quickstart.py | 68 +++-- forms/snippets/add_item.py | 53 ++-- forms/snippets/convert_form.py | 32 +- forms/snippets/create_form.py | 17 +- forms/snippets/create_watch.py | 27 +- forms/snippets/delete_watch.py | 25 +- forms/snippets/duplicate_form.py | 66 ++-- forms/snippets/list_watches.py | 19 +- forms/snippets/renew_watch.py | 25 +- forms/snippets/retrieve_all_responses.py | 19 +- forms/snippets/retrieve_contents.py | 19 +- forms/snippets/retrieve_single_response.py | 29 +- forms/snippets/update_form.py | 43 ++- gmail/quickstart/quickstart.py | 77 +++-- gmail/snippet/base_test.py | 60 ++-- gmail/snippet/send mail/create_draft.py | 71 +++-- .../send mail/create_draft_with_attachment.py | 173 ++++++----- gmail/snippet/send mail/send_message.py | 67 ++--- gmail/snippet/send mail/test_create_draft.py | 16 +- .../test_create_draft_with_attachment.py | 16 +- gmail/snippet/send mail/test_send_message.py | 15 +- .../test_send_message_with_attachment.py | 15 +- .../settings snippets/create_filter.py | 80 +++-- .../settings snippets/enable_auto_reply.py | 91 +++--- .../settings snippets/enable_forwarding.py | 89 +++--- .../settings snippets/test_create_filter.py | 17 +- .../test_enable_auto_reply.py | 17 +- .../test_enable_forwarding.py | 17 +- .../test_update_signature.py | 17 +- .../settings snippets/update_signature.py | 97 +++--- .../smime snippets/create_smime_info.py | 48 ++- .../smime snippets/insert_cert_from_csv.py | 66 ++-- .../smime snippets/insert_smime_info.py | 65 ++-- .../smime snippets/test_create_smime_info.py | 19 +- .../test_insert_cert_from_csv.py | 17 +- .../smime snippets/test_insert_smime_info.py | 17 +- .../smime snippets/test_update_smime_cert.py | 31 +- .../test_update_smime_from_csv.py | 17 +- .../smime snippets/update_smime_cert.py | 193 ++++++------ .../smime snippets/update_smime_from_csv.py | 63 ++-- gmail/snippet/thread/test_thread.py | 17 +- gmail/snippet/thread/threads.py | 84 +++--- people/quickstart/quickstart.py | 85 +++--- pyproject.toml | 5 + sheets/quickstart/quickstart.py | 88 +++--- sheets/snippets/base_test.py | 123 ++++---- sheets/snippets/sheets_append_values.py | 89 +++--- sheets/snippets/sheets_batch_get_values.py | 68 +++-- sheets/snippets/sheets_batch_update.py | 105 ++++--- sheets/snippets/sheets_batch_update_values.py | 97 +++--- .../snippets/sheets_conditional_formatting.py | 148 ++++----- sheets/snippets/sheets_create.py | 58 ++-- sheets/snippets/sheets_filter_views.py | 160 +++++----- sheets/snippets/sheets_get_values.py | 56 ++-- sheets/snippets/sheets_pivot_tables.py | 153 +++++----- sheets/snippets/sheets_update_values.py | 90 +++--- sheets/snippets/test_sheets_append_values.py | 34 +-- .../snippets/test_sheets_batch_get_values.py | 29 +- sheets/snippets/test_sheets_batch_update.py | 32 +- .../test_sheets_batch_update_values.py | 29 +- .../test_sheets_conditional_formatting.py | 19 +- sheets/snippets/test_sheets_create.py | 15 +- sheets/snippets/test_sheets_filter_views.py | 14 +- sheets/snippets/test_sheets_get_values.py | 24 +- sheets/snippets/test_sheets_pivot_tables.py | 16 +- sheets/snippets/test_sheets_update_values.py | 26 +- slides/quickstart/quickstart.py | 78 ++--- slides/snippets/base_test.py | 283 +++++++++--------- slides/snippets/slides_copy_presentation.py | 63 ++-- .../snippets/slides_create_bulleted_text.py | 76 +++-- slides/snippets/slides_create_image.py | 114 ++++--- slides/snippets/slides_create_presentation.py | 60 ++-- slides/snippets/slides_create_sheets_chart.py | 124 ++++---- slides/snippets/slides_create_slide.py | 88 +++--- .../slides_create_textbox_with_text.py | 124 ++++---- slides/snippets/slides_image_merging.py | 154 +++++----- .../snippets/slides_refresh_sheets_chart.py | 73 +++-- slides/snippets/slides_simple_text_replace.py | 88 +++--- slides/snippets/slides_text_merging.py | 204 +++++++------ slides/snippets/slides_text_style_update.py | 162 +++++----- .../snippets/test_slides_copy_presentation.py | 19 +- .../test_slides_create_bulleted_text.py | 22 +- slides/snippets/test_slides_create_image.py | 22 +- .../test_slides_create_presentation.py | 14 +- .../test_slides_create_sheets_chart.py | 36 +-- slides/snippets/test_slides_create_slide.py | 22 +- .../test_slides_create_textbox_with_text.py | 24 +- slides/snippets/test_slides_image_merging.py | 48 +-- .../test_slides_refresh_sheets_chart.py | 34 +-- .../test_slides_simple_text_replace.py | 22 +- slides/snippets/test_slides_text_merging.py | 19 +- .../snippets/test_slides_text_style_update.py | 22 +- tasks/quickstart/quickstart.py | 75 +++-- vault/quickstart/quickstart.py | 76 +++-- 214 files changed, 6682 insertions(+), 6523 deletions(-) create mode 100644 pyproject.toml diff --git a/admin_sdk/directory/quickstart.py b/admin_sdk/directory/quickstart.py index 074a545b..f4ba960f 100644 --- a/admin_sdk/directory/quickstart.py +++ b/admin_sdk/directory/quickstart.py @@ -13,8 +13,6 @@ # limitations under the License. # [START admin_sdk_directory_quickstart] -from __future__ import print_function - import os.path from google.auth.transport.requests import Request @@ -23,48 +21,51 @@ from googleapiclient.discovery import build # If modifying these scopes, delete the file token.json. -SCOPES = ['https://www.googleapis.com/auth/admin.directory.user'] +SCOPES = ["https://www.googleapis.com/auth/admin.directory.user"] def main(): - """Shows basic usage of the Admin SDK Directory API. - Prints the emails and names of the first 10 users in the domain. - """ - creds = None - # The file token.json stores the user's access and refresh tokens, and is - # created automatically when the authorization flow completes for the first - # time. - if os.path.exists('token.json'): - creds = Credentials.from_authorized_user_file('token.json', SCOPES) - # If there are no (valid) credentials available, let the user log in. - if not creds or not creds.valid: - if creds and creds.expired and creds.refresh_token: - creds.refresh(Request()) - else: - flow = InstalledAppFlow.from_client_secrets_file( - 'credentials.json', SCOPES) - creds = flow.run_local_server(port=0) - # Save the credentials for the next run - with open('token.json', 'w') as token: - token.write(creds.to_json()) + """Shows basic usage of the Admin SDK Directory API. + Prints the emails and names of the first 10 users in the domain. + """ + creds = None + # The file token.json stores the user's access and refresh tokens, and is + # created automatically when the authorization flow completes for the first + # time. + if os.path.exists("token.json"): + creds = Credentials.from_authorized_user_file("token.json", SCOPES) + # If there are no (valid) credentials available, let the user log in. + if not creds or not creds.valid: + if creds and creds.expired and creds.refresh_token: + creds.refresh(Request()) + else: + flow = InstalledAppFlow.from_client_secrets_file( + "credentials.json", SCOPES + ) + creds = flow.run_local_server(port=0) + # Save the credentials for the next run + with open("token.json", "w") as token: + token.write(creds.to_json()) - service = build('admin', 'directory_v1', credentials=creds) + service = build("admin", "directory_v1", credentials=creds) - # Call the Admin SDK Directory API - print('Getting the first 10 users in the domain') - results = service.users().list(customer='my_customer', maxResults=10, - orderBy='email').execute() - users = results.get('users', []) + # Call the Admin SDK Directory API + print("Getting the first 10 users in the domain") + results = ( + service.users() + .list(customer="my_customer", maxResults=10, orderBy="email") + .execute() + ) + users = results.get("users", []) - if not users: - print('No users in the domain.') - else: - print('Users:') - for user in users: - print(u'{0} ({1})'.format(user['primaryEmail'], - user['name']['fullName'])) + if not users: + print("No users in the domain.") + else: + print("Users:") + for user in users: + print(f"{user['primaryEmail']} ({user['name']['fullName']})") -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() # [END admin_sdk_directory_quickstart] diff --git a/admin_sdk/reports/quickstart.py b/admin_sdk/reports/quickstart.py index d609abbd..cce9f415 100644 --- a/admin_sdk/reports/quickstart.py +++ b/admin_sdk/reports/quickstart.py @@ -13,8 +13,6 @@ # limitations under the License. # [START admin_sdk_reports_quickstart] -from __future__ import print_function - import os.path from google.auth.transport.requests import Request @@ -23,48 +21,57 @@ from googleapiclient.discovery import build # If modifying these scopes, delete the file token.json. -SCOPES = ['https://www.googleapis.com/auth/admin.reports.audit.readonly'] +SCOPES = ["https://www.googleapis.com/auth/admin.reports.audit.readonly"] def main(): - """Shows basic usage of the Admin SDK Reports API. - Prints the time, email, and name of the last 10 login events in the domain. - """ - creds = None - # The file token.json stores the user's access and refresh tokens, and is - # created automatically when the authorization flow completes for the first - # time. - if os.path.exists('token.json'): - creds = Credentials.from_authorized_user_file('token.json', SCOPES) - # If there are no (valid) credentials available, let the user log in. - if not creds or not creds.valid: - if creds and creds.expired and creds.refresh_token: - creds.refresh(Request()) - else: - flow = InstalledAppFlow.from_client_secrets_file( - 'credentials.json', SCOPES) - creds = flow.run_local_server(port=0) - # Save the credentials for the next run - with open('token.json', 'w') as token: - token.write(creds.to_json()) + """Shows basic usage of the Admin SDK Reports API. + Prints the time, email, and name of the last 10 login events in the domain. + """ + creds = None + # The file token.json stores the user's access and refresh tokens, and is + # created automatically when the authorization flow completes for the first + # time. + if os.path.exists("token.json"): + creds = Credentials.from_authorized_user_file("token.json", SCOPES) + # If there are no (valid) credentials available, let the user log in. + if not creds or not creds.valid: + if creds and creds.expired and creds.refresh_token: + creds.refresh(Request()) + else: + flow = InstalledAppFlow.from_client_secrets_file( + "credentials.json", SCOPES + ) + creds = flow.run_local_server(port=0) + # Save the credentials for the next run + with open("token.json", "w") as token: + token.write(creds.to_json()) - service = build('admin', 'reports_v1', credentials=creds) + service = build("admin", "reports_v1", credentials=creds) - # Call the Admin SDK Reports API - print('Getting the last 10 login events') - results = service.activities().list(userKey='all', applicationName='login', - maxResults=10).execute() - activities = results.get('items', []) + # Call the Admin SDK Reports API + print("Getting the last 10 login events") + results = ( + service.activities() + .list(userKey="all", applicationName="login", maxResults=10) + .execute() + ) + activities = results.get("items", []) - if not activities: - print('No logins found.') - else: - print('Logins:') - for activity in activities: - print(u'{0}: {1} ({2})'.format(activity['id']['time'], - activity['actor']['email'], activity['events'][0]['name'])) + if not activities: + print("No logins found.") + else: + print("Logins:") + for activity in activities: + print( + "{0}: {1} ({2})".format( + activity["id"]["time"], + activity["actor"]["email"], + activity["events"][0]["name"], + ) + ) -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() # [END admin_sdk_reports_quickstart] diff --git a/admin_sdk/reseller/quickstart.py b/admin_sdk/reseller/quickstart.py index 1e6133a3..cdcbd663 100644 --- a/admin_sdk/reseller/quickstart.py +++ b/admin_sdk/reseller/quickstart.py @@ -13,8 +13,6 @@ # limitations under the License. # [START admin_sdk_reseller_quickstart] -from __future__ import print_function - import os.path from google.auth.transport.requests import Request @@ -23,46 +21,52 @@ from googleapiclient.discovery import build # If modifying these scopes, delete the file token.json. -SCOPES = ['https://www.googleapis.com/auth/apps.order'] +SCOPES = ["https://www.googleapis.com/auth/apps.order"] def main(): - """Calls the Admin SDK Reseller API. Prints the customer ID, SKU ID, - and plan name of the first 10 subscriptions managed by the domain. - """ - creds = None - # The file token.json stores the user's access and refresh tokens, and is - # created automatically when the authorization flow completes for the first - # time. - if os.path.exists('token.json'): - creds = Credentials.from_authorized_user_file('token.json', SCOPES) - # If there are no (valid) credentials available, let the user log in. - if not creds or not creds.valid: - if creds and creds.expired and creds.refresh_token: - creds.refresh(Request()) - else: - flow = InstalledAppFlow.from_client_secrets_file( - 'credentials.json', SCOPES) - creds = flow.run_local_server(port=0) - # Save the credentials for the next run - with open('token.json', 'w') as token: - token.write(creds.to_json()) + """Calls the Admin SDK Reseller API. Prints the customer ID, SKU ID, + and plan name of the first 10 subscriptions managed by the domain. + """ + creds = None + # The file token.json stores the user's access and refresh tokens, and is + # created automatically when the authorization flow completes for the first + # time. + if os.path.exists("token.json"): + creds = Credentials.from_authorized_user_file("token.json", SCOPES) + # If there are no (valid) credentials available, let the user log in. + if not creds or not creds.valid: + if creds and creds.expired and creds.refresh_token: + creds.refresh(Request()) + else: + flow = InstalledAppFlow.from_client_secrets_file( + "credentials.json", SCOPES + ) + creds = flow.run_local_server(port=0) + # Save the credentials for the next run + with open("token.json", "w") as token: + token.write(creds.to_json()) - service = build('reseller', 'v1', credentials=creds) + service = build("reseller", "v1", credentials=creds) - # Call the Admin SDK Reseller API - print('Getting the first 10 subscriptions') - results = service.subscriptions().list(maxResults=10).execute() - subscriptions = results.get('subscriptions', []) - if not subscriptions: - print('No subscriptions found.') - else: - print('Subscriptions:') - for subscription in subscriptions: - print(u'{0} ({1}, {2})'.format(subscription['customerId'], - subscription['skuId'], subscription['plan']['planName'])) + # Call the Admin SDK Reseller API + print("Getting the first 10 subscriptions") + results = service.subscriptions().list(maxResults=10).execute() + subscriptions = results.get("subscriptions", []) + if not subscriptions: + print("No subscriptions found.") + else: + print("Subscriptions:") + for subscription in subscriptions: + print( + "{0} ({1}, {2})".format( + subscription["customerId"], + subscription["skuId"], + subscription["plan"]["planName"], + ) + ) -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() # [END admin_sdk_reseller_quickstart] diff --git a/apps_script/execute/execute.py b/apps_script/execute/execute.py index c07ff03e..3a0eabf3 100644 --- a/apps_script/execute/execute.py +++ b/apps_script/execute/execute.py @@ -15,63 +15,58 @@ """ # [START apps_script_api_execute] -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def main(): - """Runs the sample. - """ - # pylint: disable=maybe-no-member - script_id = '1VFBDoJFy6yb9z7-luOwRv3fCmeNOzILPnR4QVmR0bGJ7gQ3QMPpCW-yt' + """Runs the sample.""" + # pylint: disable=maybe-no-member + script_id = "1VFBDoJFy6yb9z7-luOwRv3fCmeNOzILPnR4QVmR0bGJ7gQ3QMPpCW-yt" - creds, _ = google.auth.default() - service = build('script', 'v1', credentials=creds) + creds, _ = google.auth.default() + service = build("script", "v1", credentials=creds) - # Create an execution request object. - request = {"function": "getFoldersUnderRoot"} + # Create an execution request object. + request = {"function": "getFoldersUnderRoot"} - try: - # Make the API request. - response = service.scripts().run(scriptId=script_id, - body=request).execute() - if 'error' in response: - # The API executed, but the script returned an error. - # Extract the first (and only) set of error details. The values of - # this object are the script's 'errorMessage' and 'errorType', and - # a list of stack trace elements. - error = response['error']['details'][0] - print(f"Script error message: {0}.{format(error['errorMessage'])}") + try: + # Make the API request. + response = service.scripts().run(scriptId=script_id, body=request).execute() + if "error" in response: + # The API executed, but the script returned an error. + # Extract the first (and only) set of error details. The values of + # this object are the script's 'errorMessage' and 'errorType', and + # a list of stack trace elements. + error = response["error"]["details"][0] + print(f"Script error message: {0}.{format(error['errorMessage'])}") - if 'scriptStackTraceElements' in error: - # There may not be a stacktrace if the script didn't start - # executing. - print("Script error stacktrace:") - for trace in error['scriptStackTraceElements']: - print(f"\t{0}: {1}." - f"{format(trace['function'], trace['lineNumber'])}") - else: - # The structure of the result depends upon what the Apps Script - # function returns. Here, the function returns an Apps Script - # Object with String keys and values, and so the result is - # treated as a Python dictionary (folder_set). - folder_set = response['response'].get('result', {}) - if not folder_set: - print('No folders returned!') - else: - print('Folders under your root folder:') - for (folder_id, folder) in folder_set.items(): - print(f"\t{0} ({1}).{format(folder, folder_id)}") + if "scriptStackTraceElements" in error: + # There may not be a stacktrace if the script didn't start + # executing. + print("Script error stacktrace:") + for trace in error["scriptStackTraceElements"]: + print(f"\t{0}: {1}.{format(trace['function'], trace['lineNumber'])}") + else: + # The structure of the result depends upon what the Apps Script + # function returns. Here, the function returns an Apps Script + # Object with String keys and values, and so the result is + # treated as a Python dictionary (folder_set). + folder_set = response["response"].get("result", {}) + if not folder_set: + print("No folders returned!") + else: + print("Folders under your root folder:") + for folder_id, folder in folder_set.items(): + print(f"\t{0} ({1}).{format(folder, folder_id)}") - except HttpError as error: - # The API encountered a problem before the script started executing. - print(f"An error occurred: {error}") - print(error.content) + except HttpError as error: + # The API encountered a problem before the script started executing. + print(f"An error occurred: {error}") + print(error.content) -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() # [END apps_script_api_execute] diff --git a/apps_script/quickstart/quickstart.py b/apps_script/quickstart/quickstart.py index 0718b449..607b5a9b 100644 --- a/apps_script/quickstart/quickstart.py +++ b/apps_script/quickstart/quickstart.py @@ -18,8 +18,6 @@ Call the Apps Script API to create a new script project, upload a file to the project, and log the script's URL to the user. """ -from __future__ import print_function - import os.path from google.auth.transport.requests import Request @@ -29,72 +27,69 @@ from googleapiclient.discovery import build # If modifying these scopes, delete the file token.json. -SCOPES = ['https://www.googleapis.com/auth/script.projects'] +SCOPES = ["https://www.googleapis.com/auth/script.projects"] -SAMPLE_CODE = ''' +SAMPLE_CODE = """ function helloWorld() { console.log("Hello, world!"); } -'''.strip() +""".strip() -SAMPLE_MANIFEST = ''' +SAMPLE_MANIFEST = """ { "timeZone": "America/New_York", "exceptionLogging": "CLOUD" } -'''.strip() +""".strip() def main(): - """Calls the Apps Script API. - """ - creds = None - # The file token.json stores the user's access and refresh tokens, and is - # created automatically when the authorization flow completes for the first - # time. - if os.path.exists('token.json'): - creds = Credentials.from_authorized_user_file('token.json', SCOPES) - # If there are no (valid) credentials available, let the user log in. - if not creds or not creds.valid: - if creds and creds.expired and creds.refresh_token: - creds.refresh(Request()) - else: - flow = InstalledAppFlow.from_client_secrets_file( - 'credentials.json', SCOPES) - creds = flow.run_local_server(port=0) - # Save the credentials for the next run - with open('token.json', 'w') as token: - token.write(creds.to_json()) + """Calls the Apps Script API.""" + creds = None + # The file token.json stores the user's access and refresh tokens, and is + # created automatically when the authorization flow completes for the first + # time. + if os.path.exists("token.json"): + creds = Credentials.from_authorized_user_file("token.json", SCOPES) + # If there are no (valid) credentials available, let the user log in. + if not creds or not creds.valid: + if creds and creds.expired and creds.refresh_token: + creds.refresh(Request()) + else: + flow = InstalledAppFlow.from_client_secrets_file( + "credentials.json", SCOPES + ) + creds = flow.run_local_server(port=0) + # Save the credentials for the next run + with open("token.json", "w") as token: + token.write(creds.to_json()) - try: - service = build('script', 'v1', credentials=creds) + try: + service = build("script", "v1", credentials=creds) - # Call the Apps Script API - # Create a new project - request = {'title': 'My Script'} - response = service.projects().create(body=request).execute() + # Call the Apps Script API + # Create a new project + request = {"title": "My Script"} + response = service.projects().create(body=request).execute() - # Upload two files to the project - request = { - 'files': [{ - 'name': 'hello', - 'type': 'SERVER_JS', - 'source': SAMPLE_CODE - }, { - 'name': 'appsscript', - 'type': 'JSON', - 'source': SAMPLE_MANIFEST - }] - } - response = service.projects().updateContent( - body=request, - scriptId=response['scriptId']).execute() - print('https://script.google.com/d/' + response['scriptId'] + '/edit') - except errors.HttpError as error: - # The API encountered a problem. - print(error.content) + # Upload two files to the project + request = { + "files": [ + {"name": "hello", "type": "SERVER_JS", "source": SAMPLE_CODE}, + {"name": "appsscript", "type": "JSON", "source": SAMPLE_MANIFEST}, + ] + } + response = ( + service.projects() + .updateContent(body=request, scriptId=response["scriptId"]) + .execute() + ) + print("https://script.google.com/d/" + response["scriptId"] + "/edit") + except errors.HttpError as error: + # The API encountered a problem. + print(error.content) -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() # [END apps_script_api_quickstart] diff --git a/calendar/quickstart/quickstart.py b/calendar/quickstart/quickstart.py index d3d827cf..6bedb465 100644 --- a/calendar/quickstart/quickstart.py +++ b/calendar/quickstart/quickstart.py @@ -13,8 +13,6 @@ # limitations under the License. # [START calendar_quickstart] -from __future__ import print_function - import datetime import os.path @@ -25,55 +23,64 @@ from googleapiclient.errors import HttpError # If modifying these scopes, delete the file token.json. -SCOPES = ['https://www.googleapis.com/auth/calendar.readonly'] +SCOPES = ["https://www.googleapis.com/auth/calendar.readonly"] def main(): - """Shows basic usage of the Google Calendar API. - Prints the start and name of the next 10 events on the user's calendar. - """ - creds = None - # The file token.json stores the user's access and refresh tokens, and is - # created automatically when the authorization flow completes for the first - # time. - if os.path.exists('token.json'): - creds = Credentials.from_authorized_user_file('token.json', SCOPES) - # If there are no (valid) credentials available, let the user log in. - if not creds or not creds.valid: - if creds and creds.expired and creds.refresh_token: - creds.refresh(Request()) - else: - flow = InstalledAppFlow.from_client_secrets_file( - 'credentials.json', SCOPES) - creds = flow.run_local_server(port=0) - # Save the credentials for the next run - with open('token.json', 'w') as token: - token.write(creds.to_json()) + """Shows basic usage of the Google Calendar API. + Prints the start and name of the next 10 events on the user's calendar. + """ + creds = None + # The file token.json stores the user's access and refresh tokens, and is + # created automatically when the authorization flow completes for the first + # time. + if os.path.exists("token.json"): + creds = Credentials.from_authorized_user_file("token.json", SCOPES) + # If there are no (valid) credentials available, let the user log in. + if not creds or not creds.valid: + if creds and creds.expired and creds.refresh_token: + creds.refresh(Request()) + else: + flow = InstalledAppFlow.from_client_secrets_file( + "credentials.json", SCOPES + ) + creds = flow.run_local_server(port=0) + # Save the credentials for the next run + with open("token.json", "w") as token: + token.write(creds.to_json()) - try: - service = build('calendar', 'v3', credentials=creds) + try: + service = build("calendar", "v3", credentials=creds) - # Call the Calendar API - now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time - print('Getting the upcoming 10 events') - events_result = service.events().list(calendarId='primary', timeMin=now, - maxResults=10, singleEvents=True, - orderBy='startTime').execute() - events = events_result.get('items', []) + # Call the Calendar API + now = datetime.datetime.utcnow().isoformat() + "Z" # 'Z' indicates UTC time + print("Getting the upcoming 10 events") + events_result = ( + service.events() + .list( + calendarId="primary", + timeMin=now, + maxResults=10, + singleEvents=True, + orderBy="startTime", + ) + .execute() + ) + events = events_result.get("items", []) - if not events: - print('No upcoming events found.') - return + if not events: + print("No upcoming events found.") + return - # Prints the start and name of the next 10 events - for event in events: - start = event['start'].get('dateTime', event['start'].get('date')) - print(start, event['summary']) + # Prints the start and name of the next 10 events + for event in events: + start = event["start"].get("dateTime", event["start"].get("date")) + print(start, event["summary"]) - except HttpError as error: - print('An error occurred: %s' % error) + except HttpError as error: + print(f"An error occurred: {error}") -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() # [END calendar_quickstart] diff --git a/classroom/quickstart/quickstart.py b/classroom/quickstart/quickstart.py index 9f1d65e9..3708c0a2 100644 --- a/classroom/quickstart/quickstart.py +++ b/classroom/quickstart/quickstart.py @@ -13,8 +13,6 @@ # limitations under the License. # [START classroom_quickstart] -from __future__ import print_function - import os.path from google.auth.transport.requests import Request @@ -24,50 +22,51 @@ from googleapiclient.errors import HttpError # If modifying these scopes, delete the file token.json. -SCOPES = ['https://www.googleapis.com/auth/classroom.courses.readonly'] +SCOPES = ["https://www.googleapis.com/auth/classroom.courses.readonly"] def main(): - """Shows basic usage of the Classroom API. - Prints the names of the first 10 courses the user has access to. - """ - creds = None - # The file token.json stores the user's access and refresh tokens, and is - # created automatically when the authorization flow completes for the first - # time. - if os.path.exists('token.json'): - creds = Credentials.from_authorized_user_file('token.json', SCOPES) - # If there are no (valid) credentials available, let the user log in. - if not creds or not creds.valid: - if creds and creds.expired and creds.refresh_token: - creds.refresh(Request()) - else: - flow = InstalledAppFlow.from_client_secrets_file( - 'credentials.json', SCOPES) - creds = flow.run_local_server(port=0) - # Save the credentials for the next run - with open('token.json', 'w') as token: - token.write(creds.to_json()) + """Shows basic usage of the Classroom API. + Prints the names of the first 10 courses the user has access to. + """ + creds = None + # The file token.json stores the user's access and refresh tokens, and is + # created automatically when the authorization flow completes for the first + # time. + if os.path.exists("token.json"): + creds = Credentials.from_authorized_user_file("token.json", SCOPES) + # If there are no (valid) credentials available, let the user log in. + if not creds or not creds.valid: + if creds and creds.expired and creds.refresh_token: + creds.refresh(Request()) + else: + flow = InstalledAppFlow.from_client_secrets_file( + "credentials.json", SCOPES + ) + creds = flow.run_local_server(port=0) + # Save the credentials for the next run + with open("token.json", "w") as token: + token.write(creds.to_json()) - try: - service = build('classroom', 'v1', credentials=creds) + try: + service = build("classroom", "v1", credentials=creds) - # Call the Classroom API - results = service.courses().list(pageSize=10).execute() - courses = results.get('courses', []) + # Call the Classroom API + results = service.courses().list(pageSize=10).execute() + courses = results.get("courses", []) - if not courses: - print('No courses found.') - return - # Prints the names of the first 10 courses. - print('Courses:') - for course in courses: - print(course['name']) + if not courses: + print("No courses found.") + return + # Prints the names of the first 10 courses. + print("Courses:") + for course in courses: + print(course["name"]) - except HttpError as error: - print('An error occurred: %s' % error) + except HttpError as error: + print(f"An error occurred: {error}") -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() # [END classroom_quickstart] diff --git a/classroom/snippets/base_test.py b/classroom/snippets/base_test.py index a241f644..34432364 100644 --- a/classroom/snippets/base_test.py +++ b/classroom/snippets/base_test.py @@ -12,8 +12,6 @@ # See the License for the specific language governing permissions and # limitations under the License. -from __future__ import print_function - import sys import unittest @@ -22,44 +20,45 @@ from googleapiclient.discovery import build from oauth2client.client import GoogleCredentials -SCOPES = 'https://www.googleapis.com/auth/classroom.courses' +SCOPES = "https://www.googleapis.com/auth/classroom.courses" class BaseTest(unittest.TestCase): - @classmethod - def setUpClass(cls): - cls.credentials = cls.create_credentials() - http = cls.credentials.authorize(httplib2.Http()) - cls.credentials.refresh(http) - cls.service = build('classroom', 'v1', http=http) - cls.stdout = sys.stdout - sys.stdout = None - @classmethod - def tearDownClass(cls): - # Restore STDOUT. - sys.stdout = cls.stdout + @classmethod + def setUpClass(cls): + cls.credentials = cls.create_credentials() + http = cls.credentials.authorize(httplib2.Http()) + cls.credentials.refresh(http) + cls.service = build("classroom", "v1", http=http) + cls.stdout = sys.stdout + sys.stdout = None + + @classmethod + def tearDownClass(cls): + # Restore STDOUT. + sys.stdout = cls.stdout - @classmethod - def create_credentials(cls): - cls.credentials = GoogleCredentials.get_application_default() - scope = ['https://www.googleapis.com/auth/drive'] - return cls.credentials.create_scoped(scope) + @classmethod + def create_credentials(cls): + cls.credentials = GoogleCredentials.get_application_default() + scope = ["https://www.googleapis.com/auth/drive"] + return cls.credentials.create_scoped(scope) - def setUp(self): - self.courses_to_delete = [] - print("Meow" + str(self.courses_to_delete)) + def setUp(self): + self.courses_to_delete = [] + print("Meow" + str(self.courses_to_delete)) - def tearDown(self): - for course_id in self.courses_to_delete: - try: - self.service.courses().delete(id=course_id).execute() - except errors.HttpError: - print('Unable to delete file %s' % course_id) + def tearDown(self): + for course_id in self.courses_to_delete: + try: + self.service.courses().delete(id=course_id).execute() + except errors.HttpError: + print(f"Unable to delete file {course_id}") - def delete_course_on_cleanup(self, course_id): - self.courses_to_delete.append(course_id) + def delete_course_on_cleanup(self, course_id): + self.courses_to_delete.append(course_id) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/classroom/snippets/classroom_add_alias_existing.py b/classroom/snippets/classroom_add_alias_existing.py index 4003d5cc..cb777291 100644 --- a/classroom/snippets/classroom_add_alias_existing.py +++ b/classroom/snippets/classroom_add_alias_existing.py @@ -13,7 +13,6 @@ limitations under the License. """ - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError @@ -21,34 +20,35 @@ # [START classroom_add_alias_existing] def classroom_add_alias_existing(course_id): - """ - Adds alias to existing course with specific course_id. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - # pylint: disable=maybe-no-member - # [START classroom_existing_alias] - service = build('classroom', 'v1', credentials=creds) - alias = 'd:school_math_101' - course_alias = { - 'alias': alias - } - try: - course_alias = service.courses().aliases().create( - courseId=course_id, - body=course_alias).execute() - return course_alias - except HttpError as error: - print(f"An error occurred: {error}") - print('Alias Creation Failed') + """ + Adds alias to existing course with specific course_id. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + # pylint: disable=maybe-no-member + # [START classroom_existing_alias] + service = build("classroom", "v1", credentials=creds) + alias = "d:school_math_101" + course_alias = {"alias": alias} + try: + course_alias = ( + service.courses() + .aliases() + .create(courseId=course_id, body=course_alias) + .execute() + ) return course_alias - # [END classroom_existing_alias] + except HttpError as error: + print(f"An error occurred: {error}") + print("Alias Creation Failed") + return course_alias + # [END classroom_existing_alias] -if __name__ == '__main__': - # Put the course_id of course whose alias needs to be added. - classroom_add_alias_existing(456058313539) +if __name__ == "__main__": + # Put the course_id of course whose alias needs to be added. + classroom_add_alias_existing(456058313539) # [END classroom_existing_alias] diff --git a/classroom/snippets/classroom_add_alias_new.py b/classroom/snippets/classroom_add_alias_new.py index 2412e64d..65253653 100644 --- a/classroom/snippets/classroom_add_alias_new.py +++ b/classroom/snippets/classroom_add_alias_new.py @@ -23,59 +23,59 @@ from googleapiclient.errors import HttpError # [START classroom_new_alias] - -SCOPES = ['https://www.googleapis.com/auth/classroom.courses'] +SCOPES = ["https://www.googleapis.com/auth/classroom.courses"] def classroom_add_alias_new(): - """ - Creates a course with alias specification the user has access to. - The file token.json stores the user's access and refresh tokens, and is - created automatically when the authorization flow completes for - the first time. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity for - guides on implementing OAuth2 for the application. - """ - # pylint: disable=maybe-no-member - creds = None - if os.path.exists('token.json'): - creds = Credentials.from_authorized_user_file('token.json', SCOPES) - # If there are no (valid) credentials available, let the user log in. - if not creds or not creds.valid: - if creds and creds.expired and creds.refresh_token: - creds.refresh(Request()) - else: - flow = InstalledAppFlow.from_client_secrets_file( - 'credentials.json', SCOPES) - creds = flow.run_local_server(port=0) - # Save the credentials for the next run - with open('token.json', 'w', encoding="utf8") as token: - token.write(creds.to_json()) + """ + Creates a course with alias specification the user has access to. + The file token.json stores the user's access and refresh tokens, and is + created automatically when the authorization flow completes for + the first time. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity for + guides on implementing OAuth2 for the application. + """ + # pylint: disable=maybe-no-member + creds = None + if os.path.exists("token.json"): + creds = Credentials.from_authorized_user_file("token.json", SCOPES) + # If there are no (valid) credentials available, let the user log in. + if not creds or not creds.valid: + if creds and creds.expired and creds.refresh_token: + creds.refresh(Request()) + else: + flow = InstalledAppFlow.from_client_secrets_file( + "credentials.json", SCOPES + ) + creds = flow.run_local_server(port=0) + # Save the credentials for the next run + with open("token.json", "w", encoding="utf8") as token: + token.write(creds.to_json()) - alias = 'd:school_physics_333' - course = { - 'id': alias, - 'name': 'English', - 'section': 'Period 2', - 'description': 'Course Description', - 'room': '301', - 'ownerId': 'me' - } - try: - print('-------------') - service = build('classroom', 'v1', credentials=creds) - course = service.courses().create(body=course).execute() - print('====================================') + alias = "d:school_physics_333" + course = { + "id": alias, + "name": "English", + "section": "Period 2", + "description": "Course Description", + "room": "301", + "ownerId": "me", + } + try: + print("-------------") + service = build("classroom", "v1", credentials=creds) + course = service.courses().create(body=course).execute() + print("====================================") - except HttpError as error: - print('An error occurred: %s' % error) - return course + except HttpError as error: + print(f"An error occurred: {error}") + return course -if __name__ == '__main__': - # pylint: disable=too-many-arguments - # Put the course_id of course whose alias needs to be created. - classroom_add_alias_new() +if __name__ == "__main__": + # pylint: disable=too-many-arguments + # Put the course_id of course whose alias needs to be created. + classroom_add_alias_new() # [END classroom_new_alias] diff --git a/classroom/snippets/classroom_add_attachment.py b/classroom/snippets/classroom_add_attachment.py index c5847a98..e65dfabb 100644 --- a/classroom/snippets/classroom_add_attachment.py +++ b/classroom/snippets/classroom_add_attachment.py @@ -12,49 +12,47 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - """ -from __future__ import print_function import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError -# [START classroom_add_attachment] - +# [START classroom_add_attachment] def classroom_add_attachment(course_id, coursework_id, submission_id): - """ - Adds attachment to existing course with specific course_id. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - # pylint: disable=maybe-no-member - request = { - 'addAttachments': [ - {'link': {'url': 'http://example.com/quiz-results'}}, - {'link': {'url': 'http://example.com/quiz-reading'}} - ] - } - - try: - service = build('classroom', 'v1', credentials=creds) - while True: - coursework = service.courses().courseWork() - coursework.studentSubmissions().modifyAttachments( - courseId=course_id, - courseWorkId=coursework_id, - id=submission_id, - body=request).execute() - - except HttpError as error: - print(f"An error occurred: {error}") - - -if __name__ == '__main__': - # Put the course_id, coursework_id and submission_id of course in which - # attachment needs to be added. - classroom_add_attachment('course_id', 'coursework_id', "me") + """ + Adds attachment to existing course with specific course_id. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + # pylint: disable=maybe-no-member + request = { + "addAttachments": [ + {"link": {"url": "http://example.com/quiz-results"}}, + {"link": {"url": "http://example.com/quiz-reading"}}, + ] + } + + try: + service = build("classroom", "v1", credentials=creds) + while True: + coursework = service.courses().courseWork() + coursework.studentSubmissions().modifyAttachments( + courseId=course_id, + courseWorkId=coursework_id, + id=submission_id, + body=request, + ).execute() + + except HttpError as error: + print(f"An error occurred: {error}") + + +if __name__ == "__main__": + # Put the course_id, coursework_id and submission_id of course in which + # attachment needs to be added. + classroom_add_attachment("course_id", "coursework_id", "me") # [END classroom_add_attachment] diff --git a/classroom/snippets/classroom_add_student.py b/classroom/snippets/classroom_add_student.py index a0c67539..3f7ee5f7 100644 --- a/classroom/snippets/classroom_add_student.py +++ b/classroom/snippets/classroom_add_student.py @@ -13,8 +13,6 @@ limitations under the License.""" # [START classroom_add_student] -from __future__ import print_function - import os from google.auth.transport.requests import Request @@ -23,60 +21,63 @@ from googleapiclient.discovery import build from googleapiclient.errors import HttpError -SCOPES = ['https://www.googleapis.com/auth/classroom.coursework.students'] +SCOPES = ["https://www.googleapis.com/auth/classroom.coursework.students"] def classroom_add_student_new(course_id): - """ - Adds a student to a course, the teacher has access to. - The file token.json stores the user's access and refresh tokens, and is - created automatically when the authorization flow completes for the first - time. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity for - guides on implementing OAuth2 for the application. - """ + """ + Adds a student to a course, the teacher has access to. + The file token.json stores the user's access and refresh tokens, and is + created automatically when the authorization flow completes for the first + time. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity for + guides on implementing OAuth2 for the application. + """ - creds = None - # The file token.json stores the user's access and refresh tokens, and is - # created automatically when the authorization flow completes for the first - # time. - if os.path.exists('token.json'): - creds = Credentials.from_authorized_user_file('token.json', SCOPES) - # If there are no (valid) credentials available, let the user log in. - if not creds or not creds.valid: - if creds and creds.expired and creds.refresh_token: - creds.refresh(Request()) - else: - flow = InstalledAppFlow.from_client_secrets_file( - 'credentials.json', SCOPES) - creds = flow.run_local_server(port=0) - # Save the credentials for the next run - with open('token.json', 'w', encoding="utf8") as token: - token.write(creds.to_json()) + creds = None + # The file token.json stores the user's access and refresh tokens, and is + # created automatically when the authorization flow completes for the first + # time. + if os.path.exists("token.json"): + creds = Credentials.from_authorized_user_file("token.json", SCOPES) + # If there are no (valid) credentials available, let the user log in. + if not creds or not creds.valid: + if creds and creds.expired and creds.refresh_token: + creds.refresh(Request()) + else: + flow = InstalledAppFlow.from_client_secrets_file( + "credentials.json", SCOPES + ) + creds = flow.run_local_server(port=0) + # Save the credentials for the next run + with open("token.json", "w", encoding="utf8") as token: + token.write(creds.to_json()) - enrollment_code = 'abc-def' - student = { - 'userId': 'gduser1@workspacesamples.dev' - } - try: - service = build('classroom', 'v1', credentials=creds) - student = service.courses().students().create( - courseId=course_id, - enrollmentCode=enrollment_code, - body=student).execute() - print( - '''User {%s} was enrolled as a student in + enrollment_code = "abc-def" + student = {"userId": "gduser1@workspacesamples.dev"} + try: + service = build("classroom", "v1", credentials=creds) + student = ( + service.courses() + .students() + .create( + courseId=course_id, enrollmentCode=enrollment_code, body=student + ) + .execute() + ) + print( + '''User {%s} was enrolled as a student in the course with ID "{%s}"''' - % (student.get('profile').get('name').get('fullName'), - course_id)) - return student - except HttpError as error: - print(error) - return error + % (student.get("profile").get("name").get("fullName"), course_id) + ) + return student + except HttpError as error: + print(error) + return error -if __name__ == '__main__': - # Put the course_id of course for which student needs to be added. - classroom_add_student_new(478800920837) +if __name__ == "__main__": + # Put the course_id of course for which student needs to be added. + classroom_add_student_new(478800920837) # [END classroom_add_student] diff --git a/classroom/snippets/classroom_add_teacher.py b/classroom/snippets/classroom_add_teacher.py index 981a1fb5..9b86b715 100644 --- a/classroom/snippets/classroom_add_teacher.py +++ b/classroom/snippets/classroom_add_teacher.py @@ -19,36 +19,33 @@ def classroom_add_teacher(course_id): - """ - Adds a teacher to a course with specific course_id. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - # pylint: disable=maybe-no-member - service = build('classroom', 'v1', credentials=creds) - - teacher_email = 'gduser1@workspacesamples.dev' - teacher = { - 'userId': teacher_email - } - - try: - teachers = service.courses().teachers() - teacher = teachers.create(courseId=course_id, - body=teacher).execute() - print('User %s was added as a teacher to the course with ID %s' - % (teacher.get('profile').get('name').get('fullName'), - course_id)) - except HttpError as error: - print('User "{%s}" is already a member of this course.' - % teacher_email) - return error - return teachers - - -if __name__ == '__main__': - # Put the course_id of course for which Teacher needs to be added. - classroom_add_teacher(453686957652) + """ + Adds a teacher to a course with specific course_id. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + # pylint: disable=maybe-no-member + service = build("classroom", "v1", credentials=creds) + + teacher_email = "gduser1@workspacesamples.dev" + teacher = {"userId": teacher_email} + + try: + teachers = service.courses().teachers() + teacher = teachers.create(courseId=course_id, body=teacher).execute() + print( + "User %s was added as a teacher to the course with ID %s" + % (teacher.get("profile").get("name").get("fullName"), course_id) + ) + except HttpError as error: + print('User "{%s}" is already a member of this course.' % teacher_email) + return error + return teachers + + +if __name__ == "__main__": + # Put the course_id of course for which Teacher needs to be added. + classroom_add_teacher(453686957652) # [END classroom_add_teacher] diff --git a/classroom/snippets/classroom_all_submissions.py b/classroom/snippets/classroom_all_submissions.py index a5823724..1c505fc2 100644 --- a/classroom/snippets/classroom_all_submissions.py +++ b/classroom/snippets/classroom_all_submissions.py @@ -12,61 +12,64 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - """ -from __future__ import print_function import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError -# [START classroom_all_submissions] - +# [START classroom_all_submissions] def classroom_all_submissions(course_id, user_id): - """ - Creates the list of all submissions of the courses the user has access to. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ + """ + Creates the list of all submissions of the courses the user has access to. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ - creds, _ = google.auth.default() - # pylint: disable=maybe-no-member - submissions = [] - page_token = None + creds, _ = google.auth.default() + # pylint: disable=maybe-no-member + submissions = [] + page_token = None - try: - service = build('classroom', 'v1', credentials=creds) - while True: - coursework = service.courses().courseWork() - response = coursework.studentSubmissions().list( - pageToken=page_token, - courseId=course_id, - courseWorkId="-", - userId=user_id).execute() - submissions.extend(response.get('studentSubmissions', [])) - page_token = response.get('nextPageToken', None) - if not page_token: - break + try: + service = build("classroom", "v1", credentials=creds) + while True: + coursework = service.courses().courseWork() + response = ( + coursework.studentSubmissions() + .list( + pageToken=page_token, + courseId=course_id, + courseWorkId="-", + userId=user_id, + ) + .execute() + ) + submissions.extend(response.get("studentSubmissions", [])) + page_token = response.get("nextPageToken", None) + if not page_token: + break - if not submissions: - print('No student submissions found.') - else: - print('Complete list of student Submissions:') - for submission in submissions: - print("%s was submitted at %s" % - (submission.get('id'), - submission.get('creationTime'))) + if not submissions: + print("No student submissions found.") + else: + print("Complete list of student Submissions:") + for submission in submissions: + print( + f"{submission.get('id')} was submitted at" + f" {submission.get('creationTime')}" + ) - except HttpError as error: - print(f"An error occurred: {error}") - submissions = None - return submissions + except HttpError as error: + print(f"An error occurred: {error}") + submissions = None + return submissions -if __name__ == '__main__': - # Put the course_id and user_id of course whose list needs to be - # submitted. - classroom_all_submissions(453686957652, 466086979658) +if __name__ == "__main__": + # Put the course_id and user_id of course whose list needs to be + # submitted. + classroom_all_submissions(453686957652, 466086979658) # [END classroom_all_submissions] diff --git a/classroom/snippets/classroom_create_course.py b/classroom/snippets/classroom_create_course.py index 1f2afa77..c471d1d8 100644 --- a/classroom/snippets/classroom_create_course.py +++ b/classroom/snippets/classroom_create_course.py @@ -12,55 +12,50 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - """ # [START classroom_create_course] - -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def classroom_create_course(): - - """ - Creates the courses the user has access to. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - - creds, _ = google.auth.default() - # pylint: disable=maybe-no-member - - try: - service = build('classroom', 'v1', credentials=creds) - course = { - 'name': '10th Grade Mathematics Probability-2', - 'section': 'Period 3', - 'descriptionHeading': 'Welcome to 10th Grade Mathematics', - 'description': """We'll be learning about about the + """ + Creates the courses the user has access to. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + + creds, _ = google.auth.default() + # pylint: disable=maybe-no-member + + try: + service = build("classroom", "v1", credentials=creds) + course = { + "name": "10th Grade Mathematics Probability-2", + "section": "Period 3", + "descriptionHeading": "Welcome to 10th Grade Mathematics", + "description": """We'll be learning about about the polynomials from a combination of textbooks and guest lectures. Expect to be excited!""", - 'room': '302', - 'ownerId': 'me', - 'courseState': 'PROVISIONED' - } - # pylint: disable=maybe-no-member - course = service.courses().create(body=course).execute() - print(f"Course created: {(course.get('name'), course.get('id'))}") - return course + "room": "302", + "ownerId": "me", + "courseState": "PROVISIONED", + } + # pylint: disable=maybe-no-member + course = service.courses().create(body=course).execute() + print(f"Course created: {(course.get('name'), course.get('id'))}") + return course - except HttpError as error: - print(f"An error occurred: {error}") - return error + except HttpError as error: + print(f"An error occurred: {error}") + return error -if __name__ == '__main__': - classroom_create_course() +if __name__ == "__main__": + classroom_create_course() # [END classroom_create_course] diff --git a/classroom/snippets/classroom_create_coursework.py b/classroom/snippets/classroom_create_coursework.py index 060c3fcb..7a41392a 100644 --- a/classroom/snippets/classroom_create_coursework.py +++ b/classroom/snippets/classroom_create_coursework.py @@ -12,53 +12,54 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - """ -# [START classroom_create_coursework] -from __future__ import print_function +# [START classroom_create_coursework] import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def classroom_create_coursework(course_id): + """ + Creates the coursework the user has access to. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ - """ - Creates the coursework the user has access to. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - - creds, _ = google.auth.default() - # pylint: disable=maybe-no-member + creds, _ = google.auth.default() + # pylint: disable=maybe-no-member - try: - service = build('classroom', 'v1', credentials=creds) - coursework = { - 'title': 'Ant colonies', - 'description': '''Read the article about ant colonies - and complete the quiz.''', - 'materials': [ - {'link': {'url': 'http://example.com/ant-colonies'}}, - {'link': {'url': 'http://example.com/ant-quiz'}} - ], - 'workType': 'ASSIGNMENT', - 'state': 'PUBLISHED', - } - coursework = service.courses().courseWork().create( - courseId=course_id, body=coursework).execute() - print(f"Assignment created with ID {coursework.get('id')}") - return coursework + try: + service = build("classroom", "v1", credentials=creds) + coursework = { + "title": "Ant colonies", + "description": """Read the article about ant colonies + and complete the quiz.""", + "materials": [ + {"link": {"url": "http://example.com/ant-colonies"}}, + {"link": {"url": "http://example.com/ant-quiz"}}, + ], + "workType": "ASSIGNMENT", + "state": "PUBLISHED", + } + coursework = ( + service.courses() + .courseWork() + .create(courseId=course_id, body=coursework) + .execute() + ) + print(f"Assignment created with ID {coursework.get('id')}") + return coursework - except HttpError as error: - print(f"An error occurred: {error}") - return error + except HttpError as error: + print(f"An error occurred: {error}") + return error -if __name__ == '__main__': - # Put the course_id of course whose coursework needs to be created, - # the user has access to. - classroom_create_coursework(453686957652) +if __name__ == "__main__": + # Put the course_id of course whose coursework needs to be created, + # the user has access to. + classroom_create_coursework(453686957652) # [END classroom_create_coursework] diff --git a/classroom/snippets/classroom_get_course.py b/classroom/snippets/classroom_get_course.py index 586ecc63..f91f31c5 100644 --- a/classroom/snippets/classroom_get_course.py +++ b/classroom/snippets/classroom_get_course.py @@ -12,42 +12,38 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - """ # [START classroom_get_course] -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def classroom_get_course(course_id): - - """ - Prints the name of the with specific course_id. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - - creds, _ = google.auth.default() - # pylint: disable=maybe-no-member - course = None - try: - service = build('classroom', 'v1', credentials=creds) - course = service.courses().get(id=course_id).execute() - print(f"Course found : {course.get('name')}") - except HttpError as error: - print(f"An error occurred: {error}") - print(f"Course not found: {course_id}") - return error - return course - - -if __name__ == '__main__': - # Put the course_id of course whose information needs to be fetched. - classroom_get_course('course_id') + """ + Prints the name of the with specific course_id. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + + creds, _ = google.auth.default() + # pylint: disable=maybe-no-member + course = None + try: + service = build("classroom", "v1", credentials=creds) + course = service.courses().get(id=course_id).execute() + print(f"Course found : {course.get('name')}") + except HttpError as error: + print(f"An error occurred: {error}") + print(f"Course not found: {course_id}") + return error + return course + + +if __name__ == "__main__": + # Put the course_id of course whose information needs to be fetched. + classroom_get_course("course_id") # [END classroom_get_courses] diff --git a/classroom/snippets/classroom_invite_guardian.py b/classroom/snippets/classroom_invite_guardian.py index 9cab0ec5..8b260c39 100644 --- a/classroom/snippets/classroom_invite_guardian.py +++ b/classroom/snippets/classroom_invite_guardian.py @@ -12,48 +12,48 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - """ -from __future__ import print_function import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError -# [START classroom_invite_guardian] - +# [START classroom_invite_guardian] def classroom_invite_guardian(): - """ - Creates the courses the user has access to. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - - creds, _ = google.auth.default() - # pylint: disable=maybe-no-member - guardian_invitation = { - 'invitedEmailAddress': 'guardian@gmail.com', - } - - try: - service = build('classroom', 'v1', credentials=creds) - while True: - guardian_invitations = service.userProfiles().guardianInvitations() - guardian_invitation = guardian_invitations.create( - # You can use a user ID or an email address. - studentId='student@mydomain.edu', - body=guardian_invitation).execute() - print("Invitation created with id: {%s}" - % guardian_invitation.get('invitationId')) - - except HttpError as error: - print(f"An error occurred: {error}") - - -if __name__ == '__main__': - # Put the course_id, coursework_id and user_id of course whose list needs - # to be submitted. - classroom_invite_guardian() + """ + Creates the courses the user has access to. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + + creds, _ = google.auth.default() + # pylint: disable=maybe-no-member + guardian_invitation = { + "invitedEmailAddress": "guardian@gmail.com", + } + + try: + service = build("classroom", "v1", credentials=creds) + while True: + guardian_invitations = service.userProfiles().guardianInvitations() + guardian_invitation = guardian_invitations.create( + # You can use a user ID or an email address. + studentId="student@mydomain.edu", + body=guardian_invitation, + ).execute() + print( + "Invitation created with id: {%s}" + % guardian_invitation.get("invitationId") + ) + + except HttpError as error: + print(f"An error occurred: {error}") + + +if __name__ == "__main__": + # Put the course_id, coursework_id and user_id of course whose list needs + # to be submitted. + classroom_invite_guardian() # [END classroom_invite_guardian] diff --git a/classroom/snippets/classroom_list_course_aliases.py b/classroom/snippets/classroom_list_course_aliases.py index ec73e3a3..562e13c6 100644 --- a/classroom/snippets/classroom_list_course_aliases.py +++ b/classroom/snippets/classroom_list_course_aliases.py @@ -12,54 +12,53 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - """ # [START classroom_list_course_aliases] - -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def classroom_list_course_aliases(course_id): - """ - Prints the list of the aliases of a specified course the user has access to. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - - creds, _ = google.auth.default() - try: - service = build('classroom', 'v1', credentials=creds) - course_aliases = [] - page_token = None - - while True: - response = service.courses().aliases().list( - pageToken=page_token, - courseId=course_id).execute() - course_aliases.extend(response.get('aliases', [])) - page_token = response.get('nextPageToken', None) - if not page_token: - break - - if not course_aliases: - print('No course aliases found.') - - print("Course aliases:") - for course_alias in course_aliases: - print(f"{course_alias.get('alias')}") - return course_aliases - except HttpError as error: - print(f"An error occurred: {error}") - return error - - -if __name__ == '__main__': - classroom_list_course_aliases('course_id') + """ + Prints the list of the aliases of a specified course the user has access to. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + + creds, _ = google.auth.default() + try: + service = build("classroom", "v1", credentials=creds) + course_aliases = [] + page_token = None + + while True: + response = ( + service.courses() + .aliases() + .list(pageToken=page_token, courseId=course_id) + .execute() + ) + course_aliases.extend(response.get("aliases", [])) + page_token = response.get("nextPageToken", None) + if not page_token: + break + + if not course_aliases: + print("No course aliases found.") + + print("Course aliases:") + for course_alias in course_aliases: + print(f"{course_alias.get('alias')}") + return course_aliases + except HttpError as error: + print(f"An error occurred: {error}") + return error + + +if __name__ == "__main__": + classroom_list_course_aliases("course_id") # [END classroom_list_course_aliases] diff --git a/classroom/snippets/classroom_list_courses.py b/classroom/snippets/classroom_list_courses.py index a811d56d..6e8c97cd 100644 --- a/classroom/snippets/classroom_list_courses.py +++ b/classroom/snippets/classroom_list_courses.py @@ -12,56 +12,52 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - """ # [START classroom_list_courses] - -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def classroom_list_courses(): - - """ - Prints the list of the courses the user has access to. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - - creds, _ = google.auth.default() - try: - service = build('classroom', 'v1', credentials=creds) - courses = [] - page_token = None - - while True: - # pylint: disable=maybe-no-member - response = service.courses().list(pageToken=page_token, - pageSize=100).execute() - courses.extend(response.get('courses', [])) - page_token = response.get('nextPageToken', None) - if not page_token: - break - - if not courses: - print("No courses found.") - return - print("Courses:") - for course in courses: - print(f"{course.get('name'), course.get('id')}") - return courses - except HttpError as error: - print(f"An error occurred: {error}") - return error - - -if __name__ == '__main__': - print('Courses available are-------') - classroom_list_courses() + """ + Prints the list of the courses the user has access to. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + + creds, _ = google.auth.default() + try: + service = build("classroom", "v1", credentials=creds) + courses = [] + page_token = None + + while True: + # pylint: disable=maybe-no-member + response = ( + service.courses().list(pageToken=page_token, pageSize=100).execute() + ) + courses.extend(response.get("courses", [])) + page_token = response.get("nextPageToken", None) + if not page_token: + break + + if not courses: + print("No courses found.") + return + print("Courses:") + for course in courses: + print(f"{course.get('name'), course.get('id')}") + return courses + except HttpError as error: + print(f"An error occurred: {error}") + return error + + +if __name__ == "__main__": + print("Courses available are-------") + classroom_list_courses() # [END classroom_list_courses] diff --git a/classroom/snippets/classroom_list_student_submissions.py b/classroom/snippets/classroom_list_student_submissions.py index 569e9593..c56ea8de 100644 --- a/classroom/snippets/classroom_list_student_submissions.py +++ b/classroom/snippets/classroom_list_student_submissions.py @@ -12,58 +12,63 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - """ -# [START classroom_list_student_submissions] -from __future__ import print_function +# [START classroom_list_student_submissions] import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def classroom_list_student_submissions(course_id, coursework_id, user_id): - """ - Creates the courses the user has access to. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ + """ + Creates the courses the user has access to. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ - creds, _ = google.auth.default() - # pylint: disable=maybe-no-member - submissions = [] - page_token = None + creds, _ = google.auth.default() + # pylint: disable=maybe-no-member + submissions = [] + page_token = None - try: - service = build('classroom', 'v1', credentials=creds) - while True: - coursework = service.courses().courseWork() - response = coursework.studentSubmissions().list( - pageToken=page_token, - courseId=course_id, - courseWorkId=coursework_id, - userId=user_id).execute() - submissions.extend(response.get('studentSubmissions', [])) - page_token = response.get('nextPageToken', None) - if not page_token: - break + try: + service = build("classroom", "v1", credentials=creds) + while True: + coursework = service.courses().courseWork() + response = ( + coursework.studentSubmissions() + .list( + pageToken=page_token, + courseId=course_id, + courseWorkId=coursework_id, + userId=user_id, + ) + .execute() + ) + submissions.extend(response.get("studentSubmissions", [])) + page_token = response.get("nextPageToken", None) + if not page_token: + break - if not submissions: - print('No student submissions found.') + if not submissions: + print("No student submissions found.") - print('Student Submissions:') - for submission in submissions: - print(f"Submitted at:" - f"{(submission.get('id'), submission.get('creationTime'))}") + print("Student Submissions:") + for submission in submissions: + print( + "Submitted at:" + f"{(submission.get('id'), submission.get('creationTime'))}" + ) - except HttpError as error: - print(f"An error occurred: {error}") - return submissions + except HttpError as error: + print(f"An error occurred: {error}") + return submissions -if __name__ == '__main__': - # Put the course_id, coursework_id and user_id of course whose list needs - # to be submitted. - classroom_list_student_submissions(453686957652, 466086979658, "me") +if __name__ == "__main__": + # Put the course_id, coursework_id and user_id of course whose list needs + # to be submitted. + classroom_list_student_submissions(453686957652, 466086979658, "me") # [END classroom_list_student_submissions] diff --git a/classroom/snippets/classroom_list_submissions.py b/classroom/snippets/classroom_list_submissions.py index ae68dbb1..e7040954 100644 --- a/classroom/snippets/classroom_list_submissions.py +++ b/classroom/snippets/classroom_list_submissions.py @@ -12,59 +12,64 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - """ -# [START classroom_list_submissions] -from __future__ import print_function +# [START classroom_list_submissions] import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def classroom_list_submissions(course_id, coursework_id): - """ - Creates the courses the user has access to. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ + """ + Creates the courses the user has access to. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ - creds, _ = google.auth.default() - # pylint: disable=maybe-no-member - submissions = [] - page_token = None + creds, _ = google.auth.default() + # pylint: disable=maybe-no-member + submissions = [] + page_token = None - try: - service = build('classroom', 'v1', credentials=creds) - while True: - coursework = service.courses().courseWork() - response = coursework.studentSubmissions().list( - pageToken=page_token, - courseId=course_id, - courseWorkId=coursework_id, - pageSize=10).execute() - submissions.extend(response.get('studentSubmissions', [])) - page_token = response.get('nextPageToken', None) - if not page_token: - break + try: + service = build("classroom", "v1", credentials=creds) + while True: + coursework = service.courses().courseWork() + response = ( + coursework.studentSubmissions() + .list( + pageToken=page_token, + courseId=course_id, + courseWorkId=coursework_id, + pageSize=10, + ) + .execute() + ) + submissions.extend(response.get("studentSubmissions", [])) + page_token = response.get("nextPageToken", None) + if not page_token: + break - if not submissions: - print('No student submissions found.') + if not submissions: + print("No student submissions found.") - print('Student Submissions:') - for submission in submissions: - print(f"Submitted at:" - f"{(submission.get('id'), submission.get('creationTime'))}") + print("Student Submissions:") + for submission in submissions: + print( + "Submitted at:" + f"{(submission.get('id'), submission.get('creationTime'))}" + ) - except HttpError as error: - print(f"An error occurred: {error}") - submissions = None - return submissions + except HttpError as error: + print(f"An error occurred: {error}") + submissions = None + return submissions -if __name__ == '__main__': - # Put the course_id and coursework_id of course whose list needs to be - # submitted. - classroom_list_submissions(453686957652, 466086979658) +if __name__ == "__main__": + # Put the course_id and coursework_id of course whose list needs to be + # submitted. + classroom_list_submissions(453686957652, 466086979658) # [END classroom_list_submissions] diff --git a/classroom/snippets/classroom_patch_course.py b/classroom/snippets/classroom_patch_course.py index 8311c0f4..e1e02420 100644 --- a/classroom/snippets/classroom_patch_course.py +++ b/classroom/snippets/classroom_patch_course.py @@ -14,44 +14,39 @@ """ # [START classroom_patch_course] - -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def classroom_patch_course(course_id): - - """ - Patch new course with existing course in the account the user has access to. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - # pylint: disable=maybe-no-member - - creds, _ = google.auth.default() - - try: - service = build('classroom', 'v1', credentials=creds) - course = { - 'section': 'Period 3', - 'room': '313' - } - course = service.courses().patch(id=course_id, - updateMask='section,room', - body=course).execute() - print(f" Course updated are: {course.get('name')}") - return course - except HttpError as error: - print(f"An error occurred: {error}") - - -if __name__ == '__main__': - # Put the course_id of course with whom we need to patch some extra - # information. - classroom_patch_course('course_id') + """ + Patch new course with existing course in the account the user has access to. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + # pylint: disable=maybe-no-member + + creds, _ = google.auth.default() + + try: + service = build("classroom", "v1", credentials=creds) + course = {"section": "Period 3", "room": "313"} + course = ( + service.courses() + .patch(id=course_id, updateMask="section,room", body=course) + .execute() + ) + print(f" Course updated are: {course.get('name')}") + return course + except HttpError as error: + print(f"An error occurred: {error}") + + +if __name__ == "__main__": + # Put the course_id of course with whom we need to patch some extra + # information. + classroom_patch_course("course_id") # [END classroom_patch_course] diff --git a/classroom/snippets/classroom_update_course.py b/classroom/snippets/classroom_update_course.py index f3e05d62..25ac1f3e 100644 --- a/classroom/snippets/classroom_update_course.py +++ b/classroom/snippets/classroom_update_course.py @@ -15,44 +15,41 @@ """ # [START classroom_update_course] - -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def classroom_update_course(course_id): - """ - Updates the courses names the user has access to. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - # pylint: disable=maybe-no-member - - creds, _ = google.auth.default() - - try: - service = build('classroom', 'v1', credentials=creds) - - # Updates the section and room of Google Classroom. - course = service.courses().get(id=course_id).execute() - course['name'] = '10th Grade Physics - Light' - course['section'] = 'Period 4' - course['room'] = '410' - course = service.courses().update(id=course_id, body=course).execute() - print(f" Updated Course is: {course.get('name')}") - return course - - except HttpError as error: - print(f"An error occurred: {error}") - return error - - -if __name__ == '__main__': - # Put the course_id of course whose course needs to be updated. - classroom_update_course('course_id') + """ + Updates the courses names the user has access to. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + # pylint: disable=maybe-no-member + + creds, _ = google.auth.default() + + try: + service = build("classroom", "v1", credentials=creds) + + # Updates the section and room of Google Classroom. + course = service.courses().get(id=course_id).execute() + course["name"] = "10th Grade Physics - Light" + course["section"] = "Period 4" + course["room"] = "410" + course = service.courses().update(id=course_id, body=course).execute() + print(f" Updated Course is: {course.get('name')}") + return course + + except HttpError as error: + print(f"An error occurred: {error}") + return error + + +if __name__ == "__main__": + # Put the course_id of course whose course needs to be updated. + classroom_update_course("course_id") # [END classroom_update_course] diff --git a/classroom/snippets/test_classroom_create_course.py b/classroom/snippets/test_classroom_create_course.py index bdae719e..8d5c76da 100644 --- a/classroom/snippets/test_classroom_create_course.py +++ b/classroom/snippets/test_classroom_create_course.py @@ -18,13 +18,14 @@ class TestClassroomCreateCourse(BaseTest): - """Unit test class for Create course snippet""" - def test_classroom_create_course(self): - """Class function for Create course snippet""" - course = classroom_create_course.classroom_create_course() - self.assertIsNotNone(course) - self.delete_course_on_cleanup(course.get('id')) + """Unit test class for Create course snippet""" + + def test_classroom_create_course(self): + """Class function for Create course snippet""" + course = classroom_create_course.classroom_create_course() + self.assertIsNotNone(course) + self.delete_course_on_cleanup(course.get("id")) if __name__ == "__main__": - unittest.main() + unittest.main() diff --git a/classroom/snippets/test_classroom_get_course.py b/classroom/snippets/test_classroom_get_course.py index d28c9e1d..0ca05299 100644 --- a/classroom/snippets/test_classroom_get_course.py +++ b/classroom/snippets/test_classroom_get_course.py @@ -11,7 +11,6 @@ limitations under the License. """ - import unittest import classroom_create_course @@ -20,16 +19,16 @@ class TestClassroomGetCourse(BaseTest): - """Unit test class for Get course snippet""" - def test_classroom_get_course(self): - """Unit test method for Get course snippet""" - course = classroom_create_course.classroom_create_course() - self.assertIsNotNone(course) - self.delete_course_on_cleanup(course.get('id')) - course_id = classroom_get_course.classroom_get_course(course.get( - 'id')) - self.assertIsNotNone(course_id) + """Unit test class for Get course snippet""" + + def test_classroom_get_course(self): + """Unit test method for Get course snippet""" + course = classroom_create_course.classroom_create_course() + self.assertIsNotNone(course) + self.delete_course_on_cleanup(course.get("id")) + course_id = classroom_get_course.classroom_get_course(course.get("id")) + self.assertIsNotNone(course_id) if __name__ == "__main__": - unittest.main() + unittest.main() diff --git a/classroom/snippets/test_classroom_list_course_aliases.py b/classroom/snippets/test_classroom_list_course_aliases.py index 5f2dac41..f68b81ea 100644 --- a/classroom/snippets/test_classroom_list_course_aliases.py +++ b/classroom/snippets/test_classroom_list_course_aliases.py @@ -10,6 +10,7 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest from base_test import BaseTest @@ -18,16 +19,16 @@ class TestClassroomListCourseAliases(BaseTest): - """Unit test class for List course aliases snippet""" + """Unit test class for List course aliases snippet""" - def test_classroom_list_course_aliases(self): - """Unit test method for List course snippet""" - course = classroom_create_course() - self.assertIsNotNone(course) - self.delete_course_on_cleanup(course.get('id')) - course_aliases = classroom_list_course_aliases(course.get('id')) - self.assertIsNotNone(course_aliases) + def test_classroom_list_course_aliases(self): + """Unit test method for List course snippet""" + course = classroom_create_course() + self.assertIsNotNone(course) + self.delete_course_on_cleanup(course.get("id")) + course_aliases = classroom_list_course_aliases(course.get("id")) + self.assertIsNotNone(course_aliases) if __name__ == "__main__": - unittest.main() + unittest.main() diff --git a/classroom/snippets/test_classroom_list_courses.py b/classroom/snippets/test_classroom_list_courses.py index 232b1627..81fc27f1 100644 --- a/classroom/snippets/test_classroom_list_courses.py +++ b/classroom/snippets/test_classroom_list_courses.py @@ -10,6 +10,7 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest import classroom_create_course @@ -18,15 +19,16 @@ class TestClassroomListCourses(BaseTest): - """Unit test class for List course snippet""" - def test_classroom_list_courses(self): - """Unit test method for List course snippet""" - course = classroom_create_course.classroom_create_course() - self.assertIsNotNone(course) - self.delete_course_on_cleanup(course.get('id')) - courses = classroom_list_courses.classroom_list_courses() - self.assertIsNotNone(courses) + """Unit test class for List course snippet""" + + def test_classroom_list_courses(self): + """Unit test method for List course snippet""" + course = classroom_create_course.classroom_create_course() + self.assertIsNotNone(course) + self.delete_course_on_cleanup(course.get("id")) + courses = classroom_list_courses.classroom_list_courses() + self.assertIsNotNone(courses) if __name__ == "__main__": - unittest.main() + unittest.main() diff --git a/classroom/snippets/test_classroom_patch_course.py b/classroom/snippets/test_classroom_patch_course.py index 3759aa61..43a4862f 100644 --- a/classroom/snippets/test_classroom_patch_course.py +++ b/classroom/snippets/test_classroom_patch_course.py @@ -10,6 +10,7 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest import classroom_create_course @@ -18,15 +19,16 @@ class TestClassroomPatchCourse(BaseTest): - """Unit test class for Patch course snippet""" - def test_classroom_patch_course(self): - """Unit test method for Patch course snippet""" - course = classroom_create_course.classroom_create_course() - self.assertIsNotNone(course) - self.delete_course_on_cleanup(course.get('id')) - course = classroom_patch_course.classroom_patch_course(course.get('id')) - self.assertIsNotNone(course) + """Unit test class for Patch course snippet""" + + def test_classroom_patch_course(self): + """Unit test method for Patch course snippet""" + course = classroom_create_course.classroom_create_course() + self.assertIsNotNone(course) + self.delete_course_on_cleanup(course.get("id")) + course = classroom_patch_course.classroom_patch_course(course.get("id")) + self.assertIsNotNone(course) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/classroom/snippets/test_classroom_update_course.py b/classroom/snippets/test_classroom_update_course.py index c8477f29..ccfcdd4b 100644 --- a/classroom/snippets/test_classroom_update_course.py +++ b/classroom/snippets/test_classroom_update_course.py @@ -10,6 +10,7 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest import classroom_create_course @@ -18,15 +19,16 @@ class TestClassroomUpdateCourse(BaseTest): - """Unit test class for Get course snippet""" - def test_classroom_update_course(self): - """Unit test method for Get course snippet""" - course = classroom_create_course.classroom_create_course() - self.assertIsNotNone(course) - self.delete_course_on_cleanup(course.get('id')) - course = classroom_update_course.classroom_update_course(course.get('id')) - self.assertIsNotNone(course) + """Unit test class for Get course snippet""" + + def test_classroom_update_course(self): + """Unit test method for Get course snippet""" + course = classroom_create_course.classroom_create_course() + self.assertIsNotNone(course) + self.delete_course_on_cleanup(course.get("id")) + course = classroom_update_course.classroom_update_course(course.get("id")) + self.assertIsNotNone(course) if __name__ == "__main__": - unittest.main() + unittest.main() diff --git a/docs/mail-merge/docs_mail_merge.py b/docs/mail-merge/docs_mail_merge.py index 82aa6dae..fe946487 100644 --- a/docs/mail-merge/docs_mail_merge.py +++ b/docs/mail-merge/docs_mail_merge.py @@ -19,8 +19,6 @@ Google Docs (REST) API mail-merge sample app """ # [START mail_merge_python] -from __future__ import print_function - import time import google.auth @@ -34,20 +32,28 @@ # authorization constants SCOPES = ( # iterable or space-delimited string - 'https://www.googleapis.com/auth/drive', - 'https://www.googleapis.com/auth/documents', - 'https://www.googleapis.com/auth/spreadsheets.readonly', + "https://www.googleapis.com/auth/drive", + "https://www.googleapis.com/auth/documents", + "https://www.googleapis.com/auth/spreadsheets.readonly", ) # application constants -SOURCES = ('text', 'sheets') -SOURCE = 'text' # Choose one of the data SOURCES -COLUMNS = ['to_name', 'to_title', 'to_company', 'to_address'] +SOURCES = ("text", "sheets") +SOURCE = "text" # Choose one of the data SOURCES +COLUMNS = ["to_name", "to_title", "to_company", "to_address"] TEXT_SOURCE_DATA = ( - ('Ms. Lara Brown', 'Googler', 'Google NYC', '111 8th Ave\n' - 'New York, NY 10011-5201'), - ('Mr. Jeff Erson', 'Googler', 'Google NYC', '76 9th Ave\n' - 'New York, NY 10011-4962'), + ( + "Ms. Lara Brown", + "Googler", + "Google NYC", + "111 8th Ave\nNew York, NY 10011-5201", + ), + ( + "Mr. Jeff Erson", + "Googler", + "Google NYC", + "76 9th Ave\nNew York, NY 10011-4962", + ), ) creds, _ = google.auth.default() @@ -55,113 +61,128 @@ # service endpoints to Google APIs -DRIVE = build('drive', 'v2', credentials=creds) -DOCS = build('docs', 'v1', credentials=creds) -SHEETS = build('sheets', 'v4', credentials=creds) +DRIVE = build("drive", "v2", credentials=creds) +DOCS = build("docs", "v1", credentials=creds) +SHEETS = build("sheets", "v4", credentials=creds) def get_data(source): - """Gets mail merge data from chosen data source. - """ - try: - if source not in {'sheets', 'text'}: - raise ValueError(f"ERROR: unsupported source {source}; " - f"choose from {SOURCES}") - return SAFE_DISPATCH[source]() - except HttpError as error: - print(f"An error occurred: {error}") - return error + """Gets mail merge data from chosen data source.""" + try: + if source not in {"sheets", "text"}: + raise ValueError( + f"ERROR: unsupported source {source}; choose from {SOURCES}" + ) + return SAFE_DISPATCH[source]() + except HttpError as error: + print(f"An error occurred: {error}") + return error def _get_text_data(): - """(private) Returns plain text data; can alter to read from CSV file. - """ - return TEXT_SOURCE_DATA + """(private) Returns plain text data; can alter to read from CSV file.""" + return TEXT_SOURCE_DATA def _get_sheets_data(service=SHEETS): - """(private) Returns data from Google Sheets source. It gets all rows of - 'Sheet1' (the default Sheet in a new spreadsheet), but drops the first - (header) row. Use any desired data range (in standard A1 notation). - """ - return service.spreadsheets().values().get(spreadsheetId=SHEETS_FILE_ID, - range='Sheet1').execute().get( - 'values')[1:] - # skip header row + """(private) Returns data from Google Sheets source. It gets all rows of + 'Sheet1' (the default Sheet in a new spreadsheet), but drops the first + (header) row. Use any desired data range (in standard A1 notation). + """ + return ( + service.spreadsheets() + .values() + .get(spreadsheetId=SHEETS_FILE_ID, range="Sheet1") + .execute() + .get("values")[1:] + ) + # skip header row # data source dispatch table [better alternative vs. eval()] -SAFE_DISPATCH = {k: globals().get('_get_%s_data' % k) for k in SOURCES} +SAFE_DISPATCH = {k: globals().get(f"_get_{k}_data") for k in SOURCES} def _copy_template(tmpl_id, source, service): - """(private) Copies letter template document using Drive API then - returns file ID of (new) copy. - """ - try: - body = {'name': 'Merged form letter (%s)' % source} - return service.files().copy(body=body, fileId=tmpl_id, - fields='id').execute().get('id') - except HttpError as error: - print(f"An error occurred: {error}") - return error + """(private) Copies letter template document using Drive API then + returns file ID of (new) copy. + """ + try: + body = {"name": f"Merged form letter ({source})"} + return ( + service.files() + .copy(body=body, fileId=tmpl_id, fields="id") + .execute() + .get("id") + ) + except HttpError as error: + print(f"An error occurred: {error}") + return error def merge_template(tmpl_id, source, service): - """Copies template document and merges data into newly-minted copy then - returns its file ID. - """ - try: - # copy template and set context data struct for merging template values - copy_id = _copy_template(tmpl_id, source, service) - context = merge.iteritems() if hasattr({}, - 'iteritems') else merge.items() - - # "search & replace" API requests for mail merge substitutions - reqs = [{'replaceAllText': { - 'containsText': { - 'text': '{{%s}}' % key.upper(), # {{VARS}} are uppercase - 'matchCase': True, - }, - 'replaceText': value, - }} for key, value in context] - - # send requests to Docs API to do actual merge - DOCS.documents().batchUpdate(body={'requests': reqs}, - documentId=copy_id, fields='').execute() - return copy_id - except HttpError as error: - print(f"An error occurred: {error}") - return error - - -if __name__ == '__main__': - # fill-in your data to merge into document template variables - merge = { - # sender data - 'my_name': 'Ayme A. Coder', - 'my_address': '1600 Amphitheatre Pkwy\n' - 'Mountain View, CA 94043-1351', - 'my_email': 'http://google.com', - 'my_phone': '+1-650-253-0000', - # - - - - - - - - - - - - - - - - - - - - - - - - - - - # recipient data (supplied by 'text' or 'sheets' data source) - 'to_name': None, - 'to_title': None, - 'to_company': None, - 'to_address': None, - # - - - - - - - - - - - - - - - - - - - - - - - - - - - 'date': time.strftime('%Y %B %d'), - # - - - - - - - - - - - - - - - - - - - - - - - - - - - 'body': 'Google, headquartered in Mountain View, unveiled the new ' - 'Android phone at the Consumer Electronics Show. CEO Sundar ' - 'Pichai said in his keynote that users love their new phones.' - } - - # get row data, then loop through & process each form letter - data = get_data(SOURCE) # get data from data source - for i, row in enumerate(data): - merge.update(dict(zip(COLUMNS, row))) - print('Merged letter %d: docs.google.com/document/d/%s/edit' % ( - i + 1, merge_template(DOCS_FILE_ID, SOURCE, DRIVE))) + """Copies template document and merges data into newly-minted copy then + returns its file ID. + """ + try: + # copy template and set context data struct for merging template values + copy_id = _copy_template(tmpl_id, source, service) + context = merge.iteritems() if hasattr({}, "iteritems") else merge.items() + + # "search & replace" API requests for mail merge substitutions + reqs = [ + { + "replaceAllText": { + "containsText": { + "text": "{{%s}}" % key.upper(), # {{VARS}} are uppercase + "matchCase": True, + }, + "replaceText": value, + } + } + for key, value in context + ] + + # send requests to Docs API to do actual merge + DOCS.documents().batchUpdate( + body={"requests": reqs}, documentId=copy_id, fields="" + ).execute() + return copy_id + except HttpError as error: + print(f"An error occurred: {error}") + return error + + +if __name__ == "__main__": + # fill-in your data to merge into document template variables + merge = { + # sender data + "my_name": "Ayme A. Coder", + "my_address": "1600 Amphitheatre Pkwy\nMountain View, CA 94043-1351", + "my_email": "http://google.com", + "my_phone": "+1-650-253-0000", + # - - - - - - - - - - - - - - - - - - - - - - - - - - + # recipient data (supplied by 'text' or 'sheets' data source) + "to_name": None, + "to_title": None, + "to_company": None, + "to_address": None, + # - - - - - - - - - - - - - - - - - - - - - - - - - - + "date": time.strftime("%Y %B %d"), + # - - - - - - - - - - - - - - - - - - - - - - - - - - + "body": ( + "Google, headquartered in Mountain View, unveiled the new " + "Android phone at the Consumer Electronics Show. CEO Sundar " + "Pichai said in his keynote that users love their new phones." + ), + } + + # get row data, then loop through & process each form letter + data = get_data(SOURCE) # get data from data source + for i, row in enumerate(data): + merge.update(dict(zip(COLUMNS, row))) + print( + "Merged letter %d: docs.google.com/document/d/%s/edit" + % (i + 1, merge_template(DOCS_FILE_ID, SOURCE, DRIVE)) + ) # [END mail_merge_python] diff --git a/docs/mail-merge/docs_mail_merge_test.py b/docs/mail-merge/docs_mail_merge_test.py index 1ff4609a..276d8f14 100644 --- a/docs/mail-merge/docs_mail_merge_test.py +++ b/docs/mail-merge/docs_mail_merge_test.py @@ -32,59 +32,59 @@ class TestDocsMailMerge(unittest.TestCase): - 'Unit tests for Mail Merge sample' + "Unit tests for Mail Merge sample" - def test_project(self): - self.assertTrue(project_test()) + def test_project(self): + self.assertTrue(project_test()) - def test_create_doc(self): - self.assertTrue(create_doc_test()) + def test_create_doc(self): + self.assertTrue(create_doc_test()) - def test_copy_doc(self): - self.assertTrue(copy_doc_test()) + def test_copy_doc(self): + self.assertTrue(copy_doc_test()) - def test_get_text_data(self): - self.assertTrue(bool(get_text_data_test())) + def test_get_text_data(self): + self.assertTrue(bool(get_text_data_test())) - def test_get_sheets_data(self): - self.assertTrue(bool(get_sheets_data_test())) + def test_get_sheets_data(self): + self.assertTrue(bool(get_sheets_data_test())) def project_test(): - 'Tests whether project credentials file was downloaded from project.' - credentials, project = google.auth.default() + "Tests whether project credentials file was downloaded from project." + credentials, project = google.auth.default() def create_doc_test(): - 'Tests whether project can create and delete a Google Docs file.' - DRIVE = discovery.build('drive', 'v3', credentials=creds) - DATA = { - 'name': 'Test Doc', - 'mimeType': 'application/vnd.google-apps.document', - } - doc_id = DRIVE.files().create(body=DATA, fields='id').execute().get('id') - DRIVE.files().delete(fileId=doc_id, fields='').execute() - return True + "Tests whether project can create and delete a Google Docs file." + DRIVE = discovery.build("drive", "v3", credentials=creds) + DATA = { + "name": "Test Doc", + "mimeType": "application/vnd.google-apps.document", + } + doc_id = DRIVE.files().create(body=DATA, fields="id").execute().get("id") + DRIVE.files().delete(fileId=doc_id, fields="").execute() + return True def copy_doc_test(): - 'Tests whether project can copy and delete a Google Docs file.' - DRIVE = discovery.build('drive', 'v3', credentials=creds) - DOCS_FILE_ID = '1Xycxuuv7OhEQUuzbt_Mw0TPMq02MseSD1vZdBJ3nLjk' - doc_id = _copy_template(DOCS_FILE_ID, 'text', DRIVE) - DRIVE.files().delete(fileId=doc_id, fields='').execute() - return True + "Tests whether project can copy and delete a Google Docs file." + DRIVE = discovery.build("drive", "v3", credentials=creds) + DOCS_FILE_ID = "1Xycxuuv7OhEQUuzbt_Mw0TPMq02MseSD1vZdBJ3nLjk" + doc_id = _copy_template(DOCS_FILE_ID, "text", DRIVE) + DRIVE.files().delete(fileId=doc_id, fields="").execute() + return True def get_text_data_test(): - 'Tests reading plain text data.' - return get_data('text') + "Tests reading plain text data." + return get_data("text") def get_sheets_data_test(): - 'Tests reading Google Sheets data.' - return get_data('sheets') + "Tests reading Google Sheets data." + return get_data("sheets") -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/docs/output-json/output-json.py b/docs/output-json/output-json.py index 71b88e93..5454a96e 100644 --- a/docs/output-json/output-json.py +++ b/docs/output-json/output-json.py @@ -17,8 +17,6 @@ Google Docs (REST) API output-json sample app """ # [START output_json_python] -from __future__ import print_function - import json from apiclient import discovery @@ -26,21 +24,24 @@ from oauth2client import client, file, tools # Set doc ID, as found at `https://docs.google.com/document/d/YOUR_DOC_ID/edit` -DOCUMENT_ID = 'YOUR_DOC_ID' +DOCUMENT_ID = "YOUR_DOC_ID" # Set the scopes and discovery info -SCOPES = 'https://www.googleapis.com/auth/documents.readonly' -DISCOVERY_DOC = ('https://docs.googleapis.com/$discovery/rest?' - 'version=v1') +SCOPES = "https://www.googleapis.com/auth/documents.readonly" +DISCOVERY_DOC = "https://docs.googleapis.com/$discovery/rest?version=v1" # Initialize credentials and instantiate Docs API service -store = file.Storage('token.json') +store = file.Storage("token.json") creds = store.get() if not creds or creds.invalid: - flow = client.flow_from_clientsecrets('credentials.json', SCOPES) - creds = tools.run_flow(flow, store) -service = discovery.build('docs', 'v1', http=creds.authorize( - Http()), discoveryServiceUrl=DISCOVERY_DOC) + flow = client.flow_from_clientsecrets("credentials.json", SCOPES) + creds = tools.run_flow(flow, store) +service = discovery.build( + "docs", + "v1", + http=creds.authorize(Http()), + discoveryServiceUrl=DISCOVERY_DOC, +) # Do a document "get" request and print the results as formatted JSON result = service.documents().get(documentId=DOCUMENT_ID).execute() diff --git a/docs/output-json/output_json.py b/docs/output-json/output_json.py index 25d0a77d..caebb10e 100644 --- a/docs/output-json/output_json.py +++ b/docs/output-json/output_json.py @@ -17,8 +17,6 @@ Google Docs (REST) API output-json sample app """ # [START output_json_python] -from __future__ import print_function - import json import google.auth @@ -29,21 +27,20 @@ DOCUMENT_ID = "195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE" # Set the scopes and discovery info -SCOPES = 'https://www.googleapis.com/auth/documents.readonly' -DISCOVERY_DOC = ('https://docs.googleapis.com/$discovery/rest?' - 'version=v1') +SCOPES = "https://www.googleapis.com/auth/documents.readonly" +DISCOVERY_DOC = "https://docs.googleapis.com/$discovery/rest?version=v1" # Initialize credentials and instantiate Docs API service creds, _ = google.auth.default() # pylint: disable=maybe-no-member try: - service = build('docs', 'v1', credentials=creds) + service = build("docs", "v1", credentials=creds) - # Do a document "get" request and print the results as formatted JSON + # Do a document "get" request and print the results as formatted JSON - result = service.documents().get(documentId=DOCUMENT_ID).execute() - print(json.dumps(result, indent=4, sort_keys=True)) + result = service.documents().get(documentId=DOCUMENT_ID).execute() + print(json.dumps(result, indent=4, sort_keys=True)) except HttpError as error: - print(f"An error occurred: {error}") + print(f"An error occurred: {error}") # [END output_json_python] diff --git a/docs/quickstart/quickstart.py b/docs/quickstart/quickstart.py index 3e4b3e45..60324159 100644 --- a/docs/quickstart/quickstart.py +++ b/docs/quickstart/quickstart.py @@ -13,8 +13,6 @@ # limitations under the License. # [START docs_quickstart] -from __future__ import print_function - import os.path from google.auth.transport.requests import Request @@ -24,45 +22,46 @@ from googleapiclient.errors import HttpError # If modifying these scopes, delete the file token.json. -SCOPES = ['https://www.googleapis.com/auth/documents.readonly'] +SCOPES = ["https://www.googleapis.com/auth/documents.readonly"] # The ID of a sample document. -DOCUMENT_ID = '195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE' +DOCUMENT_ID = "195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE" def main(): - """Shows basic usage of the Docs API. - Prints the title of a sample document. - """ - creds = None - # The file token.json stores the user's access and refresh tokens, and is - # created automatically when the authorization flow completes for the first - # time. - if os.path.exists('token.json'): - creds = Credentials.from_authorized_user_file('token.json', SCOPES) - # If there are no (valid) credentials available, let the user log in. - if not creds or not creds.valid: - if creds and creds.expired and creds.refresh_token: - creds.refresh(Request()) - else: - flow = InstalledAppFlow.from_client_secrets_file( - 'credentials.json', SCOPES) - creds = flow.run_local_server(port=0) - # Save the credentials for the next run - with open('token.json', 'w') as token: - token.write(creds.to_json()) + """Shows basic usage of the Docs API. + Prints the title of a sample document. + """ + creds = None + # The file token.json stores the user's access and refresh tokens, and is + # created automatically when the authorization flow completes for the first + # time. + if os.path.exists("token.json"): + creds = Credentials.from_authorized_user_file("token.json", SCOPES) + # If there are no (valid) credentials available, let the user log in. + if not creds or not creds.valid: + if creds and creds.expired and creds.refresh_token: + creds.refresh(Request()) + else: + flow = InstalledAppFlow.from_client_secrets_file( + "credentials.json", SCOPES + ) + creds = flow.run_local_server(port=0) + # Save the credentials for the next run + with open("token.json", "w") as token: + token.write(creds.to_json()) - try: - service = build('docs', 'v1', credentials=creds) + try: + service = build("docs", "v1", credentials=creds) - # Retrieve the documents contents from the Docs service. - document = service.documents().get(documentId=DOCUMENT_ID).execute() + # Retrieve the documents contents from the Docs service. + document = service.documents().get(documentId=DOCUMENT_ID).execute() - print('The title of the document is: {}'.format(document.get('title'))) - except HttpError as err: - print(err) + print(f"The title of the document is: {document.get('title')}") + except HttpError as err: + print(err) -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() # [END docs_quickstart] diff --git a/drive/activity-v2/quickstart.py b/drive/activity-v2/quickstart.py index 8e5ef54a..6e1b7769 100644 --- a/drive/activity-v2/quickstart.py +++ b/drive/activity-v2/quickstart.py @@ -13,8 +13,6 @@ # limitations under the License. # [START drive_activity_v2_quickstart] -from __future__ import print_function - import os.path from google.auth.transport.requests import Request @@ -24,114 +22,113 @@ from googleapiclient.errors import HttpError # If modifying these scopes, delete the file token.json. -SCOPES = ['https://www.googleapis.com/auth/drive.activity.readonly'] +SCOPES = ["https://www.googleapis.com/auth/drive.activity.readonly"] def main(): - """Shows basic usage of the Drive Activity API. - - Prints information about the last 10 events that occured the user's Drive. - """ - creds = None - # The file token.json stores the user's access and refresh tokens, and is - # created automatically when the authorization flow completes for the first - # time. - if os.path.exists('token.json'): - creds = Credentials.from_authorized_user_file('token.json', SCOPES) - # If there are no (valid) credentials available, let the user log in. - if not creds or not creds.valid: - if creds and creds.expired and creds.refresh_token: - creds.refresh(Request()) - else: - flow = InstalledAppFlow.from_client_secrets_file( - 'credentials.json', SCOPES) - creds = flow.run_local_server(port=0) - # Save the credentials for the next run - with open('token.json', 'w') as token: - token.write(creds.to_json()) - - service = build('driveactivity', 'v2', credentials=creds) - - # Call the Drive Activity API - try: - results = service.activity().query(body={ - 'pageSize': 10 - }).execute() - activities = results.get('activities', []) - - if not activities: - print('No activity.') - else: - print('Recent activity:') - for activity in activities: - time = getTimeInfo(activity) - action = getActionInfo(activity['primaryActionDetail']) - actors = map(getActorInfo, activity['actors']) - targets = map(getTargetInfo, activity['targets']) - actors_str, targets_str = "", "" - actor_name = actors_str.join(actors) - target_name = targets_str.join(targets) - - # Print the action occurred on drive with actor, target item and timestamp - print(u'{0}: {1}, {2}, {3}'.format(time, action, actor_name, target_name)) - - except HttpError as error: - # TODO(developer) - Handleerrors from drive activity API. - print(f'An error occurred: {error}') + """Shows basic usage of the Drive Activity API. + + Prints information about the last 10 events that occured the user's Drive. + """ + creds = None + # The file token.json stores the user's access and refresh tokens, and is + # created automatically when the authorization flow completes for the first + # time. + if os.path.exists("token.json"): + creds = Credentials.from_authorized_user_file("token.json", SCOPES) + # If there are no (valid) credentials available, let the user log in. + if not creds or not creds.valid: + if creds and creds.expired and creds.refresh_token: + creds.refresh(Request()) + else: + flow = InstalledAppFlow.from_client_secrets_file( + "credentials.json", SCOPES + ) + creds = flow.run_local_server(port=0) + # Save the credentials for the next run + with open("token.json", "w") as token: + token.write(creds.to_json()) + + service = build("driveactivity", "v2", credentials=creds) + + # Call the Drive Activity API + try: + results = service.activity().query(body={"pageSize": 10}).execute() + activities = results.get("activities", []) + + if not activities: + print("No activity.") + else: + print("Recent activity:") + for activity in activities: + time = getTimeInfo(activity) + action = getActionInfo(activity["primaryActionDetail"]) + actors = map(getActorInfo, activity["actors"]) + targets = map(getTargetInfo, activity["targets"]) + actors_str, targets_str = "", "" + actor_name = actors_str.join(actors) + target_name = targets_str.join(targets) + + # Print the action occurred on drive with actor, target item and timestamp + print(f"{time}: {action}, {actor_name}, {target_name}") + + except HttpError as error: + # TODO(developer) - Handleerrors from drive activity API. + print(f"An error occurred: {error}") # Returns the name of a set property in an object, or else "unknown". def getOneOf(obj): - for key in obj: - return key - return 'unknown' + for key in obj: + return key + return "unknown" # Returns a time associated with an activity. def getTimeInfo(activity): - if 'timestamp' in activity: - return activity['timestamp'] - if 'timeRange' in activity: - return activity['timeRange']['endTime'] - return 'unknown' + if "timestamp" in activity: + return activity["timestamp"] + if "timeRange" in activity: + return activity["timeRange"]["endTime"] + return "unknown" # Returns the type of action. def getActionInfo(actionDetail): - return getOneOf(actionDetail) + return getOneOf(actionDetail) # Returns user information, or the type of user if not a known user. def getUserInfo(user): - if 'knownUser' in user: - knownUser = user['knownUser'] - isMe = knownUser.get('isCurrentUser', False) - return u'people/me' if isMe else knownUser['personName'] - return getOneOf(user) + if "knownUser" in user: + knownUser = user["knownUser"] + isMe = knownUser.get("isCurrentUser", False) + return "people/me" if isMe else knownUser["personName"] + return getOneOf(user) # Returns actor information, or the type of actor if not a user. def getActorInfo(actor): - if 'user' in actor: - return getUserInfo(actor['user']) - return getOneOf(actor) + if "user" in actor: + return getUserInfo(actor["user"]) + return getOneOf(actor) # Returns the type of a target and an associated title. def getTargetInfo(target): - if 'driveItem' in target: - title = target['driveItem'].get('title', 'unknown') - return 'driveItem:"{0}"'.format(title) - if 'drive' in target: - title = target['drive'].get('title', 'unknown') - return 'drive:"{0}"'.format(title) - if 'fileComment' in target: - parent = target['fileComment'].get('parent', {}) - title = parent.get('title', 'unknown') - return 'fileComment:"{0}"'.format(title) - return '{0}:unknown'.format(getOneOf(target)) - - -if __name__ == '__main__': - main() + if "driveItem" in target: + title = target["driveItem"].get("title", "unknown") + return f'driveItem:"{title}"' + if "drive" in target: + title = target["drive"].get("title", "unknown") + return f'drive:"{title}"' + if "fileComment" in target: + parent = target["fileComment"].get("parent", {}) + title = parent.get("title", "unknown") + return f'fileComment:"{title}"' + return f"{getOneOf(target)}:unknown" + + +if __name__ == "__main__": + main() # [END drive_activity_v2_quickstart] diff --git a/drive/driveapp/main.py b/drive/driveapp/main.py index bdddeeb5..fa5b1437 100644 --- a/drive/driveapp/main.py +++ b/drive/driveapp/main.py @@ -19,8 +19,6 @@ This script uploads a single file to Google Drive. """ -from __future__ import print_function - import googleapiclient.http import httplib2 import oauth2client.client @@ -30,57 +28,57 @@ # OAuth 2.0 scope that will be authorized. # Check https://developers.google.com/drive/scopes for all available scopes. -OAUTH2_SCOPE = 'https://www.googleapis.com/auth/drive' +OAUTH2_SCOPE = "https://www.googleapis.com/auth/drive" # Location of the client secrets. -CLIENT_SECRETS = 'client_secrets.json' +CLIENT_SECRETS = "client_secrets.json" # Path to the file to upload. -FILENAME = 'document.txt' +FILENAME = "document.txt" # Metadata about the file. -MIMETYPE = 'text/plain' -TITLE = 'My New Text Document' -DESCRIPTION = 'A shiny new text document about hello world.' +MIMETYPE = "text/plain" +TITLE = "My New Text Document" +DESCRIPTION = "A shiny new text document about hello world." # Perform OAuth2.0 authorization flow. -flow = oauth2client.client.flow_from_clientsecrets( - CLIENT_SECRETS, OAUTH2_SCOPE) +flow = oauth2client.client.flow_from_clientsecrets(CLIENT_SECRETS, OAUTH2_SCOPE) flow.redirect_uri = oauth2client.client.OOB_CALLBACK_URN authorize_url = flow.step1_get_authorize_url() -print('Go to the following link in your browser: ' + authorize_url) +print("Go to the following link in your browser: " + authorize_url) # `six` library supports Python2 and Python3 without redefining builtin input() -code = six.moves.input('Enter verification code: ').strip() +code = six.moves.input("Enter verification code: ").strip() credentials = flow.step2_exchange(code) # Create an authorized Drive API client. http = httplib2.Http() credentials.authorize(http) -drive_service = build('drive', 'v2', http=http) +drive_service = build("drive", "v2", http=http) # Insert a file. Files are comprised of contents and metadata. # MediaFileUpload abstracts uploading file contents from a file on disk. media_body = googleapiclient.http.MediaFileUpload( - FILENAME, - mimetype=MIMETYPE, - resumable=True + FILENAME, mimetype=MIMETYPE, resumable=True ) # The body contains the metadata for the file. body = { - 'title': TITLE, - 'description': DESCRIPTION, + "title": TITLE, + "description": DESCRIPTION, } # Perform the request and print the result. try: - new_file = drive_service.files().insert( - body=body, media_body=media_body).execute() - file_title = new_file.get('title') - file_desc = new_file.get('description') - if file_title == TITLE and file_desc == DESCRIPTION: - print(f"File is uploaded \nTitle : {file_title} \nDescription : {file_desc}") + new_file = ( + drive_service.files().insert(body=body, media_body=media_body).execute() + ) + file_title = new_file.get("title") + file_desc = new_file.get("description") + if file_title == TITLE and file_desc == DESCRIPTION: + print( + f"File is uploaded \nTitle : {file_title} \nDescription : {file_desc}" + ) except HttpError as error: - # TODO(developer) - Handle errors from drive API. - print(f'An error occurred: {error}') + # TODO(developer) - Handle errors from drive API. + print(f"An error occurred: {error}") diff --git a/drive/quickstart/quickstart.py b/drive/quickstart/quickstart.py index f8d0cb6c..117ba4f8 100644 --- a/drive/quickstart/quickstart.py +++ b/drive/quickstart/quickstart.py @@ -13,8 +13,6 @@ # limitations under the License. # [START drive_quickstart] -from __future__ import print_function - import os.path from google.auth.transport.requests import Request @@ -24,50 +22,54 @@ from googleapiclient.errors import HttpError # If modifying these scopes, delete the file token.json. -SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly'] +SCOPES = ["https://www.googleapis.com/auth/drive.metadata.readonly"] def main(): - """Shows basic usage of the Drive v3 API. - Prints the names and ids of the first 10 files the user has access to. - """ - creds = None - # The file token.json stores the user's access and refresh tokens, and is - # created automatically when the authorization flow completes for the first - # time. - if os.path.exists('token.json'): - creds = Credentials.from_authorized_user_file('token.json', SCOPES) - # If there are no (valid) credentials available, let the user log in. - if not creds or not creds.valid: - if creds and creds.expired and creds.refresh_token: - creds.refresh(Request()) - else: - flow = InstalledAppFlow.from_client_secrets_file( - 'credentials.json', SCOPES) - creds = flow.run_local_server(port=0) - # Save the credentials for the next run - with open('token.json', 'w') as token: - token.write(creds.to_json()) + """Shows basic usage of the Drive v3 API. + Prints the names and ids of the first 10 files the user has access to. + """ + creds = None + # The file token.json stores the user's access and refresh tokens, and is + # created automatically when the authorization flow completes for the first + # time. + if os.path.exists("token.json"): + creds = Credentials.from_authorized_user_file("token.json", SCOPES) + # If there are no (valid) credentials available, let the user log in. + if not creds or not creds.valid: + if creds and creds.expired and creds.refresh_token: + creds.refresh(Request()) + else: + flow = InstalledAppFlow.from_client_secrets_file( + "credentials.json", SCOPES + ) + creds = flow.run_local_server(port=0) + # Save the credentials for the next run + with open("token.json", "w") as token: + token.write(creds.to_json()) - try: - service = build('drive', 'v3', credentials=creds) + try: + service = build("drive", "v3", credentials=creds) - # Call the Drive v3 API - results = service.files().list( - pageSize=10, fields="nextPageToken, files(id, name)").execute() - items = results.get('files', []) + # Call the Drive v3 API + results = ( + service.files() + .list(pageSize=10, fields="nextPageToken, files(id, name)") + .execute() + ) + items = results.get("files", []) - if not items: - print('No files found.') - return - print('Files:') - for item in items: - print(u'{0} ({1})'.format(item['name'], item['id'])) - except HttpError as error: - # TODO(developer) - Handle errors from drive API. - print(f'An error occurred: {error}') + if not items: + print("No files found.") + return + print("Files:") + for item in items: + print(f"{item['name']} ({item['id']})") + except HttpError as error: + # TODO(developer) - Handle errors from drive API. + print(f"An error occurred: {error}") -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() # [END drive_quickstart] diff --git a/drive/snippets/drive-v2/app data snippet/fetch_appdata_folder.py b/drive/snippets/drive-v2/app data snippet/fetch_appdata_folder.py index a3450ff5..94008a33 100644 --- a/drive/snippets/drive-v2/app data snippet/fetch_appdata_folder.py +++ b/drive/snippets/drive-v2/app data snippet/fetch_appdata_folder.py @@ -14,40 +14,36 @@ """ # [START drive_fetch_appdata_folder] - -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def fetch_appdata_folder(): - """List out application data folder and prints folder ID. - Returns : Folder ID + """List out application data folder and prints folder ID. + Returns : Folder ID - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() - try: - # call drive api client - service = build('drive', 'v2', credentials=creds) + try: + # call drive api client + service = build("drive", "v2", credentials=creds) - # pylint: disable=maybe-no-member - file = service.files().get(fileId='appDataFolder', fields='id')\ - .execute() - print(F'Folder ID: {file.get("id")}') + # pylint: disable=maybe-no-member + file = service.files().get(fileId="appDataFolder", fields="id").execute() + print(f'Folder ID: {file.get("id")}') - except HttpError as error: - print(F'An error occurred: {error}') - file = None + except HttpError as error: + print(f"An error occurred: {error}") + file = None - return file.get('id') + return file.get("id") -if __name__ == '__main__': - fetch_appdata_folder() +if __name__ == "__main__": + fetch_appdata_folder() # [END drive_fetch_appdata_folder] diff --git a/drive/snippets/drive-v2/app data snippet/list_appdata.py b/drive/snippets/drive-v2/app data snippet/list_appdata.py index 25b11f0a..3930d30b 100644 --- a/drive/snippets/drive-v2/app data snippet/list_appdata.py +++ b/drive/snippets/drive-v2/app data snippet/list_appdata.py @@ -14,44 +14,47 @@ """ # [START drive_list_appdata] - -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def list_appdata(): - """List all files inserted in the application data folder - prints file titles with Ids. - Returns : List of items - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # call drive api client - service = build('drive', 'v2', credentials=creds) - - # pylint: disable=maybe-no-member - response = service.files().list(spaces='appDataFolder', - fields='nextPageToken, items(id, title' - ')', maxResults=10).execute() - for file in response.get('items', []): - # Process change - print(F'Found file: {file.get("title")} ,{file.get("id")}') - - except HttpError as error: - print(F'An error occurred: {error}') - response = None - - return response.get('items') - - -if __name__ == '__main__': - list_appdata() + """List all files inserted in the application data folder + prints file titles with Ids. + Returns : List of items + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # call drive api client + service = build("drive", "v2", credentials=creds) + + # pylint: disable=maybe-no-member + response = ( + service.files() + .list( + spaces="appDataFolder", + fields="nextPageToken, items(id, title)", + maxResults=10, + ) + .execute() + ) + for file in response.get("items", []): + # Process change + print(f'Found file: {file.get("title")} ,{file.get("id")}') + + except HttpError as error: + print(f"An error occurred: {error}") + response = None + + return response.get("items") + + +if __name__ == "__main__": + list_appdata() # [END drive_list_appdata] diff --git a/drive/snippets/drive-v2/app data snippet/test_fetch_appdata_folder.py b/drive/snippets/drive-v2/app data snippet/test_fetch_appdata_folder.py index c48b3472..5eddf5f8 100644 --- a/drive/snippets/drive-v2/app data snippet/test_fetch_appdata_folder.py +++ b/drive/snippets/drive-v2/app data snippet/test_fetch_appdata_folder.py @@ -12,20 +12,21 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest import fetch_appdata_folder class TestFetchAppdataFolder(unittest.TestCase): - """Unit test class for Appdata snippet""" + """Unit test class for Appdata snippet""" - @classmethod - def test_list_appdata(cls): - """Test list_appdata""" - file_id = fetch_appdata_folder.fetch_appdata_folder() - cls.assertIsNotNone(cls, file_id) + @classmethod + def test_list_appdata(cls): + """Test list_appdata""" + file_id = fetch_appdata_folder.fetch_appdata_folder() + cls.assertIsNotNone(cls, file_id) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v2/app data snippet/test_list_appdata.py b/drive/snippets/drive-v2/app data snippet/test_list_appdata.py index dd66a706..f4a959a2 100644 --- a/drive/snippets/drive-v2/app data snippet/test_list_appdata.py +++ b/drive/snippets/drive-v2/app data snippet/test_list_appdata.py @@ -12,20 +12,21 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest import list_appdata class TestListAppdata(unittest.TestCase): - """Unit test class for Appdata snippet""" + """Unit test class for Appdata snippet""" - @classmethod - def test_list_appdata(cls): - """Test list_appdata""" - files = list_appdata.list_appdata() - cls.assertNotEqual(cls, 0, len(files)) + @classmethod + def test_list_appdata(cls): + """Test list_appdata""" + files = list_appdata.list_appdata() + cls.assertNotEqual(cls, 0, len(files)) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v2/app data snippet/test_upload_appdata.py b/drive/snippets/drive-v2/app data snippet/test_upload_appdata.py index 95b5025b..e4835c35 100644 --- a/drive/snippets/drive-v2/app data snippet/test_upload_appdata.py +++ b/drive/snippets/drive-v2/app data snippet/test_upload_appdata.py @@ -12,24 +12,25 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest import upload_app_data class TestUploadAppdata(unittest.TestCase): + """ + Unit test class for Appdata snippet + """ + + @classmethod + def test_upload_adddata(cls): + """Test upload_appdata + create a text file titled "abc.txt" in order to pass this test """ - Unit test class for Appdata snippet - """ - - @classmethod - def test_upload_adddata(cls): - """Test upload_appdata - create a text file titled "abc.txt" in order to pass this test - """ - file_id = upload_app_data.upload_appdata() - cls.assertIsNotNone(cls, file_id) + file_id = upload_app_data.upload_appdata() + cls.assertIsNotNone(cls, file_id) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v2/app data snippet/upload_app_data.py b/drive/snippets/drive-v2/app data snippet/upload_app_data.py index c8cef2e2..062f28cb 100644 --- a/drive/snippets/drive-v2/app data snippet/upload_app_data.py +++ b/drive/snippets/drive-v2/app data snippet/upload_app_data.py @@ -14,9 +14,6 @@ """ # [START drive_upload_appdata] - -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError @@ -24,40 +21,36 @@ def upload_appdata(): - """Insert a file in the application data folder and prints file Id. - Returns : ID's of the inserted files - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # call drive api client - service = build('drive', 'v2', credentials=creds) - - file_metadata = { - 'title': 'abc.txt', - 'parents': [{ - 'id': 'appDataFolder' - }] - } - media = MediaFileUpload('abc.txt', - mimetype='text/txt', - resumable=True) - # pylint: disable=maybe-no-member - file = service.files().insert(body=file_metadata, media_body=media, - fields='id').execute() - print(F'File ID: {file.get("id")}') - - except HttpError as error: - print(F'An error occurred: {error}') - file = None - - return file.get('id') - - -if __name__ == '__main__': - upload_appdata() + """Insert a file in the application data folder and prints file Id. + Returns : ID's of the inserted files + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # call drive api client + service = build("drive", "v2", credentials=creds) + + file_metadata = {"title": "abc.txt", "parents": [{"id": "appDataFolder"}]} + media = MediaFileUpload("abc.txt", mimetype="text/txt", resumable=True) + # pylint: disable=maybe-no-member + file = ( + service.files() + .insert(body=file_metadata, media_body=media, fields="id") + .execute() + ) + print(f'File ID: {file.get("id")}') + + except HttpError as error: + print(f"An error occurred: {error}") + file = None + + return file.get("id") + + +if __name__ == "__main__": + upload_appdata() # [END drive_upload_appdata] diff --git a/drive/snippets/drive-v2/change snippet/fetch_changes.py b/drive/snippets/drive-v2/change snippet/fetch_changes.py index d7f046b7..904132fc 100644 --- a/drive/snippets/drive-v2/change snippet/fetch_changes.py +++ b/drive/snippets/drive-v2/change snippet/fetch_changes.py @@ -10,54 +10,53 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START drive_fetch_changes] - -from __future__ import print_function +# [START drive_fetch_changes] import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def fetch_changes(saved_start_page_token): - """Retrieve the list of changes for the currently authenticated user. - prints changed file's ID - Args: - saved_start_page_token : StartPageToken for the current state of the - account. - Returns: saved start page token. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - try: - # create drive api client - service = build('drive', 'v2', credentials=creds) - - # Begin with our last saved start token for this user or the - # current token from getStartPageToken() - page_token = saved_start_page_token - while page_token is not None: - # pylint: disable=maybe-no-member - response = service.changes().list(pageToken=page_token, - spaces='drive').execute() - for change in response.get('items'): - # Process change - print(F'Change found for file: {change.get("fileId")}') - if 'newStartPageToken' in response: - # Last page, save this token for the next polling interval - saved_start_page_token = response.get('newStartPageToken') - page_token = response.get('nextPageToken') - - except HttpError as error: - print(F'An error occurred: {error}') - saved_start_page_token = None - - return saved_start_page_token - - -if __name__ == '__main__': - # saved_start_page_token is the token number - fetch_changes(saved_start_page_token=15) + """Retrieve the list of changes for the currently authenticated user. + prints changed file's ID + Args: + saved_start_page_token : StartPageToken for the current state of the + account. + Returns: saved start page token. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + try: + # create drive api client + service = build("drive", "v2", credentials=creds) + + # Begin with our last saved start token for this user or the + # current token from getStartPageToken() + page_token = saved_start_page_token + while page_token is not None: + # pylint: disable=maybe-no-member + response = ( + service.changes().list(pageToken=page_token, spaces="drive").execute() + ) + for change in response.get("items"): + # Process change + print(f'Change found for file: {change.get("fileId")}') + if "newStartPageToken" in response: + # Last page, save this token for the next polling interval + saved_start_page_token = response.get("newStartPageToken") + page_token = response.get("nextPageToken") + + except HttpError as error: + print(f"An error occurred: {error}") + saved_start_page_token = None + + return saved_start_page_token + + +if __name__ == "__main__": + # saved_start_page_token is the token number + fetch_changes(saved_start_page_token=15) # [END drive_fetch_changes] diff --git a/drive/snippets/drive-v2/change snippet/fetch_start_page_token.py b/drive/snippets/drive-v2/change snippet/fetch_start_page_token.py index 763344a3..9d8f16cb 100644 --- a/drive/snippets/drive-v2/change snippet/fetch_start_page_token.py +++ b/drive/snippets/drive-v2/change snippet/fetch_start_page_token.py @@ -10,39 +10,37 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START drive_fetch_start_page_token] - -from __future__ import print_function +# [START drive_fetch_start_page_token] import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def fetch_start_page_token(): - """Retrieve page token for the current state of the account. - Returns & prints : start page token - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() + """Retrieve page token for the current state of the account. + Returns & prints : start page token + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() - try: - # create drive api client - service = build('drive', 'v2', credentials=creds) + try: + # create drive api client + service = build("drive", "v2", credentials=creds) - # pylint: disable=maybe-no-member - response = service.changes().getStartPageToken().execute() - print(F'Start token: {response.get("startPageToken")}') + # pylint: disable=maybe-no-member + response = service.changes().getStartPageToken().execute() + print(f'Start token: {response.get("startPageToken")}') - except HttpError as error: - print(F'An error occurred: {error}') - response = None + except HttpError as error: + print(f"An error occurred: {error}") + response = None - return response.get('startPageToken') + return response.get("startPageToken") -if __name__ == '__main__': - fetch_start_page_token() +if __name__ == "__main__": + fetch_start_page_token() # [END drive_fetch_start_page_token] diff --git a/drive/snippets/drive-v2/change snippet/test_fetch_changes.py b/drive/snippets/drive-v2/change snippet/test_fetch_changes.py index a172f69e..adb16f2d 100644 --- a/drive/snippets/drive-v2/change snippet/test_fetch_changes.py +++ b/drive/snippets/drive-v2/change snippet/test_fetch_changes.py @@ -20,15 +20,15 @@ class TestFetchChanges(unittest.TestCase): - """Unit test classs for Change snippet""" + """Unit test class for Change snippet""" - @classmethod - def test_fetch_changes(cls): - """Test fetch_changes""" - start_token = fetch_start_page_token.fetch_start_page_token() - token = fetch_changes.fetch_changes(start_token) - cls.assertIsNotNone(cls, token) + @classmethod + def test_fetch_changes(cls): + """Test fetch_changes""" + start_token = fetch_start_page_token.fetch_start_page_token() + token = fetch_changes.fetch_changes(start_token) + cls.assertIsNotNone(cls, token) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v2/change snippet/test_fetch_start_page_token.py b/drive/snippets/drive-v2/change snippet/test_fetch_start_page_token.py index 9405cfa6..69b2cd15 100644 --- a/drive/snippets/drive-v2/change snippet/test_fetch_start_page_token.py +++ b/drive/snippets/drive-v2/change snippet/test_fetch_start_page_token.py @@ -12,20 +12,21 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest import fetch_start_page_token class TestFetchChanges(unittest.TestCase): - """Unit test classs for Change snippet""" + """Unit test class for Change snippet""" - @classmethod - def test_fetch_start_page_token(cls): - """Test fetch_start_page_token""" - token = fetch_start_page_token.fetch_start_page_token() - cls.assertIsNotNone(cls, token) + @classmethod + def test_fetch_start_page_token(cls): + """Test fetch_start_page_token""" + token = fetch_start_page_token.fetch_start_page_token() + cls.assertIsNotNone(cls, token) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v2/drive_snippet/create_drive.py b/drive/snippets/drive-v2/drive_snippet/create_drive.py index 600efef2..a5ef4de8 100644 --- a/drive/snippets/drive-v2/drive_snippet/create_drive.py +++ b/drive/snippets/drive-v2/drive_snippet/create_drive.py @@ -13,10 +13,8 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START drive_create_drive] - -from __future__ import print_function +# [START drive_create_drive] import uuid import google.auth @@ -25,35 +23,37 @@ def create_drive(): - """Create a drive. - Returns: - Id of the created drive - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # create drive api client - service = build('drive', 'v2', credentials=creds) - - drive_metadata = {'name': 'Project Resources'} - request_id = str(uuid.uuid4()) - # pylint: disable=maybe-no-member - drive = service.drives().insert(body=drive_metadata, - requestId=request_id, fields='id') \ - .execute() - print(F'Drive ID: {drive.get("id")}') - - except HttpError as error: - print(F'An error occurred: {error}') - drive = None - - return drive.get('id') - - -if __name__ == '__main__': - create_drive() + """Create a drive. + Returns: + Id of the created drive + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # create drive api client + service = build("drive", "v2", credentials=creds) + + drive_metadata = {"name": "Project Resources"} + request_id = str(uuid.uuid4()) + # pylint: disable=maybe-no-member + drive = ( + service.drives() + .insert(body=drive_metadata, requestId=request_id, fields="id") + .execute() + ) + print(f'Drive ID: {drive.get("id")}') + + except HttpError as error: + print(f"An error occurred: {error}") + drive = None + + return drive.get("id") + + +if __name__ == "__main__": + create_drive() # [END drive_create_drive] diff --git a/drive/snippets/drive-v2/drive_snippet/recover_drives.py b/drive/snippets/drive-v2/drive_snippet/recover_drives.py index d8159e6f..4584df3d 100644 --- a/drive/snippets/drive-v2/drive_snippet/recover_drives.py +++ b/drive/snippets/drive-v2/drive_snippet/recover_drives.py @@ -13,71 +13,81 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START drive_recover_drives] - -from __future__ import print_function +# [START drive_recover_drives] import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def recover_drives(real_user): - """Find all shared drives without an organizer and add one. - Args: - real_user:User ID for the new organizer. - Returns: - drives object - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - try: - # create drive api client - service = build('drive', 'v2', credentials=creds) - - drives = [] - - page_token = None - new_organizer_permission = { - 'type': 'user', - 'role': 'organizer', - 'value': 'user@example.com' - } - - new_organizer_permission['value'] = real_user - # pylint: disable=maybe-no-member - - while True: - response = service.drives().list( - q='organizerCount = 0', + """Find all shared drives without an organizer and add one. + Args: + real_user:User ID for the new organizer. + Returns: + drives object + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + try: + # create drive api client + service = build("drive", "v2", credentials=creds) + + drives = [] + + page_token = None + new_organizer_permission = { + "type": "user", + "role": "organizer", + "value": "user@example.com", + } + + new_organizer_permission["value"] = real_user + # pylint: disable=maybe-no-member + + while True: + response = ( + service.drives() + .list( + q="organizerCount = 0", + useDomainAdminAccess=True, + fields="nextPageToken, items(id, name)", + pageToken=page_token, + ) + .execute() + ) + for drive in response.get("items", []): + print( + "Found shared drive without organizer: " + f"{drive.get('title')}, {drive.get('id')}" + ) + permission = ( + service.permissions() + .insert( + fileId=drive.get("id"), + body=new_organizer_permission, useDomainAdminAccess=True, - fields='nextPageToken, items(id, name)', - pageToken=page_token).execute() - for drive in response.get('items', []): - print(F'Found shared drive without organizer: ' - F'{drive.get("title")}, {drive.get("id")}') - permission = service.permissions().insert( - fileId=drive.get('id'), - body=new_organizer_permission, - useDomainAdminAccess=True, - supportsAllDrives=True, - fields='id').execute() - print(F'Added organizer permission: {permission.get("id")}') - - drives.extend(response.get('items', [])) - page_token = response.get('nextPageToken', None) - if page_token is None: - break - - except HttpError as error: - print(F'An error occurred: {error}') - - return drives - - -if __name__ == '__main__': - recover_drives(real_user='gduser1@workspacesamples.dev') + supportsAllDrives=True, + fields="id", + ) + .execute() + ) + print(f'Added organizer permission: {permission.get("id")}') + + drives.extend(response.get("items", [])) + page_token = response.get("nextPageToken", None) + if page_token is None: + break + + except HttpError as error: + print(f"An error occurred: {error}") + + return drives + + +if __name__ == "__main__": + recover_drives(real_user="gduser1@workspacesamples.dev") # [END drive_recover_drives] diff --git a/drive/snippets/drive-v2/file snippet/create_folder.py b/drive/snippets/drive-v2/file snippet/create_folder.py index 8dfb152c..a32b24bf 100644 --- a/drive/snippets/drive-v2/file snippet/create_folder.py +++ b/drive/snippets/drive-v2/file snippet/create_folder.py @@ -13,44 +13,41 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START drive_create_folder] - -from __future__ import print_function +# [START drive_create_folder] import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def create_folder(): - """ Create a folder and prints the folder ID - Returns : Folder Id - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # create drive api client - service = build('drive', 'v2', credentials=creds) - file_metadata = { - 'title': 'Invoices', - 'mimeType': 'application/vnd.google-apps.folder' - } - - # pylint: disable=maybe-no-member - file = service.files().insert(body=file_metadata, - fields='id').execute() - print(F'Folder ID: "{file.get("id")}".') - return file.get('id') - - except HttpError as error: - print(F'An error occurred: {error}') - return None - - -if __name__ == '__main__': - create_folder() + """Create a folder and prints the folder ID + Returns : Folder Id + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # create drive api client + service = build("drive", "v2", credentials=creds) + file_metadata = { + "title": "Invoices", + "mimeType": "application/vnd.google-apps.folder", + } + + # pylint: disable=maybe-no-member + file = service.files().insert(body=file_metadata, fields="id").execute() + print(f'Folder ID: "{file.get("id")}".') + return file.get("id") + + except HttpError as error: + print(f"An error occurred: {error}") + return None + + +if __name__ == "__main__": + create_folder() # [END drive_create_folder] diff --git a/drive/snippets/drive-v2/file snippet/create_shortcut.py b/drive/snippets/drive-v2/file snippet/create_shortcut.py index 08b13b22..70665c09 100644 --- a/drive/snippets/drive-v2/file snippet/create_shortcut.py +++ b/drive/snippets/drive-v2/file snippet/create_shortcut.py @@ -13,41 +13,38 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START drive_create_shortcut] - -from __future__ import print_function +# [START drive_create_shortcut] import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def create_shortcut(): - """Create a third party shortcut - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # create drive api client - service = build('drive', 'v2', credentials=creds) - file_metadata = { - 'title': 'Project plan', - 'mimeType': 'application/vnd.google-apps.drive-sdk' - } - # pylint: disable=maybe-no-member - file = service.files().insert(body=file_metadata, - fields='id').execute() - print(F'File ID: {file.get("id")}') - - except HttpError as error: - print(F'An error occurred: {error}') - return file.get('id') - - -if __name__ == '__main__': - create_shortcut() + """Create a third party shortcut + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # create drive api client + service = build("drive", "v2", credentials=creds) + file_metadata = { + "title": "Project plan", + "mimeType": "application/vnd.google-apps.drive-sdk", + } + # pylint: disable=maybe-no-member + file = service.files().insert(body=file_metadata, fields="id").execute() + print(f'File ID: {file.get("id")}') + + except HttpError as error: + print(f"An error occurred: {error}") + return file.get("id") + + +if __name__ == "__main__": + create_shortcut() # [END drive_create_shortcut] diff --git a/drive/snippets/drive-v2/file snippet/download_file.py b/drive/snippets/drive-v2/file snippet/download_file.py index ced352bc..68fe2faa 100644 --- a/drive/snippets/drive-v2/file snippet/download_file.py +++ b/drive/snippets/drive-v2/file snippet/download_file.py @@ -13,10 +13,8 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START drive_download_file] - -from __future__ import print_function +# [START drive_download_file] import io import google.auth @@ -26,39 +24,39 @@ def download_file(real_file_id): - """Downloads a file - Args: - real_file_id: ID of the file to download - Returns : IO object with location. + """Downloads a file + Args: + real_file_id: ID of the file to download + Returns : IO object with location. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() - try: - # create drive api client - service = build('drive', 'v2', credentials=creds) + try: + # create drive api client + service = build("drive", "v2", credentials=creds) - file_id = real_file_id + file_id = real_file_id - # pylint: disable=maybe-no-member - request = service.files().get_media(fileId=file_id) - file = io.BytesIO() - downloader = MediaIoBaseDownload(file, request) - done = False - while done is False: - status, done = downloader.next_chunk() - print(F'Download {int(status.progress() * 100)}.') + # pylint: disable=maybe-no-member + request = service.files().get_media(fileId=file_id) + file = io.BytesIO() + downloader = MediaIoBaseDownload(file, request) + done = False + while done is False: + status, done = downloader.next_chunk() + print(f"Download {int(status.progress() * 100)}.") - except HttpError as error: - print(F'An error occurred: {error}') - file = None + except HttpError as error: + print(f"An error occurred: {error}") + file = None - return file.getvalue() + return file.getvalue() -if __name__ == '__main__': - download_file(real_file_id='1KuPmvGq8yoYgbfW74OENMCB5H0n_2Jm9') +if __name__ == "__main__": + download_file(real_file_id="1KuPmvGq8yoYgbfW74OENMCB5H0n_2Jm9") # [END drive_download_file] diff --git a/drive/snippets/drive-v2/file snippet/export_pdf.py b/drive/snippets/drive-v2/file snippet/export_pdf.py index 3f9b9c11..cde24bf0 100644 --- a/drive/snippets/drive-v2/file snippet/export_pdf.py +++ b/drive/snippets/drive-v2/file snippet/export_pdf.py @@ -13,10 +13,8 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START drive_export_pdf] - -from __future__ import print_function +# [START drive_export_pdf] import io import google.auth @@ -26,40 +24,41 @@ def export_pdf(real_file_id): - """Download a Document file in PDF format. - Args: - real_file_id : file ID of any workspace document format file - Returns : IO object with location - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # create drive api client - service = build('drive', 'v2', credentials=creds) - - file_id = real_file_id - - # pylint: disable=maybe-no-member - request = service.files().export_media(fileId=file_id, - mimeType='application/pdf') - file = io.BytesIO() - downloader = MediaIoBaseDownload(file, request) - done = False - while done is False: - status, done = downloader.next_chunk() - print(F'Download {int(status.progress() * 100)}.') - - except HttpError as error: - print(F'An error occurred: {error}') - file = None - - return file.getvalue() - - -if __name__ == '__main__': - export_pdf(real_file_id='1zbp8wAyuImX91Jt9mI-CAX_1TqkBLDEDcr2WeXBbKUY') + """Download a Document file in PDF format. + Args: + real_file_id : file ID of any workspace document format file + Returns : IO object with location + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # create drive api client + service = build("drive", "v2", credentials=creds) + + file_id = real_file_id + + # pylint: disable=maybe-no-member + request = service.files().export_media( + fileId=file_id, mimeType="application/pdf" + ) + file = io.BytesIO() + downloader = MediaIoBaseDownload(file, request) + done = False + while done is False: + status, done = downloader.next_chunk() + print(f"Download {int(status.progress() * 100)}.") + + except HttpError as error: + print(f"An error occurred: {error}") + file = None + + return file.getvalue() + + +if __name__ == "__main__": + export_pdf(real_file_id="1zbp8wAyuImX91Jt9mI-CAX_1TqkBLDEDcr2WeXBbKUY") # [END drive_export_pdf] diff --git a/drive/snippets/drive-v2/file snippet/move_file_to_folder.py b/drive/snippets/drive-v2/file snippet/move_file_to_folder.py index 1717d737..a4093ce4 100644 --- a/drive/snippets/drive-v2/file snippet/move_file_to_folder.py +++ b/drive/snippets/drive-v2/file snippet/move_file_to_folder.py @@ -14,52 +14,61 @@ """ # [START drive_move_file_to_folder] - -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def move_file_to_folder(file_id, folder_id): - """Move specified file to the specified folder. - Args: - file_id: Id of the file to move. - folder_id: Id of the folder - Print: An object containing the new parent folder and other meta data - Returns : Parent Ids for the file + """Move specified file to the specified folder. + Args: + file_id: Id of the file to move. + folder_id: Id of the folder + Print: An object containing the new parent folder and other meta data + Returns : Parent Ids for the file - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() - try: - # call drive api client - service = build('drive', 'v2', credentials=creds) + try: + # call drive api client + service = build("drive", "v2", credentials=creds) - # Retrieve the existing parents to remove - # pylint: disable=maybe-no-member - file = service.files().get(fileId=file_id, fields='parents').execute() - previous_parents = ",".join( - [parent["id"] for parent in file.get('parents')]) - # Move the file to the new folder - file = service.files().update(fileId=file_id, addParents=folder_id, - removeParents=previous_parents, - fields='id, parents').execute() - new_parent_folder_id = [parent["id"] for parent in file.get('parents')] - print(F'file with ID : {file.get("id")} moved to folder : ' - F'{new_parent_folder_id}') - return [parent["id"] for parent in file.get('parents')] + # Retrieve the existing parents to remove + # pylint: disable=maybe-no-member + file = service.files().get(fileId=file_id, fields="parents").execute() + previous_parents = ",".join( + [parent["id"] for parent in file.get("parents")] + ) + # Move the file to the new folder + file = ( + service.files() + .update( + fileId=file_id, + addParents=folder_id, + removeParents=previous_parents, + fields="id, parents", + ) + .execute() + ) + new_parent_folder_id = [parent["id"] for parent in file.get("parents")] + print( + f'file with ID : {file.get("id")} moved to folder : ' + f"{new_parent_folder_id}" + ) + return [parent["id"] for parent in file.get("parents")] - except HttpError as error: - print(F'An error occurred: {error}') - return None + except HttpError as error: + print(f"An error occurred: {error}") + return None -if __name__ == '__main__': - move_file_to_folder(file_id='14fesChjgzDA7lUu9ZeGqXOuXMPgaVkxS', - folder_id='1KzT9gjq-AHfciwNzKjh7nUd6prrQOA4') +if __name__ == "__main__": + move_file_to_folder( + file_id="14fesChjgzDA7lUu9ZeGqXOuXMPgaVkxS", + folder_id="1KzT9gjq-AHfciwNzKjh7nUd6prrQOA4", + ) # [END drive_move_file_to_folder] diff --git a/drive/snippets/drive-v2/file snippet/search_file.py b/drive/snippets/drive-v2/file snippet/search_file.py index 9a2d28ef..efc990d9 100644 --- a/drive/snippets/drive-v2/file snippet/search_file.py +++ b/drive/snippets/drive-v2/file snippet/search_file.py @@ -13,51 +13,54 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START drive_search_file] - -from __future__ import print_function +# [START drive_search_file] import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def search_file(): - """Search file in drive location - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # create drive api client - service = build('drive', 'v2', credentials=creds) - files = [] - page_token = None - while True: - # pylint: disable=maybe-no-member - response = service.files().list(q="mimeType='image/jpeg'", - spaces='drive', - fields='nextPageToken, ' - 'items(id, title)', - pageToken=page_token).execute() - for file in response.get('items', []): - # Process change - print(F'Found file: {file.get("title")}, {file.get("id")}') - files.extend(response.get('items', [])) - page_token = response.get('nextPageToken', None) - if page_token is None: - break - - except HttpError as error: - print(F'An error occurred: {error}') - files = None - - return files - - -if __name__ == '__main__': - search_file() + """Search file in drive location + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # create drive api client + service = build("drive", "v2", credentials=creds) + files = [] + page_token = None + while True: + # pylint: disable=maybe-no-member + response = ( + service.files() + .list( + q="mimeType='image/jpeg'", + spaces="drive", + fields="nextPageToken, items(id, title)", + pageToken=page_token, + ) + .execute() + ) + for file in response.get("items", []): + # Process change + print(f'Found file: {file.get("title")}, {file.get("id")}') + files.extend(response.get("items", [])) + page_token = response.get("nextPageToken", None) + if page_token is None: + break + + except HttpError as error: + print(f"An error occurred: {error}") + files = None + + return files + + +if __name__ == "__main__": + search_file() # [END drive_search_file] diff --git a/drive/snippets/drive-v2/file snippet/share_file.py b/drive/snippets/drive-v2/file snippet/share_file.py index 5b8413f2..c45a11fd 100644 --- a/drive/snippets/drive-v2/file snippet/share_file.py +++ b/drive/snippets/drive-v2/file snippet/share_file.py @@ -13,74 +13,82 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START drive_share_file] - -from __future__ import print_function +# [START drive_share_file] import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def share_file(real_file_id, real_user, real_domain): - """Batch permission modification. - Args: - real_file_id: file Id - real_user: User ID - real_domain: Domain of the user ID - Prints modified permissions + """Batch permission modification. + Args: + real_file_id: file Id + real_user: User ID + real_domain: Domain of the user ID + Prints modified permissions - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() - try: - # create drive api client - service = build('drive', 'v2', credentials=creds) - ids = [] - file_id = real_file_id + try: + # create drive api client + service = build("drive", "v2", credentials=creds) + ids = [] + file_id = real_file_id - def callback(request_id, response, exception): - if exception: - print(exception) - else: - print(f'Request_Id: {request_id}') - print(F'Permission Id: {response.get("id")}') - ids.append(response.get('id')) + def callback(request_id, response, exception): + if exception: + print(exception) + else: + print(f"Request_Id: {request_id}") + print(f'Permission Id: {response.get("id")}') + ids.append(response.get("id")) - # pylint: disable=maybe-no-member - batch = service.new_batch_http_request(callback=callback) - user_permission = {'type': 'user', - 'role': 'writer', - 'value': 'user@example.com'} - user_permission['value'] = real_user - batch.add(service.permissions().insert( + # pylint: disable=maybe-no-member + batch = service.new_batch_http_request(callback=callback) + user_permission = { + "type": "user", + "role": "writer", + "value": "user@example.com", + } + user_permission["value"] = real_user + batch.add( + service.permissions().insert( fileId=file_id, body=user_permission, - fields='id', - )) - domain_permission = {'type': 'domain', - 'role': 'reader', - 'value': 'example.com'} - domain_permission['value'] = real_domain - batch.add(service.permissions().insert( + fields="id", + ) + ) + domain_permission = { + "type": "domain", + "role": "reader", + "value": "example.com", + } + domain_permission["value"] = real_domain + batch.add( + service.permissions().insert( fileId=file_id, body=domain_permission, - fields='id', - )) - batch.execute() + fields="id", + ) + ) + batch.execute() - except HttpError as error: - print(F'An error occurred: {error}') - ids = None + except HttpError as error: + print(f"An error occurred: {error}") + ids = None - return ids + return ids -if __name__ == '__main__': - share_file(real_file_id='1dUiRSoAQKkM3a4nTPeNQWgiuau1KdQ_l', - real_user='anurag@workspacesamples.dev', - real_domain='workspacesamples.dev') +if __name__ == "__main__": + share_file( + real_file_id="1dUiRSoAQKkM3a4nTPeNQWgiuau1KdQ_l", + real_user="anurag@workspacesamples.dev", + real_domain="workspacesamples.dev", + ) # [END drive_share_file] diff --git a/drive/snippets/drive-v2/file snippet/test_create_folder.py b/drive/snippets/drive-v2/file snippet/test_create_folder.py index 1cb7bfbd..24eb83d0 100644 --- a/drive/snippets/drive-v2/file snippet/test_create_folder.py +++ b/drive/snippets/drive-v2/file snippet/test_create_folder.py @@ -12,20 +12,21 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest import create_folder class TestCreateFolder(unittest.TestCase): - """Unit test class for file snippet""" + """Unit test class for file snippet""" - @classmethod - def test_create_folder(cls): - """Test create_folder""" - file_id = create_folder.create_folder() - cls.assertIsNotNone(cls, file_id) + @classmethod + def test_create_folder(cls): + """Test create_folder""" + file_id = create_folder.create_folder() + cls.assertIsNotNone(cls, file_id) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v2/file snippet/test_create_shortcut.py b/drive/snippets/drive-v2/file snippet/test_create_shortcut.py index 2e2f3080..82789471 100644 --- a/drive/snippets/drive-v2/file snippet/test_create_shortcut.py +++ b/drive/snippets/drive-v2/file snippet/test_create_shortcut.py @@ -12,20 +12,21 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest import create_shortcut class TestCreateShortcut(unittest.TestCase): - """Unit test class for file snippet""" + """Unit test class for file snippet""" - @classmethod - def test_create_shortcut(cls): - """Test create_folder""" - file_id = create_shortcut.create_shortcut() - cls.assertIsNotNone(cls, file_id) + @classmethod + def test_create_shortcut(cls): + """Test create_folder""" + file_id = create_shortcut.create_shortcut() + cls.assertIsNotNone(cls, file_id) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v2/file snippet/test_download_file.py b/drive/snippets/drive-v2/file snippet/test_download_file.py index 724b780c..bb5455bd 100644 --- a/drive/snippets/drive-v2/file snippet/test_download_file.py +++ b/drive/snippets/drive-v2/file snippet/test_download_file.py @@ -12,22 +12,23 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest import download_file class TestDownloadFile(unittest.TestCase): - """Unit test class for file snippet""" + """Unit test class for file snippet""" - @classmethod - def test_download_file(cls): - """Test Download_file""" - # valid file id - real_file_id = '1KuPmvGq8yoYgbfW74OENMCB5H0n_2Jm9' - file = download_file.download_file(real_file_id=real_file_id) - cls.assertNotEqual(cls, 0, len(file)) + @classmethod + def test_download_file(cls): + """Test Download_file""" + # valid file id + real_file_id = "1KuPmvGq8yoYgbfW74OENMCB5H0n_2Jm9" + file = download_file.download_file(real_file_id=real_file_id) + cls.assertNotEqual(cls, 0, len(file)) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v2/file snippet/test_export_pdf.py b/drive/snippets/drive-v2/file snippet/test_export_pdf.py index cf0ecb9f..e9dfb88f 100644 --- a/drive/snippets/drive-v2/file snippet/test_export_pdf.py +++ b/drive/snippets/drive-v2/file snippet/test_export_pdf.py @@ -12,22 +12,23 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest import export_pdf class TestExportPdf(unittest.TestCase): - """Unit test class for file snippet""" + """Unit test class for file snippet""" - @classmethod - def test_export_pdf(cls): - """Test export_pdf""" - # valid file ID - real_file_id = '1zbp8wAyuImX91Jt9mI-CAX_1TqkBLDEDcr2WeXBbKUY' - file = export_pdf.export_pdf(real_file_id=real_file_id) - cls.assertNotEqual(cls, 0, len(file)) + @classmethod + def test_export_pdf(cls): + """Test export_pdf""" + # valid file ID + real_file_id = "1zbp8wAyuImX91Jt9mI-CAX_1TqkBLDEDcr2WeXBbKUY" + file = export_pdf.export_pdf(real_file_id=real_file_id) + cls.assertNotEqual(cls, 0, len(file)) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v2/file snippet/test_move_file_to_folder.py b/drive/snippets/drive-v2/file snippet/test_move_file_to_folder.py index 579bf37f..6f9b933a 100644 --- a/drive/snippets/drive-v2/file snippet/test_move_file_to_folder.py +++ b/drive/snippets/drive-v2/file snippet/test_move_file_to_folder.py @@ -12,24 +12,26 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest import move_file_to_folder class TestMoveFileToFolder(unittest.TestCase): - """Unit test class for file snippet""" + """Unit test class for file snippet""" - @classmethod - def test_move_file_to_folder(cls): - """Test move_file_to_folder""" - real_file_id = '1KuPmvGq8yoYgbfW74OENMCB5H0n_2Jm9' - real_folder_id = '1v5eyIbXCr9TZX3eX_44HEExfe7yRj24V' + @classmethod + def test_move_file_to_folder(cls): + """Test move_file_to_folder""" + real_file_id = "1KuPmvGq8yoYgbfW74OENMCB5H0n_2Jm9" + real_folder_id = "1v5eyIbXCr9TZX3eX_44HEExfe7yRj24V" - update = move_file_to_folder.move_file_to_folder( - real_file_id=real_file_id, real_folder_id=real_folder_id) - cls.assertIsNotNone(cls, 0, len(update)) + update = move_file_to_folder.move_file_to_folder( + real_file_id=real_file_id, real_folder_id=real_folder_id + ) + cls.assertIsNotNone(cls, 0, len(update)) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v2/file snippet/test_search_file.py b/drive/snippets/drive-v2/file snippet/test_search_file.py index 964d2a6b..a86d2158 100644 --- a/drive/snippets/drive-v2/file snippet/test_search_file.py +++ b/drive/snippets/drive-v2/file snippet/test_search_file.py @@ -12,20 +12,21 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest import search_file class TestSearchFile(unittest.TestCase): - """Unit test class for file snippet""" + """Unit test class for file snippet""" - @classmethod - def test_search_file(cls): - """Test search_file""" - file = search_file.search_file() - cls.assertNotEqual(cls, 0, len(file)) + @classmethod + def test_search_file(cls): + """Test search_file""" + file = search_file.search_file() + cls.assertNotEqual(cls, 0, len(file)) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v2/file snippet/test_share_file.py b/drive/snippets/drive-v2/file snippet/test_share_file.py index 85392192..9bfdd717 100644 --- a/drive/snippets/drive-v2/file snippet/test_share_file.py +++ b/drive/snippets/drive-v2/file snippet/test_share_file.py @@ -12,25 +12,26 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest import share_file class TestShareFile(unittest.TestCase): - """Unit test class for file snippet""" - - @classmethod - def test_share_file(cls): - """Test share_file""" - real_file_id = '1dUiRSoAQKkM3a4nTPeNQWgiuau1KdQ_l' - real_user = 'gduser1@workspacesamples.dev' - real_domain = 'workspacesamples.dev' - file = share_file.share_file(real_file_id=real_file_id, - real_user=real_user, - real_domain=real_domain) - cls.assertNotEqual(cls, 0, len(file)) - - -if __name__ == '__main__': - unittest.main() + """Unit test class for file snippet""" + + @classmethod + def test_share_file(cls): + """Test share_file""" + real_file_id = "1dUiRSoAQKkM3a4nTPeNQWgiuau1KdQ_l" + real_user = "gduser1@workspacesamples.dev" + real_domain = "workspacesamples.dev" + file = share_file.share_file( + real_file_id=real_file_id, real_user=real_user, real_domain=real_domain + ) + cls.assertNotEqual(cls, 0, len(file)) + + +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v2/file snippet/test_touch_file.py b/drive/snippets/drive-v2/file snippet/test_touch_file.py index cd1f68a4..f35dc08d 100644 --- a/drive/snippets/drive-v2/file snippet/test_touch_file.py +++ b/drive/snippets/drive-v2/file snippet/test_touch_file.py @@ -12,6 +12,7 @@ See the License for the specific language governing permissions and limitations under the License. """ + import re import unittest from datetime import datetime @@ -20,18 +21,19 @@ class TestTouchFile(unittest.TestCase): - """Unit test class for file snippet""" - - @classmethod - def test_touch_file(cls): - """Test touch_file""" - real_file_id = '1KuPmvGq8yoYgbfW74OENMCB5H0n_2Jm9' - now = datetime.utcnow().isoformat() + 'Z' - now = re.sub(r'\d{3}Z', 'Z', now) # Truncate microseconds - modified_time = touch_file.touch_file(real_file_id=real_file_id, - real_timestamp=now) - cls.assertIsNotNone(cls, modified_time) - - -if __name__ == '__main__': - unittest.main() + """Unit test class for file snippet""" + + @classmethod + def test_touch_file(cls): + """Test touch_file""" + real_file_id = "1KuPmvGq8yoYgbfW74OENMCB5H0n_2Jm9" + now = datetime.utcnow().isoformat() + "Z" + now = re.sub(r"\d{3}Z", "Z", now) # Truncate microseconds + modified_time = touch_file.touch_file( + real_file_id=real_file_id, real_timestamp=now + ) + cls.assertIsNotNone(cls, modified_time) + + +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v2/file snippet/test_upload_basic.py b/drive/snippets/drive-v2/file snippet/test_upload_basic.py index 3d6c473d..c0bb7c30 100644 --- a/drive/snippets/drive-v2/file snippet/test_upload_basic.py +++ b/drive/snippets/drive-v2/file snippet/test_upload_basic.py @@ -12,20 +12,21 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest import upload_basic class TestUploadBasic(unittest.TestCase): - """Unit test class for file snippet""" + """Unit test class for file snippet""" - @classmethod - def test_upload_basic(cls): - """Test upload_basic""" - file_id = upload_basic.upload_basic() - cls.assertIsNotNone(cls, file_id) + @classmethod + def test_upload_basic(cls): + """Test upload_basic""" + file_id = upload_basic.upload_basic() + cls.assertIsNotNone(cls, file_id) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v2/file snippet/test_upload_revision.py b/drive/snippets/drive-v2/file snippet/test_upload_revision.py index 88f396e5..c1ab5a6d 100644 --- a/drive/snippets/drive-v2/file snippet/test_upload_revision.py +++ b/drive/snippets/drive-v2/file snippet/test_upload_revision.py @@ -12,22 +12,23 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest import upload_revision class TestUploadRevision(unittest.TestCase): - """Unit test class for file snippet""" + """Unit test class for file snippet""" - @classmethod - def test_upload_revision(cls): - """Test upload_revision""" + @classmethod + def test_upload_revision(cls): + """Test upload_revision""" - real_file_id = '1KuPmvGq8yoYgbfW74OENMCB5H0n_2Jm9' - file_id = upload_revision.upload_revision(real_file_id=real_file_id) - cls.assertIsNotNone(cls, file_id) + real_file_id = "1KuPmvGq8yoYgbfW74OENMCB5H0n_2Jm9" + file_id = upload_revision.upload_revision(real_file_id=real_file_id) + cls.assertIsNotNone(cls, file_id) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v2/file snippet/test_upload_to_folder.py b/drive/snippets/drive-v2/file snippet/test_upload_to_folder.py index 4b129df3..776f23cd 100644 --- a/drive/snippets/drive-v2/file snippet/test_upload_to_folder.py +++ b/drive/snippets/drive-v2/file snippet/test_upload_to_folder.py @@ -12,22 +12,22 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest import upload_to_folder class TestUploadToFolder(unittest.TestCase): - """Unit test class for file snippet""" + """Unit test class for file snippet""" - @classmethod - def test_upload_to_folder(cls): - """Test upload_to_folder""" - real_folder_id = '1s0oKEZZXjImNngxHGnY0xed6Mw-tvspu' - file_id = upload_to_folder.upload_to_folder( - real_folder_id=real_folder_id) - cls.assertIsNotNone(cls, file_id) + @classmethod + def test_upload_to_folder(cls): + """Test upload_to_folder""" + real_folder_id = "1s0oKEZZXjImNngxHGnY0xed6Mw-tvspu" + file_id = upload_to_folder.upload_to_folder(real_folder_id=real_folder_id) + cls.assertIsNotNone(cls, file_id) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v2/file snippet/test_upload_with_conversion.py b/drive/snippets/drive-v2/file snippet/test_upload_with_conversion.py index 563f5c70..ce3bd168 100644 --- a/drive/snippets/drive-v2/file snippet/test_upload_with_conversion.py +++ b/drive/snippets/drive-v2/file snippet/test_upload_with_conversion.py @@ -12,20 +12,21 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest import upload_with_conversion class TestUploadWithConversion(unittest.TestCase): - """Unit test class for file snippet""" + """Unit test class for file snippet""" - @classmethod - def test_upload_to_folder(cls): - """Test upload_with_conversion""" - file_id = upload_with_conversion.upload_with_conversion() - cls.assertIsNotNone(cls, file_id) + @classmethod + def test_upload_to_folder(cls): + """Test upload_with_conversion""" + file_id = upload_with_conversion.upload_with_conversion() + cls.assertIsNotNone(cls, file_id) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v2/file snippet/touch_file.py b/drive/snippets/drive-v2/file snippet/touch_file.py index 1ba0826f..8369b274 100644 --- a/drive/snippets/drive-v2/file snippet/touch_file.py +++ b/drive/snippets/drive-v2/file snippet/touch_file.py @@ -13,10 +13,8 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START drive_touch_file] - -from __future__ import print_function +# [START drive_touch_file] from datetime import datetime import google.auth @@ -25,42 +23,49 @@ def touch_file(real_file_id, real_timestamp): - """Change the file's modification timestamp. - Args: - real_file_id: ID of the file to change modified time - real_timestamp: Timestamp to override Modified date time of the file - Returns : Modified Date and time. - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # create drive api client - service = build('drive', 'v2', credentials=creds) - - file_metadata = { - 'modifiedDate': datetime.utcnow().isoformat() + 'Z' - } - - file_id = real_file_id - file_metadata['modifiedDate'] = real_timestamp - # pylint: disable=maybe-no-member - file = service.files().update(fileId=file_id, body=file_metadata, - setModifiedDate=True, - fields='id, modifiedDate').execute() - print(F'Modified time: {file.get("modifiedDate")}') - - except HttpError as error: - print(F'An error occurred: {error}') - file = None - - return file.get('modifiedDate') - - -if __name__ == '__main__': - touch_file(real_file_id='1KuPmvGq8yoYgbfW74OENMCB5H0n_2Jm9', - real_timestamp='2022-03-02T05:43:27.504Z') + """Change the file's modification timestamp. + Args: + real_file_id: ID of the file to change modified time + real_timestamp: Timestamp to override Modified date time of the file + Returns : Modified Date and time. + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # create drive api client + service = build("drive", "v2", credentials=creds) + + file_metadata = {"modifiedDate": datetime.utcnow().isoformat() + "Z"} + + file_id = real_file_id + file_metadata["modifiedDate"] = real_timestamp + # pylint: disable=maybe-no-member + file = ( + service.files() + .update( + fileId=file_id, + body=file_metadata, + setModifiedDate=True, + fields="id, modifiedDate", + ) + .execute() + ) + print(f'Modified time: {file.get("modifiedDate")}') + + except HttpError as error: + print(f"An error occurred: {error}") + file = None + + return file.get("modifiedDate") + + +if __name__ == "__main__": + touch_file( + real_file_id="1KuPmvGq8yoYgbfW74OENMCB5H0n_2Jm9", + real_timestamp="2022-03-02T05:43:27.504Z", + ) # [END drive_touch_file] diff --git a/drive/snippets/drive-v2/file snippet/upload_basic.py b/drive/snippets/drive-v2/file snippet/upload_basic.py index e773bddf..2821ed9d 100644 --- a/drive/snippets/drive-v2/file snippet/upload_basic.py +++ b/drive/snippets/drive-v2/file snippet/upload_basic.py @@ -13,10 +13,8 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START drive_upload_basic] - -from __future__ import print_function +# [START drive_upload_basic] import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError @@ -24,34 +22,36 @@ def upload_basic(): - """Insert new file. - Returns : Id's of the file uploaded - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # create drive api client - service = build('drive', 'v2', credentials=creds) - - file_metadata = {'title': 'photo.jpg'} - media = MediaFileUpload('photo.jpg', - mimetype='image/jpeg') - # pylint: disable=maybe-no-member - file = service.files().insert(body=file_metadata, media_body=media, - fields='id').execute() - print(F'File ID: {file.get("id")}') - - except HttpError as error: - print(F'An error occurred: {error}') - file = None - - return file.get('id') - - -if __name__ == '__main__': - upload_basic() + """Insert new file. + Returns : Id's of the file uploaded + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # create drive api client + service = build("drive", "v2", credentials=creds) + + file_metadata = {"title": "photo.jpg"} + media = MediaFileUpload("photo.jpg", mimetype="image/jpeg") + # pylint: disable=maybe-no-member + file = ( + service.files() + .insert(body=file_metadata, media_body=media, fields="id") + .execute() + ) + print(f'File ID: {file.get("id")}') + + except HttpError as error: + print(f"An error occurred: {error}") + file = None + + return file.get("id") + + +if __name__ == "__main__": + upload_basic() # [END drive_upload_basic] diff --git a/drive/snippets/drive-v2/file snippet/upload_revision.py b/drive/snippets/drive-v2/file snippet/upload_revision.py index b823a9d3..7cce8f5a 100644 --- a/drive/snippets/drive-v2/file snippet/upload_revision.py +++ b/drive/snippets/drive-v2/file snippet/upload_revision.py @@ -13,10 +13,8 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START drive_upload_revision] - -from __future__ import print_function +# [START drive_upload_revision] import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError @@ -24,36 +22,35 @@ def upload_revision(real_file_id): - """Replace the old file with new one on same file ID - Args: ID of the file to be replaced - Returns: file ID - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # create drive api client - service = build('drive', 'v2', credentials=creds) - file_id = real_file_id - media = MediaFileUpload('photo.jpg', - mimetype='image/jpeg', - resumable=True) - # pylint: disable=maybe-no-member - file = service.files().update(fileId=file_id, - body={}, - media_body=media, - fields='id').execute() - print(F'File ID: {file.get("id")}') - - except HttpError as error: - print(F'An error occurred: {error}') - - return file.get('id') - - -if __name__ == '__main__': - upload_revision(real_file_id='1M4xjYwPynOk5TsIWN7hcGYkFdBkPTd5F') + """Replace the old file with new one on same file ID + Args: ID of the file to be replaced + Returns: file ID + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # create drive api client + service = build("drive", "v2", credentials=creds) + file_id = real_file_id + media = MediaFileUpload("photo.jpg", mimetype="image/jpeg", resumable=True) + # pylint: disable=maybe-no-member + file = ( + service.files() + .update(fileId=file_id, body={}, media_body=media, fields="id") + .execute() + ) + print(f'File ID: {file.get("id")}') + + except HttpError as error: + print(f"An error occurred: {error}") + + return file.get("id") + + +if __name__ == "__main__": + upload_revision(real_file_id="1M4xjYwPynOk5TsIWN7hcGYkFdBkPTd5F") # [END drive_upload_revision] diff --git a/drive/snippets/drive-v2/file snippet/upload_to_folder.py b/drive/snippets/drive-v2/file snippet/upload_to_folder.py index 1845868a..4b9a5179 100644 --- a/drive/snippets/drive-v2/file snippet/upload_to_folder.py +++ b/drive/snippets/drive-v2/file snippet/upload_to_folder.py @@ -13,10 +13,8 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START drive_upload_to_folder] - -from __future__ import print_function +# [START drive_upload_to_folder] import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError @@ -24,37 +22,36 @@ def upload_to_folder(folder_id): - """Upload a file to the specified folder and prints file ID, folder ID - Args: Id of the folder - Returns: ID of the file uploaded - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # create drive api client - service = build('drive', 'v2', credentials=creds) - - file_metadata = { - 'title': 'photo.jpg', - 'parents': [{'id': folder_id}] - } - media = MediaFileUpload('photo.jpg', - mimetype='image/jpeg', resumable=True) - # pylint: disable=maybe-no-member - file = service.files().insert(body=file_metadata, - media_body=media, fields='id').execute() - print(F'File ID: "{file.get("id")}".') - return file.get('id') - - except HttpError as error: - print(F'An error occurred: {error}') - return None - - -if __name__ == '__main__': - upload_to_folder(folder_id='1s0oKEZZXjImNngxHGnY0xed6Mw-tvspu') + """Upload a file to the specified folder and prints file ID, folder ID + Args: Id of the folder + Returns: ID of the file uploaded + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # create drive api client + service = build("drive", "v2", credentials=creds) + + file_metadata = {"title": "photo.jpg", "parents": [{"id": folder_id}]} + media = MediaFileUpload("photo.jpg", mimetype="image/jpeg", resumable=True) + # pylint: disable=maybe-no-member + file = ( + service.files() + .insert(body=file_metadata, media_body=media, fields="id") + .execute() + ) + print(f'File ID: "{file.get("id")}".') + return file.get("id") + + except HttpError as error: + print(f"An error occurred: {error}") + return None + + +if __name__ == "__main__": + upload_to_folder(folder_id="1s0oKEZZXjImNngxHGnY0xed6Mw-tvspu") # [END drive_upload_to_folder] diff --git a/drive/snippets/drive-v2/file snippet/upload_with_conversion.py b/drive/snippets/drive-v2/file snippet/upload_with_conversion.py index 34cf747e..1e010f67 100644 --- a/drive/snippets/drive-v2/file snippet/upload_with_conversion.py +++ b/drive/snippets/drive-v2/file snippet/upload_with_conversion.py @@ -13,10 +13,8 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START drive_upload_with_conversion] - -from __future__ import print_function +# [START drive_upload_with_conversion] import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError @@ -24,37 +22,39 @@ def upload_with_conversion(): - """Upload file with conversion - Returns: ID of the file uploaded - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # create drive api client - service = build('drive', 'v2', credentials=creds) - - file_metadata = { - 'title': 'My Report', - 'mimeType': 'application/vnd.google-apps.spreadsheet' - } - media = MediaFileUpload('report.csv', mimetype='text/csv', - resumable=True) - # pylint: disable=maybe-no-member - file = service.files().insert(body=file_metadata, - media_body=media, fields='id').execute() - print(F'File with ID: "{file.get("id")}" has been uploaded.') - - except HttpError as error: - print(F'An error occurred: {error}') - file = None - - return file.get('id') - - -if __name__ == '__main__': - upload_with_conversion() + """Upload file with conversion + Returns: ID of the file uploaded + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # create drive api client + service = build("drive", "v2", credentials=creds) + + file_metadata = { + "title": "My Report", + "mimeType": "application/vnd.google-apps.spreadsheet", + } + media = MediaFileUpload("report.csv", mimetype="text/csv", resumable=True) + # pylint: disable=maybe-no-member + file = ( + service.files() + .insert(body=file_metadata, media_body=media, fields="id") + .execute() + ) + print(f'File with ID: "{file.get("id")}" has been uploaded.') + + except HttpError as error: + print(f"An error occurred: {error}") + file = None + + return file.get("id") + + +if __name__ == "__main__": + upload_with_conversion() # [END drive_upload_with_conversion] diff --git a/drive/snippets/drive-v2/team_drive_snippets/create_team_drive.py b/drive/snippets/drive-v2/team_drive_snippets/create_team_drive.py index de62d616..1c1b1a79 100644 --- a/drive/snippets/drive-v2/team_drive_snippets/create_team_drive.py +++ b/drive/snippets/drive-v2/team_drive_snippets/create_team_drive.py @@ -14,9 +14,6 @@ """ # [START drive_create_team_drive] - -from __future__ import print_function - import uuid import google.auth @@ -25,34 +22,36 @@ def create_team_drive(): - """ Create a drive for team. - Returns: ID of the created drive - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # call drive api client - service = build('drive', 'v2', credentials=creds) - - # pylint: disable=maybe-no-member - team_drive_metadata = {'name': 'Project Resources'} - request_id = str(uuid.uuid4()) - team_drive = service.teamdrives().insert(body=team_drive_metadata, - requestId=request_id, - fields='id').execute() - print(F'Team Drive ID: {team_drive.get("id")}') - - except HttpError as error: - print(F'An error occurred: {error}') - team_drive = None - - return team_drive.get('id') - - -if __name__ == '__main__': - create_team_drive() + """Create a drive for team. + Returns: ID of the created drive + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # call drive api client + service = build("drive", "v2", credentials=creds) + + # pylint: disable=maybe-no-member + team_drive_metadata = {"name": "Project Resources"} + request_id = str(uuid.uuid4()) + team_drive = ( + service.teamdrives() + .insert(body=team_drive_metadata, requestId=request_id, fields="id") + .execute() + ) + print(f'Team Drive ID: {team_drive.get("id")}') + + except HttpError as error: + print(f"An error occurred: {error}") + team_drive = None + + return team_drive.get("id") + + +if __name__ == "__main__": + create_team_drive() # [END drive_create_team_drive] diff --git a/drive/snippets/drive-v2/team_drive_snippets/recover_team_drives.py b/drive/snippets/drive-v2/team_drive_snippets/recover_team_drives.py index e2ff27eb..150f9710 100644 --- a/drive/snippets/drive-v2/team_drive_snippets/recover_team_drives.py +++ b/drive/snippets/drive-v2/team_drive_snippets/recover_team_drives.py @@ -14,68 +14,80 @@ """ # [START drive_recover_team_drives] - -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def recover_team_drives(real_user): - """Finds all Team Drives without an organizer and add one - Args: - real_user:User ID for the new organizer. - Returns: - team drives_object. - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # call drive api client - service = build('drive', 'v2', credentials=creds) - - # pylint: disable=maybe-no-member - team_drives = [] - - page_token = None - new_organizer_permission = {'type': 'user', - 'role': 'organizer', - 'value': 'user@example.com'} - new_organizer_permission['value'] = real_user - - while True: - response = service.teamdrives().list(q='organizerCount = 0', - useDomainAdminAccess=True, - fields='nextPageToken, ' - 'items(id, name)', - pageToken=page_token) \ - .execute() - for team_drive in response.get('items', []): - print(F'Found Team Drive without organizer: ' - F'{team_drive.get("title")}, {team_drive.get("id")}') - permission = service.permissions().insert( - fileId=team_drive.get('id'), - body=new_organizer_permission, useDomainAdminAccess=True, - supportsTeamDrives=True, fields='id').execute() - print(F'Added organizer permission: {permission.get("id")}') - - team_drives.extend(response.get('items', [])) - page_token = response.get('nextPageToken', None) - if page_token is None: - break - - except HttpError as error: - print(F'An error occurred: {error}') - team_drives = None - - print(team_drives) - - -if __name__ == '__main__': - recover_team_drives(real_user='rajesh@workspacesamples.dev') + """Finds all Team Drives without an organizer and add one + Args: + real_user:User ID for the new organizer. + Returns: + team drives_object. + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # call drive api client + service = build("drive", "v2", credentials=creds) + + # pylint: disable=maybe-no-member + team_drives = [] + + page_token = None + new_organizer_permission = { + "type": "user", + "role": "organizer", + "value": "user@example.com", + } + new_organizer_permission["value"] = real_user + + while True: + response = ( + service.teamdrives() + .list( + q="organizerCount = 0", + useDomainAdminAccess=True, + fields="nextPageToken, items(id, name)", + pageToken=page_token, + ) + .execute() + ) + for team_drive in response.get("items", []): + print( + "Found Team Drive without organizer: " + f"{team_drive.get('title')}, {team_drive.get('id')}" + ) + permission = ( + service.permissions() + .insert( + fileId=team_drive.get("id"), + body=new_organizer_permission, + useDomainAdminAccess=True, + supportsTeamDrives=True, + fields="id", + ) + .execute() + ) + print(f'Added organizer permission: {permission.get("id")}') + + team_drives.extend(response.get("items", [])) + page_token = response.get("nextPageToken", None) + if page_token is None: + break + + except HttpError as error: + print(f"An error occurred: {error}") + team_drives = None + + print(team_drives) + + +if __name__ == "__main__": + recover_team_drives(real_user="rajesh@workspacesamples.dev") # [END drive_recover_team_drives] diff --git a/drive/snippets/drive-v3/app_data_snippet/fetch_appdata_folder.py b/drive/snippets/drive-v3/app_data_snippet/fetch_appdata_folder.py index c69dd7a5..2cfa9117 100644 --- a/drive/snippets/drive-v3/app_data_snippet/fetch_appdata_folder.py +++ b/drive/snippets/drive-v3/app_data_snippet/fetch_appdata_folder.py @@ -14,40 +14,36 @@ """ # [START drive_fetch_appdata_folder] - -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def fetch_appdata_folder(): - """List out application data folder and prints folder ID. - Returns : Folder ID + """List out application data folder and prints folder ID. + Returns : Folder ID - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() - try: - # call drive api client - service = build('drive', 'v3', credentials=creds) + try: + # call drive api client + service = build("drive", "v3", credentials=creds) - # pylint: disable=maybe-no-member - file = service.files().get(fileId='appDataFolder', - fields='id').execute() - print(F'Folder ID: {file.get("id")}') + # pylint: disable=maybe-no-member + file = service.files().get(fileId="appDataFolder", fields="id").execute() + print(f'Folder ID: {file.get("id")}') - except HttpError as error: - print(F'An error occurred: {error}') - file = None + except HttpError as error: + print(f"An error occurred: {error}") + file = None - return file.get('id') + return file.get("id") -if __name__ == '__main__': - fetch_appdata_folder() +if __name__ == "__main__": + fetch_appdata_folder() # [END drive_fetch_appdata_folder] diff --git a/drive/snippets/drive-v3/app_data_snippet/list_appdata.py b/drive/snippets/drive-v3/app_data_snippet/list_appdata.py index 608699ec..e69fe22a 100644 --- a/drive/snippets/drive-v3/app_data_snippet/list_appdata.py +++ b/drive/snippets/drive-v3/app_data_snippet/list_appdata.py @@ -14,44 +14,47 @@ """ # [START drive_list_appdata] - -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def list_appdata(): - """List all files inserted in the application data folder - prints file titles with Ids. - Returns : List of items - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # call drive api client - service = build('drive', 'v3', credentials=creds) - - # pylint: disable=maybe-no-member - response = service.files().list(spaces='appDataFolder', - fields='nextPageToken, files(id, ' - 'name)', pageSize=10).execute() - for file in response.get('files', []): - # Process change - print(F'Found file: {file.get("name")}, {file.get("id")}') - - except HttpError as error: - print(F'An error occurred: {error}') - response = None - - return response.get('files') - - -if __name__ == '__main__': - list_appdata() + """List all files inserted in the application data folder + prints file titles with Ids. + Returns : List of items + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # call drive api client + service = build("drive", "v3", credentials=creds) + + # pylint: disable=maybe-no-member + response = ( + service.files() + .list( + spaces="appDataFolder", + fields="nextPageToken, files(id, name)", + pageSize=10, + ) + .execute() + ) + for file in response.get("files", []): + # Process change + print(f'Found file: {file.get("name")}, {file.get("id")}') + + except HttpError as error: + print(f"An error occurred: {error}") + response = None + + return response.get("files") + + +if __name__ == "__main__": + list_appdata() # [END drive_list_appdata] diff --git a/drive/snippets/drive-v3/app_data_snippet/test_fetch_appdata_folder.py b/drive/snippets/drive-v3/app_data_snippet/test_fetch_appdata_folder.py index c48b3472..5eddf5f8 100644 --- a/drive/snippets/drive-v3/app_data_snippet/test_fetch_appdata_folder.py +++ b/drive/snippets/drive-v3/app_data_snippet/test_fetch_appdata_folder.py @@ -12,20 +12,21 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest import fetch_appdata_folder class TestFetchAppdataFolder(unittest.TestCase): - """Unit test class for Appdata snippet""" + """Unit test class for Appdata snippet""" - @classmethod - def test_list_appdata(cls): - """Test list_appdata""" - file_id = fetch_appdata_folder.fetch_appdata_folder() - cls.assertIsNotNone(cls, file_id) + @classmethod + def test_list_appdata(cls): + """Test list_appdata""" + file_id = fetch_appdata_folder.fetch_appdata_folder() + cls.assertIsNotNone(cls, file_id) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v3/app_data_snippet/test_list_appdata.py b/drive/snippets/drive-v3/app_data_snippet/test_list_appdata.py index dd66a706..f4a959a2 100644 --- a/drive/snippets/drive-v3/app_data_snippet/test_list_appdata.py +++ b/drive/snippets/drive-v3/app_data_snippet/test_list_appdata.py @@ -12,20 +12,21 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest import list_appdata class TestListAppdata(unittest.TestCase): - """Unit test class for Appdata snippet""" + """Unit test class for Appdata snippet""" - @classmethod - def test_list_appdata(cls): - """Test list_appdata""" - files = list_appdata.list_appdata() - cls.assertNotEqual(cls, 0, len(files)) + @classmethod + def test_list_appdata(cls): + """Test list_appdata""" + files = list_appdata.list_appdata() + cls.assertNotEqual(cls, 0, len(files)) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v3/app_data_snippet/test_upload_appdata.py b/drive/snippets/drive-v3/app_data_snippet/test_upload_appdata.py index 95b5025b..e4835c35 100644 --- a/drive/snippets/drive-v3/app_data_snippet/test_upload_appdata.py +++ b/drive/snippets/drive-v3/app_data_snippet/test_upload_appdata.py @@ -12,24 +12,25 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest import upload_app_data class TestUploadAppdata(unittest.TestCase): + """ + Unit test class for Appdata snippet + """ + + @classmethod + def test_upload_adddata(cls): + """Test upload_appdata + create a text file titled "abc.txt" in order to pass this test """ - Unit test class for Appdata snippet - """ - - @classmethod - def test_upload_adddata(cls): - """Test upload_appdata - create a text file titled "abc.txt" in order to pass this test - """ - file_id = upload_app_data.upload_appdata() - cls.assertIsNotNone(cls, file_id) + file_id = upload_app_data.upload_appdata() + cls.assertIsNotNone(cls, file_id) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v3/app_data_snippet/upload_appdata.py b/drive/snippets/drive-v3/app_data_snippet/upload_appdata.py index 58d34a05..c35f3e66 100644 --- a/drive/snippets/drive-v3/app_data_snippet/upload_appdata.py +++ b/drive/snippets/drive-v3/app_data_snippet/upload_appdata.py @@ -14,9 +14,6 @@ """ # [START drive_upload_appdata] - -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError @@ -24,38 +21,36 @@ def upload_appdata(): - """Insert a file in the application data folder and prints file Id. - Returns : ID's of the inserted files - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # call drive api client - service = build('drive', 'v3', credentials=creds) - - # pylint: disable=maybe-no-member - file_metadata = { - 'name': 'abc.txt', - 'parents': ['appDataFolder'] - } - media = MediaFileUpload('abc.txt', - mimetype='text/txt', - resumable=True) - file = service.files().create(body=file_metadata, media_body=media, - fields='id').execute() - print(F'File ID: {file.get("id")}') - - except HttpError as error: - print(F'An error occurred: {error}') - file = None - - return file.get('id') - - -if __name__ == '__main__': - upload_appdata() + """Insert a file in the application data folder and prints file Id. + Returns : ID's of the inserted files + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # call drive api client + service = build("drive", "v3", credentials=creds) + + # pylint: disable=maybe-no-member + file_metadata = {"name": "abc.txt", "parents": ["appDataFolder"]} + media = MediaFileUpload("abc.txt", mimetype="text/txt", resumable=True) + file = ( + service.files() + .create(body=file_metadata, media_body=media, fields="id") + .execute() + ) + print(f'File ID: {file.get("id")}') + + except HttpError as error: + print(f"An error occurred: {error}") + file = None + + return file.get("id") + + +if __name__ == "__main__": + upload_appdata() # [END drive_upload_appdata] diff --git a/drive/snippets/drive-v3/change_snippet/fetch_changes.py b/drive/snippets/drive-v3/change_snippet/fetch_changes.py index b73d198f..d6809e51 100644 --- a/drive/snippets/drive-v3/change_snippet/fetch_changes.py +++ b/drive/snippets/drive-v3/change_snippet/fetch_changes.py @@ -10,56 +10,55 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START drive_fetch_changes] - -from __future__ import print_function +# [START drive_fetch_changes] import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def fetch_changes(saved_start_page_token): - """Retrieve the list of changes for the currently authenticated user. - prints changed file's ID - Args: - saved_start_page_token : StartPageToken for the current state of the - account. - Returns: saved start page token. + """Retrieve the list of changes for the currently authenticated user. + prints changed file's ID + Args: + saved_start_page_token : StartPageToken for the current state of the + account. + Returns: saved start page token. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - try: - # create drive api client - service = build('drive', 'v3', credentials=creds) + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + try: + # create drive api client + service = build("drive", "v3", credentials=creds) - # Begin with our last saved start token for this user or the - # current token from getStartPageToken() - page_token = saved_start_page_token - # pylint: disable=maybe-no-member + # Begin with our last saved start token for this user or the + # current token from getStartPageToken() + page_token = saved_start_page_token + # pylint: disable=maybe-no-member - while page_token is not None: - response = service.changes().list(pageToken=page_token, - spaces='drive').execute() - for change in response.get('changes'): - # Process change - print(F'Change found for file: {change.get("fileId")}') - if 'newStartPageToken' in response: - # Last page, save this token for the next polling interval - saved_start_page_token = response.get('newStartPageToken') - page_token = response.get('nextPageToken') + while page_token is not None: + response = ( + service.changes().list(pageToken=page_token, spaces="drive").execute() + ) + for change in response.get("changes"): + # Process change + print(f'Change found for file: {change.get("fileId")}') + if "newStartPageToken" in response: + # Last page, save this token for the next polling interval + saved_start_page_token = response.get("newStartPageToken") + page_token = response.get("nextPageToken") - except HttpError as error: - print(F'An error occurred: {error}') - saved_start_page_token = None + except HttpError as error: + print(f"An error occurred: {error}") + saved_start_page_token = None - return saved_start_page_token + return saved_start_page_token -if __name__ == '__main__': - # saved_start_page_token is the token number - fetch_changes(saved_start_page_token=209) +if __name__ == "__main__": + # saved_start_page_token is the token number + fetch_changes(saved_start_page_token=209) # [END drive_fetch_changes] diff --git a/drive/snippets/drive-v3/change_snippet/fetch_start_page_token.py b/drive/snippets/drive-v3/change_snippet/fetch_start_page_token.py index 2a3f87f1..df36b35a 100644 --- a/drive/snippets/drive-v3/change_snippet/fetch_start_page_token.py +++ b/drive/snippets/drive-v3/change_snippet/fetch_start_page_token.py @@ -10,40 +10,38 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START drive_fetch_start_page_token] - -from __future__ import print_function +# [START drive_fetch_start_page_token] import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def fetch_start_page_token(): - """Retrieve page token for the current state of the account. - Returns & prints : start page token + """Retrieve page token for the current state of the account. + Returns & prints : start page token - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() - try: - # create drive api client - service = build('drive', 'v3', credentials=creds) + try: + # create drive api client + service = build("drive", "v3", credentials=creds) - # pylint: disable=maybe-no-member - response = service.changes().getStartPageToken().execute() - print(F'Start token: {response.get("startPageToken")}') + # pylint: disable=maybe-no-member + response = service.changes().getStartPageToken().execute() + print(f'Start token: {response.get("startPageToken")}') - except HttpError as error: - print(F'An error occurred: {error}') - response = None + except HttpError as error: + print(f"An error occurred: {error}") + response = None - return response.get('startPageToken') + return response.get("startPageToken") -if __name__ == '__main__': - fetch_start_page_token() +if __name__ == "__main__": + fetch_start_page_token() # [END drive_fetch_start_page_token] diff --git a/drive/snippets/drive-v3/change_snippet/test_fetch_changes.py b/drive/snippets/drive-v3/change_snippet/test_fetch_changes.py index a172f69e..adb16f2d 100644 --- a/drive/snippets/drive-v3/change_snippet/test_fetch_changes.py +++ b/drive/snippets/drive-v3/change_snippet/test_fetch_changes.py @@ -20,15 +20,15 @@ class TestFetchChanges(unittest.TestCase): - """Unit test classs for Change snippet""" + """Unit test class for Change snippet""" - @classmethod - def test_fetch_changes(cls): - """Test fetch_changes""" - start_token = fetch_start_page_token.fetch_start_page_token() - token = fetch_changes.fetch_changes(start_token) - cls.assertIsNotNone(cls, token) + @classmethod + def test_fetch_changes(cls): + """Test fetch_changes""" + start_token = fetch_start_page_token.fetch_start_page_token() + token = fetch_changes.fetch_changes(start_token) + cls.assertIsNotNone(cls, token) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v3/change_snippet/test_fetch_start_page_token.py b/drive/snippets/drive-v3/change_snippet/test_fetch_start_page_token.py index 9405cfa6..69b2cd15 100644 --- a/drive/snippets/drive-v3/change_snippet/test_fetch_start_page_token.py +++ b/drive/snippets/drive-v3/change_snippet/test_fetch_start_page_token.py @@ -12,20 +12,21 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest import fetch_start_page_token class TestFetchChanges(unittest.TestCase): - """Unit test classs for Change snippet""" + """Unit test class for Change snippet""" - @classmethod - def test_fetch_start_page_token(cls): - """Test fetch_start_page_token""" - token = fetch_start_page_token.fetch_start_page_token() - cls.assertIsNotNone(cls, token) + @classmethod + def test_fetch_start_page_token(cls): + """Test fetch_start_page_token""" + token = fetch_start_page_token.fetch_start_page_token() + cls.assertIsNotNone(cls, token) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v3/drive_snippet/create_drive.py b/drive/snippets/drive-v3/drive_snippet/create_drive.py index 308c0b1e..871a495f 100644 --- a/drive/snippets/drive-v3/drive_snippet/create_drive.py +++ b/drive/snippets/drive-v3/drive_snippet/create_drive.py @@ -13,10 +13,8 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START drive_create_drive] - -from __future__ import print_function +# [START drive_create_drive] import uuid import google.auth @@ -25,35 +23,37 @@ def create_drive(): - """Create a drive. - Returns: - Id of the created drive - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # create drive api client - service = build('drive', 'v3', credentials=creds) - - drive_metadata = {'name': 'Project Resources'} - request_id = str(uuid.uuid4()) - # pylint: disable=maybe-no-member - drive = service.drives().create(body=drive_metadata, - requestId=request_id, - fields='id').execute() - print(F'Drive ID: {drive.get("id")}') - - except HttpError as error: - print(F'An error occurred: {error}') - drive = None - - return drive.get('id') - - -if __name__ == '__main__': - create_drive() + """Create a drive. + Returns: + Id of the created drive + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # create drive api client + service = build("drive", "v3", credentials=creds) + + drive_metadata = {"name": "Project Resources"} + request_id = str(uuid.uuid4()) + # pylint: disable=maybe-no-member + drive = ( + service.drives() + .create(body=drive_metadata, requestId=request_id, fields="id") + .execute() + ) + print(f'Drive ID: {drive.get("id")}') + + except HttpError as error: + print(f"An error occurred: {error}") + drive = None + + return drive.get("id") + + +if __name__ == "__main__": + create_drive() # [END drive_create_drive] diff --git a/drive/snippets/drive-v3/drive_snippet/recover_drives.py b/drive/snippets/drive-v3/drive_snippet/recover_drives.py index 45a86658..2f1159c7 100644 --- a/drive/snippets/drive-v3/drive_snippet/recover_drives.py +++ b/drive/snippets/drive-v3/drive_snippet/recover_drives.py @@ -13,69 +13,80 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START drive_recover_drives] - -from __future__ import print_function +# [START drive_recover_drives] import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def recover_drives(real_user): - """Find all shared drives without an organizer and add one. - Args: - real_user:User ID for the new organizer. - Returns: - drives object - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - try: - # create drive api client - service = build('drive', 'v3', credentials=creds) - - drives = [] - - # pylint: disable=maybe-no-member - page_token = None - new_organizer_permission = { - 'type': 'user', - 'role': 'organizer', - 'emailAddress': 'user@example.com' - } - new_organizer_permission['emailAddress'] = real_user - - while True: - response = service.drives().list( - q='organizerCount = 0', - fields='nextPageToken, drives(id, name)', - useDomainAdminAccess=True, pageToken=page_token).execute() - for drive in response.get('drives', []): - print(F'Found shared drive without organizer: ' - F'{drive.get("title")}, {drive.get("id")}') - permission = service.permissions().create( - fileId=drive.get('id'), - body=new_organizer_permission, - useDomainAdminAccess=True, - supportsAllDrives=True, - fields='id').execute() - print(F'Added organizer permission: {permission.get("id")}') - - drives.extend(response.get('drives', [])) - page_token = response.get('nextPageToken', None) - if page_token is None: - break - - except HttpError as error: - print(F'An error occurred: {error}') - - return drives - - -if __name__ == '__main__': - recover_drives(real_user='gduser1@workspacesamples.dev') + """Find all shared drives without an organizer and add one. + Args: + real_user:User ID for the new organizer. + Returns: + drives object + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + try: + # create drive api client + service = build("drive", "v3", credentials=creds) + + drives = [] + + # pylint: disable=maybe-no-member + page_token = None + new_organizer_permission = { + "type": "user", + "role": "organizer", + "emailAddress": "user@example.com", + } + new_organizer_permission["emailAddress"] = real_user + + while True: + response = ( + service.drives() + .list( + q="organizerCount = 0", + fields="nextPageToken, drives(id, name)", + useDomainAdminAccess=True, + pageToken=page_token, + ) + .execute() + ) + for drive in response.get("drives", []): + print( + "Found shared drive without organizer: " + f"{drive.get('title')}, {drive.get('id')}" + ) + permission = ( + service.permissions() + .create( + fileId=drive.get("id"), + body=new_organizer_permission, + useDomainAdminAccess=True, + supportsAllDrives=True, + fields="id", + ) + .execute() + ) + print(f'Added organizer permission: {permission.get("id")}') + + drives.extend(response.get("drives", [])) + page_token = response.get("nextPageToken", None) + if page_token is None: + break + + except HttpError as error: + print(f"An error occurred: {error}") + + return drives + + +if __name__ == "__main__": + recover_drives(real_user="gduser1@workspacesamples.dev") # [END drive_recover_drives] diff --git a/drive/snippets/drive-v3/file_snippet/create_folder.py b/drive/snippets/drive-v3/file_snippet/create_folder.py index 41240fef..b0fc814e 100644 --- a/drive/snippets/drive-v3/file_snippet/create_folder.py +++ b/drive/snippets/drive-v3/file_snippet/create_folder.py @@ -13,44 +13,41 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START drive_create_folder] - -from __future__ import print_function +# [START drive_create_folder] import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def create_folder(): - """ Create a folder and prints the folder ID - Returns : Folder Id - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # create drive api client - service = build('drive', 'v3', credentials=creds) - file_metadata = { - 'name': 'Invoices', - 'mimeType': 'application/vnd.google-apps.folder' - } - - # pylint: disable=maybe-no-member - file = service.files().create(body=file_metadata, fields='id' - ).execute() - print(F'Folder ID: "{file.get("id")}".') - return file.get('id') - - except HttpError as error: - print(F'An error occurred: {error}') - return None - - -if __name__ == '__main__': - create_folder() + """Create a folder and prints the folder ID + Returns : Folder Id + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # create drive api client + service = build("drive", "v3", credentials=creds) + file_metadata = { + "name": "Invoices", + "mimeType": "application/vnd.google-apps.folder", + } + + # pylint: disable=maybe-no-member + file = service.files().create(body=file_metadata, fields="id").execute() + print(f'Folder ID: "{file.get("id")}".') + return file.get("id") + + except HttpError as error: + print(f"An error occurred: {error}") + return None + + +if __name__ == "__main__": + create_folder() # [END drive_create_folder] diff --git a/drive/snippets/drive-v3/file_snippet/create_shortcut.py b/drive/snippets/drive-v3/file_snippet/create_shortcut.py index c43c5b20..435b7b4d 100644 --- a/drive/snippets/drive-v3/file_snippet/create_shortcut.py +++ b/drive/snippets/drive-v3/file_snippet/create_shortcut.py @@ -13,42 +13,39 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START drive_create_shortcut] - -from __future__ import print_function +# [START drive_create_shortcut] import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def create_shortcut(): - """Create a third party shortcut - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # create drive api client - service = build('drive', 'v3', credentials=creds) - file_metadata = { - 'name': 'Project plan', - 'mimeType': 'application/vnd.google-apps.drive-sdk' - } - - # pylint: disable=maybe-no-member - file = service.files().create(body=file_metadata, - fields='id').execute() - print(F'File ID: {file.get("id")}') - - except HttpError as error: - print(F'An error occurred: {error}') - return file.get('id') - - -if __name__ == '__main__': - create_shortcut() + """Create a third party shortcut + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # create drive api client + service = build("drive", "v3", credentials=creds) + file_metadata = { + "name": "Project plan", + "mimeType": "application/vnd.google-apps.drive-sdk", + } + + # pylint: disable=maybe-no-member + file = service.files().create(body=file_metadata, fields="id").execute() + print(f'File ID: {file.get("id")}') + + except HttpError as error: + print(f"An error occurred: {error}") + return file.get("id") + + +if __name__ == "__main__": + create_shortcut() # [END drive_create_shortcut] diff --git a/drive/snippets/drive-v3/file_snippet/download_file.py b/drive/snippets/drive-v3/file_snippet/download_file.py index 44d345fc..c0345524 100644 --- a/drive/snippets/drive-v3/file_snippet/download_file.py +++ b/drive/snippets/drive-v3/file_snippet/download_file.py @@ -13,10 +13,8 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START drive_download_file] - -from __future__ import print_function +# [START drive_download_file] import io import google.auth @@ -26,39 +24,39 @@ def download_file(real_file_id): - """Downloads a file - Args: - real_file_id: ID of the file to download - Returns : IO object with location. + """Downloads a file + Args: + real_file_id: ID of the file to download + Returns : IO object with location. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() - try: - # create drive api client - service = build('drive', 'v3', credentials=creds) + try: + # create drive api client + service = build("drive", "v3", credentials=creds) - file_id = real_file_id + file_id = real_file_id - # pylint: disable=maybe-no-member - request = service.files().get_media(fileId=file_id) - file = io.BytesIO() - downloader = MediaIoBaseDownload(file, request) - done = False - while done is False: - status, done = downloader.next_chunk() - print(F'Download {int(status.progress() * 100)}.') + # pylint: disable=maybe-no-member + request = service.files().get_media(fileId=file_id) + file = io.BytesIO() + downloader = MediaIoBaseDownload(file, request) + done = False + while done is False: + status, done = downloader.next_chunk() + print(f"Download {int(status.progress() * 100)}.") - except HttpError as error: - print(F'An error occurred: {error}') - file = None + except HttpError as error: + print(f"An error occurred: {error}") + file = None - return file.getvalue() + return file.getvalue() -if __name__ == '__main__': - download_file(real_file_id='1KuPmvGq8yoYgbfW74OENMCB5H0n_2Jm9') +if __name__ == "__main__": + download_file(real_file_id="1KuPmvGq8yoYgbfW74OENMCB5H0n_2Jm9") # [END drive_download_file] diff --git a/drive/snippets/drive-v3/file_snippet/export_pdf.py b/drive/snippets/drive-v3/file_snippet/export_pdf.py index 28d224a7..4588cbbf 100644 --- a/drive/snippets/drive-v3/file_snippet/export_pdf.py +++ b/drive/snippets/drive-v3/file_snippet/export_pdf.py @@ -13,10 +13,8 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START drive_export_pdf] - -from __future__ import print_function +# [START drive_export_pdf] import io import google.auth @@ -26,40 +24,41 @@ def export_pdf(real_file_id): - """Download a Document file in PDF format. - Args: - real_file_id : file ID of any workspace document format file - Returns : IO object with location - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # create drive api client - service = build('drive', 'v3', credentials=creds) - - file_id = real_file_id - - # pylint: disable=maybe-no-member - request = service.files().export_media(fileId=file_id, - mimeType='application/pdf') - file = io.BytesIO() - downloader = MediaIoBaseDownload(file, request) - done = False - while done is False: - status, done = downloader.next_chunk() - print(F'Download {int(status.progress() * 100)}.') - - except HttpError as error: - print(F'An error occurred: {error}') - file = None - - return file.getvalue() - - -if __name__ == '__main__': - export_pdf(real_file_id='1zbp8wAyuImX91Jt9mI-CAX_1TqkBLDEDcr2WeXBbKUY') + """Download a Document file in PDF format. + Args: + real_file_id : file ID of any workspace document format file + Returns : IO object with location + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # create drive api client + service = build("drive", "v3", credentials=creds) + + file_id = real_file_id + + # pylint: disable=maybe-no-member + request = service.files().export_media( + fileId=file_id, mimeType="application/pdf" + ) + file = io.BytesIO() + downloader = MediaIoBaseDownload(file, request) + done = False + while done is False: + status, done = downloader.next_chunk() + print(f"Download {int(status.progress() * 100)}.") + + except HttpError as error: + print(f"An error occurred: {error}") + file = None + + return file.getvalue() + + +if __name__ == "__main__": + export_pdf(real_file_id="1zbp8wAyuImX91Jt9mI-CAX_1TqkBLDEDcr2WeXBbKUY") # [END drive_export_pdf] diff --git a/drive/snippets/drive-v3/file_snippet/move_file_to_folder.py b/drive/snippets/drive-v3/file_snippet/move_file_to_folder.py index 06b711c1..5d3a0a28 100644 --- a/drive/snippets/drive-v3/file_snippet/move_file_to_folder.py +++ b/drive/snippets/drive-v3/file_snippet/move_file_to_folder.py @@ -14,48 +14,54 @@ """ # [START drive_move_file_to_folder] - -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def move_file_to_folder(file_id, folder_id): - """Move specified file to the specified folder. - Args: - file_id: Id of the file to move. - folder_id: Id of the folder - Print: An object containing the new parent folder and other meta data - Returns : Parent Ids for the file - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # call drive api client - service = build('drive', 'v3', credentials=creds) - - # pylint: disable=maybe-no-member - # Retrieve the existing parents to remove - file = service.files().get(fileId=file_id, fields='parents').execute() - previous_parents = ",".join(file.get('parents')) - # Move the file to the new folder - file = service.files().update(fileId=file_id, addParents=folder_id, - removeParents=previous_parents, - fields='id, parents').execute() - return file.get('parents') - - except HttpError as error: - print(F'An error occurred: {error}') - return None - - -if __name__ == '__main__': - move_file_to_folder(file_id='1KuPmvGq8yoYgbfW74OENMCB5H0n_2Jm9', - folder_id='1jvTFoyBhUspwDncOTB25kb9k0Fl0EqeN') + """Move specified file to the specified folder. + Args: + file_id: Id of the file to move. + folder_id: Id of the folder + Print: An object containing the new parent folder and other meta data + Returns : Parent Ids for the file + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # call drive api client + service = build("drive", "v3", credentials=creds) + + # pylint: disable=maybe-no-member + # Retrieve the existing parents to remove + file = service.files().get(fileId=file_id, fields="parents").execute() + previous_parents = ",".join(file.get("parents")) + # Move the file to the new folder + file = ( + service.files() + .update( + fileId=file_id, + addParents=folder_id, + removeParents=previous_parents, + fields="id, parents", + ) + .execute() + ) + return file.get("parents") + + except HttpError as error: + print(f"An error occurred: {error}") + return None + + +if __name__ == "__main__": + move_file_to_folder( + file_id="1KuPmvGq8yoYgbfW74OENMCB5H0n_2Jm9", + folder_id="1jvTFoyBhUspwDncOTB25kb9k0Fl0EqeN", + ) # [END drive_move_file_to_folder] diff --git a/drive/snippets/drive-v3/file_snippet/search_file.py b/drive/snippets/drive-v3/file_snippet/search_file.py index b2a55060..fc17b006 100644 --- a/drive/snippets/drive-v3/file_snippet/search_file.py +++ b/drive/snippets/drive-v3/file_snippet/search_file.py @@ -13,51 +13,54 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START drive_search_file] - -from __future__ import print_function +# [START drive_search_file] import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def search_file(): - """Search file in drive location - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # create drive api client - service = build('drive', 'v3', credentials=creds) - files = [] - page_token = None - while True: - # pylint: disable=maybe-no-member - response = service.files().list(q="mimeType='image/jpeg'", - spaces='drive', - fields='nextPageToken, ' - 'files(id, name)', - pageToken=page_token).execute() - for file in response.get('files', []): - # Process change - print(F'Found file: {file.get("name")}, {file.get("id")}') - files.extend(response.get('files', [])) - page_token = response.get('nextPageToken', None) - if page_token is None: - break - - except HttpError as error: - print(F'An error occurred: {error}') - files = None - - return files - - -if __name__ == '__main__': - search_file() + """Search file in drive location + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # create drive api client + service = build("drive", "v3", credentials=creds) + files = [] + page_token = None + while True: + # pylint: disable=maybe-no-member + response = ( + service.files() + .list( + q="mimeType='image/jpeg'", + spaces="drive", + fields="nextPageToken, files(id, name)", + pageToken=page_token, + ) + .execute() + ) + for file in response.get("files", []): + # Process change + print(f'Found file: {file.get("name")}, {file.get("id")}') + files.extend(response.get("files", [])) + page_token = response.get("nextPageToken", None) + if page_token is None: + break + + except HttpError as error: + print(f"An error occurred: {error}") + files = None + + return files + + +if __name__ == "__main__": + search_file() # [END drive_search_file] diff --git a/drive/snippets/drive-v3/file_snippet/share_file.py b/drive/snippets/drive-v3/file_snippet/share_file.py index 72bb1121..8850aa5e 100644 --- a/drive/snippets/drive-v3/file_snippet/share_file.py +++ b/drive/snippets/drive-v3/file_snippet/share_file.py @@ -13,77 +13,85 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START drive_share_file] - -from __future__ import print_function +# [START drive_share_file] import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def share_file(real_file_id, real_user, real_domain): - """Batch permission modification. - Args: - real_file_id: file Id - real_user: User ID - real_domain: Domain of the user ID - Prints modified permissions + """Batch permission modification. + Args: + real_file_id: file Id + real_user: User ID + real_domain: Domain of the user ID + Prints modified permissions - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() - try: - # create drive api client - service = build('drive', 'v3', credentials=creds) - ids = [] - file_id = real_file_id + try: + # create drive api client + service = build("drive", "v3", credentials=creds) + ids = [] + file_id = real_file_id - def callback(request_id, response, exception): - if exception: - # Handle error - print(exception) - else: - print(f'Request_Id: {request_id}') - print(F'Permission Id: {response.get("id")}') - ids.append(response.get('id')) + def callback(request_id, response, exception): + if exception: + # Handle error + print(exception) + else: + print(f"Request_Id: {request_id}") + print(f'Permission Id: {response.get("id")}') + ids.append(response.get("id")) - # pylint: disable=maybe-no-member - batch = service.new_batch_http_request(callback=callback) - user_permission = { - 'type': 'user', - 'role': 'writer', - 'emailAddress': 'user@example.com' - } - # [START_EXCLUDE silent] - user_permission['emailAddress'] = real_user - # [END_EXCLUDE] - batch.add(service.permissions().create(fileId=file_id, - body=user_permission, - fields='id',)) - domain_permission = { - 'type': 'domain', - 'role': 'reader', - 'domain': 'example.com' - } - domain_permission['domain'] = real_domain - batch.add(service.permissions().create(fileId=file_id, - body=domain_permission, - fields='id',)) - batch.execute() + # pylint: disable=maybe-no-member + batch = service.new_batch_http_request(callback=callback) + user_permission = { + "type": "user", + "role": "writer", + "emailAddress": "user@example.com", + } + # [START_EXCLUDE silent] + user_permission["emailAddress"] = real_user + # [END_EXCLUDE] + batch.add( + service.permissions().create( + fileId=file_id, + body=user_permission, + fields="id", + ) + ) + domain_permission = { + "type": "domain", + "role": "reader", + "domain": "example.com", + } + domain_permission["domain"] = real_domain + batch.add( + service.permissions().create( + fileId=file_id, + body=domain_permission, + fields="id", + ) + ) + batch.execute() - except HttpError as error: - print(F'An error occurred: {error}') - ids = None + except HttpError as error: + print(f"An error occurred: {error}") + ids = None - return ids + return ids -if __name__ == '__main__': - share_file(real_file_id='1dUiRSoAQKkM3a4nTPeNQWgiuau1KdQ_l', - real_user='gduser1@workspacesamples.dev', - real_domain='workspacesamples.dev') +if __name__ == "__main__": + share_file( + real_file_id="1dUiRSoAQKkM3a4nTPeNQWgiuau1KdQ_l", + real_user="gduser1@workspacesamples.dev", + real_domain="workspacesamples.dev", + ) # [END drive_share_file] diff --git a/drive/snippets/drive-v3/file_snippet/test_create_folder.py b/drive/snippets/drive-v3/file_snippet/test_create_folder.py index 1cb7bfbd..24eb83d0 100644 --- a/drive/snippets/drive-v3/file_snippet/test_create_folder.py +++ b/drive/snippets/drive-v3/file_snippet/test_create_folder.py @@ -12,20 +12,21 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest import create_folder class TestCreateFolder(unittest.TestCase): - """Unit test class for file snippet""" + """Unit test class for file snippet""" - @classmethod - def test_create_folder(cls): - """Test create_folder""" - file_id = create_folder.create_folder() - cls.assertIsNotNone(cls, file_id) + @classmethod + def test_create_folder(cls): + """Test create_folder""" + file_id = create_folder.create_folder() + cls.assertIsNotNone(cls, file_id) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v3/file_snippet/test_create_shortcut.py b/drive/snippets/drive-v3/file_snippet/test_create_shortcut.py index 2e2f3080..82789471 100644 --- a/drive/snippets/drive-v3/file_snippet/test_create_shortcut.py +++ b/drive/snippets/drive-v3/file_snippet/test_create_shortcut.py @@ -12,20 +12,21 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest import create_shortcut class TestCreateShortcut(unittest.TestCase): - """Unit test class for file snippet""" + """Unit test class for file snippet""" - @classmethod - def test_create_shortcut(cls): - """Test create_folder""" - file_id = create_shortcut.create_shortcut() - cls.assertIsNotNone(cls, file_id) + @classmethod + def test_create_shortcut(cls): + """Test create_folder""" + file_id = create_shortcut.create_shortcut() + cls.assertIsNotNone(cls, file_id) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v3/file_snippet/test_download_file.py b/drive/snippets/drive-v3/file_snippet/test_download_file.py index 724b780c..bb5455bd 100644 --- a/drive/snippets/drive-v3/file_snippet/test_download_file.py +++ b/drive/snippets/drive-v3/file_snippet/test_download_file.py @@ -12,22 +12,23 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest import download_file class TestDownloadFile(unittest.TestCase): - """Unit test class for file snippet""" + """Unit test class for file snippet""" - @classmethod - def test_download_file(cls): - """Test Download_file""" - # valid file id - real_file_id = '1KuPmvGq8yoYgbfW74OENMCB5H0n_2Jm9' - file = download_file.download_file(real_file_id=real_file_id) - cls.assertNotEqual(cls, 0, len(file)) + @classmethod + def test_download_file(cls): + """Test Download_file""" + # valid file id + real_file_id = "1KuPmvGq8yoYgbfW74OENMCB5H0n_2Jm9" + file = download_file.download_file(real_file_id=real_file_id) + cls.assertNotEqual(cls, 0, len(file)) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v3/file_snippet/test_export_pdf.py b/drive/snippets/drive-v3/file_snippet/test_export_pdf.py index cf0ecb9f..e9dfb88f 100644 --- a/drive/snippets/drive-v3/file_snippet/test_export_pdf.py +++ b/drive/snippets/drive-v3/file_snippet/test_export_pdf.py @@ -12,22 +12,23 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest import export_pdf class TestExportPdf(unittest.TestCase): - """Unit test class for file snippet""" + """Unit test class for file snippet""" - @classmethod - def test_export_pdf(cls): - """Test export_pdf""" - # valid file ID - real_file_id = '1zbp8wAyuImX91Jt9mI-CAX_1TqkBLDEDcr2WeXBbKUY' - file = export_pdf.export_pdf(real_file_id=real_file_id) - cls.assertNotEqual(cls, 0, len(file)) + @classmethod + def test_export_pdf(cls): + """Test export_pdf""" + # valid file ID + real_file_id = "1zbp8wAyuImX91Jt9mI-CAX_1TqkBLDEDcr2WeXBbKUY" + file = export_pdf.export_pdf(real_file_id=real_file_id) + cls.assertNotEqual(cls, 0, len(file)) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v3/file_snippet/test_move_file_to_folder.py b/drive/snippets/drive-v3/file_snippet/test_move_file_to_folder.py index 579bf37f..6f9b933a 100644 --- a/drive/snippets/drive-v3/file_snippet/test_move_file_to_folder.py +++ b/drive/snippets/drive-v3/file_snippet/test_move_file_to_folder.py @@ -12,24 +12,26 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest import move_file_to_folder class TestMoveFileToFolder(unittest.TestCase): - """Unit test class for file snippet""" + """Unit test class for file snippet""" - @classmethod - def test_move_file_to_folder(cls): - """Test move_file_to_folder""" - real_file_id = '1KuPmvGq8yoYgbfW74OENMCB5H0n_2Jm9' - real_folder_id = '1v5eyIbXCr9TZX3eX_44HEExfe7yRj24V' + @classmethod + def test_move_file_to_folder(cls): + """Test move_file_to_folder""" + real_file_id = "1KuPmvGq8yoYgbfW74OENMCB5H0n_2Jm9" + real_folder_id = "1v5eyIbXCr9TZX3eX_44HEExfe7yRj24V" - update = move_file_to_folder.move_file_to_folder( - real_file_id=real_file_id, real_folder_id=real_folder_id) - cls.assertIsNotNone(cls, 0, len(update)) + update = move_file_to_folder.move_file_to_folder( + real_file_id=real_file_id, real_folder_id=real_folder_id + ) + cls.assertIsNotNone(cls, 0, len(update)) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v3/file_snippet/test_search_file.py b/drive/snippets/drive-v3/file_snippet/test_search_file.py index 964d2a6b..a86d2158 100644 --- a/drive/snippets/drive-v3/file_snippet/test_search_file.py +++ b/drive/snippets/drive-v3/file_snippet/test_search_file.py @@ -12,20 +12,21 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest import search_file class TestSearchFile(unittest.TestCase): - """Unit test class for file snippet""" + """Unit test class for file snippet""" - @classmethod - def test_search_file(cls): - """Test search_file""" - file = search_file.search_file() - cls.assertNotEqual(cls, 0, len(file)) + @classmethod + def test_search_file(cls): + """Test search_file""" + file = search_file.search_file() + cls.assertNotEqual(cls, 0, len(file)) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v3/file_snippet/test_share_file.py b/drive/snippets/drive-v3/file_snippet/test_share_file.py index 85392192..9bfdd717 100644 --- a/drive/snippets/drive-v3/file_snippet/test_share_file.py +++ b/drive/snippets/drive-v3/file_snippet/test_share_file.py @@ -12,25 +12,26 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest import share_file class TestShareFile(unittest.TestCase): - """Unit test class for file snippet""" - - @classmethod - def test_share_file(cls): - """Test share_file""" - real_file_id = '1dUiRSoAQKkM3a4nTPeNQWgiuau1KdQ_l' - real_user = 'gduser1@workspacesamples.dev' - real_domain = 'workspacesamples.dev' - file = share_file.share_file(real_file_id=real_file_id, - real_user=real_user, - real_domain=real_domain) - cls.assertNotEqual(cls, 0, len(file)) - - -if __name__ == '__main__': - unittest.main() + """Unit test class for file snippet""" + + @classmethod + def test_share_file(cls): + """Test share_file""" + real_file_id = "1dUiRSoAQKkM3a4nTPeNQWgiuau1KdQ_l" + real_user = "gduser1@workspacesamples.dev" + real_domain = "workspacesamples.dev" + file = share_file.share_file( + real_file_id=real_file_id, real_user=real_user, real_domain=real_domain + ) + cls.assertNotEqual(cls, 0, len(file)) + + +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v3/file_snippet/test_touch_file.py b/drive/snippets/drive-v3/file_snippet/test_touch_file.py index cd1f68a4..f35dc08d 100644 --- a/drive/snippets/drive-v3/file_snippet/test_touch_file.py +++ b/drive/snippets/drive-v3/file_snippet/test_touch_file.py @@ -12,6 +12,7 @@ See the License for the specific language governing permissions and limitations under the License. """ + import re import unittest from datetime import datetime @@ -20,18 +21,19 @@ class TestTouchFile(unittest.TestCase): - """Unit test class for file snippet""" - - @classmethod - def test_touch_file(cls): - """Test touch_file""" - real_file_id = '1KuPmvGq8yoYgbfW74OENMCB5H0n_2Jm9' - now = datetime.utcnow().isoformat() + 'Z' - now = re.sub(r'\d{3}Z', 'Z', now) # Truncate microseconds - modified_time = touch_file.touch_file(real_file_id=real_file_id, - real_timestamp=now) - cls.assertIsNotNone(cls, modified_time) - - -if __name__ == '__main__': - unittest.main() + """Unit test class for file snippet""" + + @classmethod + def test_touch_file(cls): + """Test touch_file""" + real_file_id = "1KuPmvGq8yoYgbfW74OENMCB5H0n_2Jm9" + now = datetime.utcnow().isoformat() + "Z" + now = re.sub(r"\d{3}Z", "Z", now) # Truncate microseconds + modified_time = touch_file.touch_file( + real_file_id=real_file_id, real_timestamp=now + ) + cls.assertIsNotNone(cls, modified_time) + + +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v3/file_snippet/test_upload_basic.py b/drive/snippets/drive-v3/file_snippet/test_upload_basic.py index 3d6c473d..c0bb7c30 100644 --- a/drive/snippets/drive-v3/file_snippet/test_upload_basic.py +++ b/drive/snippets/drive-v3/file_snippet/test_upload_basic.py @@ -12,20 +12,21 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest import upload_basic class TestUploadBasic(unittest.TestCase): - """Unit test class for file snippet""" + """Unit test class for file snippet""" - @classmethod - def test_upload_basic(cls): - """Test upload_basic""" - file_id = upload_basic.upload_basic() - cls.assertIsNotNone(cls, file_id) + @classmethod + def test_upload_basic(cls): + """Test upload_basic""" + file_id = upload_basic.upload_basic() + cls.assertIsNotNone(cls, file_id) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v3/file_snippet/test_upload_revision.py b/drive/snippets/drive-v3/file_snippet/test_upload_revision.py index 88f396e5..c1ab5a6d 100644 --- a/drive/snippets/drive-v3/file_snippet/test_upload_revision.py +++ b/drive/snippets/drive-v3/file_snippet/test_upload_revision.py @@ -12,22 +12,23 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest import upload_revision class TestUploadRevision(unittest.TestCase): - """Unit test class for file snippet""" + """Unit test class for file snippet""" - @classmethod - def test_upload_revision(cls): - """Test upload_revision""" + @classmethod + def test_upload_revision(cls): + """Test upload_revision""" - real_file_id = '1KuPmvGq8yoYgbfW74OENMCB5H0n_2Jm9' - file_id = upload_revision.upload_revision(real_file_id=real_file_id) - cls.assertIsNotNone(cls, file_id) + real_file_id = "1KuPmvGq8yoYgbfW74OENMCB5H0n_2Jm9" + file_id = upload_revision.upload_revision(real_file_id=real_file_id) + cls.assertIsNotNone(cls, file_id) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v3/file_snippet/test_upload_to_folder.py b/drive/snippets/drive-v3/file_snippet/test_upload_to_folder.py index 4b129df3..776f23cd 100644 --- a/drive/snippets/drive-v3/file_snippet/test_upload_to_folder.py +++ b/drive/snippets/drive-v3/file_snippet/test_upload_to_folder.py @@ -12,22 +12,22 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest import upload_to_folder class TestUploadToFolder(unittest.TestCase): - """Unit test class for file snippet""" + """Unit test class for file snippet""" - @classmethod - def test_upload_to_folder(cls): - """Test upload_to_folder""" - real_folder_id = '1s0oKEZZXjImNngxHGnY0xed6Mw-tvspu' - file_id = upload_to_folder.upload_to_folder( - real_folder_id=real_folder_id) - cls.assertIsNotNone(cls, file_id) + @classmethod + def test_upload_to_folder(cls): + """Test upload_to_folder""" + real_folder_id = "1s0oKEZZXjImNngxHGnY0xed6Mw-tvspu" + file_id = upload_to_folder.upload_to_folder(real_folder_id=real_folder_id) + cls.assertIsNotNone(cls, file_id) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v3/file_snippet/test_upload_with_conversion.py b/drive/snippets/drive-v3/file_snippet/test_upload_with_conversion.py index 563f5c70..ce3bd168 100644 --- a/drive/snippets/drive-v3/file_snippet/test_upload_with_conversion.py +++ b/drive/snippets/drive-v3/file_snippet/test_upload_with_conversion.py @@ -12,20 +12,21 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest import upload_with_conversion class TestUploadWithConversion(unittest.TestCase): - """Unit test class for file snippet""" + """Unit test class for file snippet""" - @classmethod - def test_upload_to_folder(cls): - """Test upload_with_conversion""" - file_id = upload_with_conversion.upload_with_conversion() - cls.assertIsNotNone(cls, file_id) + @classmethod + def test_upload_to_folder(cls): + """Test upload_with_conversion""" + file_id = upload_with_conversion.upload_with_conversion() + cls.assertIsNotNone(cls, file_id) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/drive/snippets/drive-v3/file_snippet/touch_file.py b/drive/snippets/drive-v3/file_snippet/touch_file.py index 17478b92..c27ec382 100644 --- a/drive/snippets/drive-v3/file_snippet/touch_file.py +++ b/drive/snippets/drive-v3/file_snippet/touch_file.py @@ -13,10 +13,8 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START drive_touch_file] - -from __future__ import print_function +# [START drive_touch_file] from datetime import datetime import google.auth @@ -25,40 +23,43 @@ def touch_file(real_file_id, real_timestamp): - """Change the file's modification timestamp. - Args: - real_file_id: ID of the file to change modified time - real_timestamp: Timestamp to override Modified date time of the file - Returns : Modified Date and time. + """Change the file's modification timestamp. + Args: + real_file_id: ID of the file to change modified time + real_timestamp: Timestamp to override Modified date time of the file + Returns : Modified Date and time. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() - try: - # create drive api client - service = build('drive', 'v3', credentials=creds) + try: + # create drive api client + service = build("drive", "v3", credentials=creds) - file_metadata = { - 'modifiedTime': datetime.utcnow().isoformat() + 'Z' - } - # pylint: disable=maybe-no-member - file_id = real_file_id - file_metadata['modifiedTime'] = real_timestamp - file = service.files().update(fileId=file_id, body=file_metadata, - fields='id, modifiedTime').execute() - print(F'Modified time: {file.get("modifiedTime")}') + file_metadata = {"modifiedTime": datetime.utcnow().isoformat() + "Z"} + # pylint: disable=maybe-no-member + file_id = real_file_id + file_metadata["modifiedTime"] = real_timestamp + file = ( + service.files() + .update(fileId=file_id, body=file_metadata, fields="id, modifiedTime") + .execute() + ) + print(f'Modified time: {file.get("modifiedTime")}') - except HttpError as error: - print(F'An error occurred: {error}') - file = None + except HttpError as error: + print(f"An error occurred: {error}") + file = None - return file.get('modifiedDate') + return file.get("modifiedDate") -if __name__ == '__main__': - touch_file(real_file_id='17EqlSf7FpPU95SS00sICyVzQHpeET1cz', - real_timestamp='2022-03-02T05:43:27.504Z') +if __name__ == "__main__": + touch_file( + real_file_id="17EqlSf7FpPU95SS00sICyVzQHpeET1cz", + real_timestamp="2022-03-02T05:43:27.504Z", + ) # [END drive_touch_file] diff --git a/drive/snippets/drive-v3/file_snippet/upload_basic.py b/drive/snippets/drive-v3/file_snippet/upload_basic.py index 1cecb3f9..1795c4d8 100644 --- a/drive/snippets/drive-v3/file_snippet/upload_basic.py +++ b/drive/snippets/drive-v3/file_snippet/upload_basic.py @@ -13,10 +13,8 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START drive_upload_basic] - -from __future__ import print_function +# [START drive_upload_basic] import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError @@ -24,34 +22,36 @@ def upload_basic(): - """Insert new file. - Returns : Id's of the file uploaded - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # create drive api client - service = build('drive', 'v3', credentials=creds) - - file_metadata = {'name': 'download.jpeg'} - media = MediaFileUpload('download.jpeg', - mimetype='image/jpeg') - # pylint: disable=maybe-no-member - file = service.files().create(body=file_metadata, media_body=media, - fields='id').execute() - print(F'File ID: {file.get("id")}') - - except HttpError as error: - print(F'An error occurred: {error}') - file = None - - return file.get('id') - - -if __name__ == '__main__': - upload_basic() + """Insert new file. + Returns : Id's of the file uploaded + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # create drive api client + service = build("drive", "v3", credentials=creds) + + file_metadata = {"name": "download.jpeg"} + media = MediaFileUpload("download.jpeg", mimetype="image/jpeg") + # pylint: disable=maybe-no-member + file = ( + service.files() + .create(body=file_metadata, media_body=media, fields="id") + .execute() + ) + print(f'File ID: {file.get("id")}') + + except HttpError as error: + print(f"An error occurred: {error}") + file = None + + return file.get("id") + + +if __name__ == "__main__": + upload_basic() # [END drive_upload_basic] diff --git a/drive/snippets/drive-v3/file_snippet/upload_revision.py b/drive/snippets/drive-v3/file_snippet/upload_revision.py index 69d88d84..2fd6f3ff 100644 --- a/drive/snippets/drive-v3/file_snippet/upload_revision.py +++ b/drive/snippets/drive-v3/file_snippet/upload_revision.py @@ -13,10 +13,8 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START drive_upload_revision] - -from __future__ import print_function +# [START drive_upload_revision] import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError @@ -24,36 +22,37 @@ def upload_revision(real_file_id): - """Replace the old file with new one on same file ID - Args: ID of the file to be replaced - Returns: file ID - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # create drive api client - service = build('drive', 'v3', credentials=creds) - file_id = real_file_id - media = MediaFileUpload('download.jpeg', - mimetype='image/jpeg', - resumable=True) - # pylint: disable=maybe-no-member - file = service.files().update(fileId=file_id, - body={}, - media_body=media, - fields='id').execute() - print(F'File ID: {file.get("id")}') - - except HttpError as error: - print(F'An error occurred: {error}') - - return file.get('id') - - -if __name__ == '__main__': - upload_revision(real_file_id='1jJTiihczk_xSNPVLwMySQBJACXYdpGTi') + """Replace the old file with new one on same file ID + Args: ID of the file to be replaced + Returns: file ID + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # create drive api client + service = build("drive", "v3", credentials=creds) + file_id = real_file_id + media = MediaFileUpload( + "download.jpeg", mimetype="image/jpeg", resumable=True + ) + # pylint: disable=maybe-no-member + file = ( + service.files() + .update(fileId=file_id, body={}, media_body=media, fields="id") + .execute() + ) + print(f'File ID: {file.get("id")}') + + except HttpError as error: + print(f"An error occurred: {error}") + + return file.get("id") + + +if __name__ == "__main__": + upload_revision(real_file_id="1jJTiihczk_xSNPVLwMySQBJACXYdpGTi") # [END drive_upload_revision] diff --git a/drive/snippets/drive-v3/file_snippet/upload_to_folder.py b/drive/snippets/drive-v3/file_snippet/upload_to_folder.py index b76470ce..13441920 100644 --- a/drive/snippets/drive-v3/file_snippet/upload_to_folder.py +++ b/drive/snippets/drive-v3/file_snippet/upload_to_folder.py @@ -13,10 +13,8 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START drive_upload_to_folder] - -from __future__ import print_function +# [START drive_upload_to_folder] import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError @@ -24,37 +22,38 @@ def upload_to_folder(folder_id): - """Upload a file to the specified folder and prints file ID, folder ID - Args: Id of the folder - Returns: ID of the file uploaded - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # create drive api client - service = build('drive', 'v3', credentials=creds) - - file_metadata = { - 'name': 'photo.jpg', - 'parents': [folder_id] - } - media = MediaFileUpload('download.jpeg', - mimetype='image/jpeg', resumable=True) - # pylint: disable=maybe-no-member - file = service.files().create(body=file_metadata, media_body=media, - fields='id').execute() - print(F'File ID: "{file.get("id")}".') - return file.get('id') - - except HttpError as error: - print(F'An error occurred: {error}') - return None - - -if __name__ == '__main__': - upload_to_folder(folder_id='1s0oKEZZXjImNngxHGnY0xed6Mw-tvspu') + """Upload a file to the specified folder and prints file ID, folder ID + Args: Id of the folder + Returns: ID of the file uploaded + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # create drive api client + service = build("drive", "v3", credentials=creds) + + file_metadata = {"name": "photo.jpg", "parents": [folder_id]} + media = MediaFileUpload( + "download.jpeg", mimetype="image/jpeg", resumable=True + ) + # pylint: disable=maybe-no-member + file = ( + service.files() + .create(body=file_metadata, media_body=media, fields="id") + .execute() + ) + print(f'File ID: "{file.get("id")}".') + return file.get("id") + + except HttpError as error: + print(f"An error occurred: {error}") + return None + + +if __name__ == "__main__": + upload_to_folder(folder_id="1s0oKEZZXjImNngxHGnY0xed6Mw-tvspu") # [END drive_upload_to_folder] diff --git a/drive/snippets/drive-v3/file_snippet/upload_with_conversion.py b/drive/snippets/drive-v3/file_snippet/upload_with_conversion.py index 8c40a5aa..cff3c070 100644 --- a/drive/snippets/drive-v3/file_snippet/upload_with_conversion.py +++ b/drive/snippets/drive-v3/file_snippet/upload_with_conversion.py @@ -13,10 +13,8 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START drive_upload_with_conversion] - -from __future__ import print_function +# [START drive_upload_with_conversion] import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError @@ -24,37 +22,39 @@ def upload_with_conversion(): - """Upload file with conversion - Returns: ID of the file uploaded - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # create drive api client - service = build('drive', 'v3', credentials=creds) - - file_metadata = { - 'name': 'My Report', - 'mimeType': 'application/vnd.google-apps.spreadsheet' - } - media = MediaFileUpload('report.csv', mimetype='text/csv', - resumable=True) - # pylint: disable=maybe-no-member - file = service.files().create(body=file_metadata, media_body=media, - fields='id').execute() - print(F'File with ID: "{file.get("id")}" has been uploaded.') - - except HttpError as error: - print(F'An error occurred: {error}') - file = None - - return file.get('id') - - -if __name__ == '__main__': - upload_with_conversion() + """Upload file with conversion + Returns: ID of the file uploaded + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # create drive api client + service = build("drive", "v3", credentials=creds) + + file_metadata = { + "name": "My Report", + "mimeType": "application/vnd.google-apps.spreadsheet", + } + media = MediaFileUpload("report.csv", mimetype="text/csv", resumable=True) + # pylint: disable=maybe-no-member + file = ( + service.files() + .create(body=file_metadata, media_body=media, fields="id") + .execute() + ) + print(f'File with ID: "{file.get("id")}" has been uploaded.') + + except HttpError as error: + print(f"An error occurred: {error}") + file = None + + return file.get("id") + + +if __name__ == "__main__": + upload_with_conversion() # [END drive_upload_with_conversion] diff --git a/drive/snippets/drive-v3/team_drive_snippets/create_team_drive.py b/drive/snippets/drive-v3/team_drive_snippets/create_team_drive.py index f39bfd6d..cca27ce2 100644 --- a/drive/snippets/drive-v3/team_drive_snippets/create_team_drive.py +++ b/drive/snippets/drive-v3/team_drive_snippets/create_team_drive.py @@ -14,9 +14,6 @@ """ # [START drive_create_team_drive] - -from __future__ import print_function - import uuid import google.auth @@ -25,34 +22,36 @@ def create_team_drive(): - """ Create a drive for team. - Returns: ID of the created drive - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # call drive api client - service = build('drive', 'v3', credentials=creds) - - # pylint: disable=maybe-no-member - team_drive_metadata = {'name': 'Project Resources'} - request_id = str(uuid.uuid4()) - team_drive = service.teamdrives().create(body=team_drive_metadata, - requestId=request_id, - fields='id').execute() - print(F'Team Drive ID: {team_drive.get("id")}') - - except HttpError as error: - print(F'An error occurred: {error}') - team_drive = None - - return team_drive.get('id') - - -if __name__ == '__main__': - create_team_drive() + """Create a drive for team. + Returns: ID of the created drive + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # call drive api client + service = build("drive", "v3", credentials=creds) + + # pylint: disable=maybe-no-member + team_drive_metadata = {"name": "Project Resources"} + request_id = str(uuid.uuid4()) + team_drive = ( + service.teamdrives() + .create(body=team_drive_metadata, requestId=request_id, fields="id") + .execute() + ) + print(f'Team Drive ID: {team_drive.get("id")}') + + except HttpError as error: + print(f"An error occurred: {error}") + team_drive = None + + return team_drive.get("id") + + +if __name__ == "__main__": + create_team_drive() # [END drive_create_team_drive] diff --git a/drive/snippets/drive-v3/team_drive_snippets/recover_team_drives.py b/drive/snippets/drive-v3/team_drive_snippets/recover_team_drives.py index 7c28df56..3a082cbf 100644 --- a/drive/snippets/drive-v3/team_drive_snippets/recover_team_drives.py +++ b/drive/snippets/drive-v3/team_drive_snippets/recover_team_drives.py @@ -14,71 +14,82 @@ """ # [START drive_recover_team_drives] - -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def recover_team_drives(real_user): - """Finds all Team Drives without an organizer and add one - Args: - real_user:User ID for the new organizer. - Returns: - team drives_object. - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # call drive api client - service = build('drive', 'v3', credentials=creds) - - # pylint: disable=maybe-no-member - team_drives = [] - - page_token = None - new_organizer_permission = {'type': 'user', - 'role': 'organizer', - 'value': 'user@example.com'} - - new_organizer_permission['emailAddress'] = real_user - - while True: - response = service.teamdrives().list(q='organizerCount = 0', - fields='nextPageToken, ' - 'teamDrives(id, ' - 'name)', - useDomainAdminAccess=True, - pageToken=page_token - ).execute() - - for team_drive in response.get('teamDrives', []): - print('Found Team Drive without organizer: {team_drive.get(' - '"title")},{team_drive.get("id")}') - permission = service.permissions().create( - fileId=team_drive.get('id'), - body=new_organizer_permission, useDomainAdminAccess=True, - supportsTeamDrives=True, fields='id').execute() - print(F'Added organizer permission:{permission.get("id")}') - - team_drives.extend(response.get('teamDrives', [])) - page_token = response.get('nextPageToken', None) - if page_token is None: - break - - except HttpError as error: - print(F'An error occurred: {error}') - team_drives = None - - print(team_drives) - - -if __name__ == '__main__': - recover_team_drives(real_user='gduser1@workspacesamples.dev') + """Finds all Team Drives without an organizer and add one + Args: + real_user:User ID for the new organizer. + Returns: + team drives_object. + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # call drive api client + service = build("drive", "v3", credentials=creds) + + # pylint: disable=maybe-no-member + team_drives = [] + + page_token = None + new_organizer_permission = { + "type": "user", + "role": "organizer", + "value": "user@example.com", + } + + new_organizer_permission["emailAddress"] = real_user + + while True: + response = ( + service.teamdrives() + .list( + q="organizerCount = 0", + fields="nextPageToken, teamDrives(id, name)", + useDomainAdminAccess=True, + pageToken=page_token, + ) + .execute() + ) + + for team_drive in response.get("teamDrives", []): + print( + "Found Team Drive without organizer: {team_drive.get(" + '"title")},{team_drive.get("id")}' + ) + permission = ( + service.permissions() + .create( + fileId=team_drive.get("id"), + body=new_organizer_permission, + useDomainAdminAccess=True, + supportsTeamDrives=True, + fields="id", + ) + .execute() + ) + print(f'Added organizer permission:{permission.get("id")}') + + team_drives.extend(response.get("teamDrives", [])) + page_token = response.get("nextPageToken", None) + if page_token is None: + break + + except HttpError as error: + print(f"An error occurred: {error}") + team_drives = None + + print(team_drives) + + +if __name__ == "__main__": + recover_team_drives(real_user="gduser1@workspacesamples.dev") # [END drive_recover_team_drives] diff --git a/events/next18/customer_data_service.py b/events/next18/customer_data_service.py index d7e2e143..84766454 100644 --- a/events/next18/customer_data_service.py +++ b/events/next18/customer_data_service.py @@ -22,106 +22,110 @@ class CustomerDataService(object): - _CUSTOMER_DATA = { - 'mars': { - 'customer_name': 'Mars Inc.', - 'customer_logo': - 'https://upload.wikimedia.org/wikipedia/commons/thumb/0/02/' + - 'OSIRIS_Mars_true_color.jpg/550px-OSIRIS_Mars_true_color.jpg', - 'curr_q': 'Q2', - 'curr_q_total_sales': '$2,532,124', - 'curr_q_qoq': '0.054', - 'prev_q': 'Q1', - 'prev_q_total_sales': '$2,413,584', - 'next_q': 'Q3', - 'next_q_total_sales_proj': '$2,634,765', - 'next_q_qoq_proj': '0.041', - 'top1_sku': 'Phobos', - 'top1_sales': '$334,384', - 'top2_sku': 'Deimos', - 'top2_sales': '$315,718', - 'top3_sku': 'Charon', - 'top3_sales': '$285,727', - 'top4_sku': 'Nix', - 'top4_sales': '$264,023', - 'top5_sku': 'Hydra', - 'top5_sales': '$212,361', - }, - 'jupiter': { - 'customer_name': 'Jupiter LLC', - 'customer_logo': - 'https://upload.wikimedia.org/wikipedia/commons/thumb/2/2b/' + - 'Jupiter_and_its_shrunken_Great_Red_Spot.jpg/660px-Jupiter_' + - 'and_its_shrunken_Great_Red_Spot.jpg', - 'curr_q': 'Q2', - 'curr_q_total_sales': '$1,532,124', - 'curr_q_qoq': '0.031', - 'prev_q': 'Q1', - 'prev_q_total_sales': '$1,413,584', - 'next_q': 'Q3', - 'next_q_total_sales_proj': '$1,634,765', - 'next_q_qoq_proj': '0.021', - 'top1_sku': 'Io', - 'top1_sales': '$234,384', - 'top2_sku': 'Europa', - 'top2_sales': '$215,718', - 'top3_sku': 'Ganymede', - 'top3_sales': '$185,727', - 'top4_sku': 'Callisto', - 'top4_sales': '$164,023', - 'top5_sku': 'Amalthea', - 'top5_sales': '$112,361', - }, - 'saturn': { - 'customer_name': 'Saturn', - 'customer_logo': - 'https://upload.wikimedia.org/wikipedia/commons/thumb/c/c7/' + - 'Saturn_during_Equinox.jpg/800px-Saturn_during_Equinox.jpg', - 'curr_q': 'Q2', - 'curr_q_total_sales': '$2,532,124', - 'curr_q_qoq': '0.032', - 'prev_q': 'Q1', - 'prev_q_total_sales': '$2,413,584', - 'next_q': 'Q3', - 'next_q_total_sales_proj': '$2,634,765', - 'next_q_qoq_proj': '0.029', - 'top1_sku': 'Mimas', - 'top1_sales': '$334,384', - 'top2_sku': 'Enceladus', - 'top2_sales': '$315,718', - 'top3_sku': 'Tethys', - 'top3_sales': '$285,727', - 'top4_sku': 'Dione', - 'top4_sales': '$264,023', - 'top5_sku': 'Rhea', - 'top5_sales': '$212,361', - }, - 'neptune': { - 'customer_name': 'Neptune', - 'customer_logo': - 'https://upload.wikimedia.org/wikipedia/commons/thumb/5/56/' + - 'Neptune_Full.jpg/600px-Neptune_Full.jpg', - 'curr_q': 'Q2', - 'curr_q_total_sales': '$2,532,124', - 'curr_q_qoq': '0.027', - 'prev_q': 'Q1', - 'prev_q_total_sales': '$2,413,584', - 'next_q': 'Q3', - 'next_q_total_sales_proj': '$2,634,765', - 'next_q_qoq_proj': '0.039', - 'top1_sku': 'Triton', - 'top1_sales': '$334,384', - 'top2_sku': 'Nereid', - 'top2_sales': '$315,718', - 'top3_sku': 'Naiad', - 'top3_sales': '$285,727', - 'top4_sku': 'Thalassa', - 'top4_sales': '$264,023', - 'top5_sku': 'Despina', - 'top5_sales': '$212,361', - }, - } + _CUSTOMER_DATA = { + "mars": { + "customer_name": "Mars Inc.", + "customer_logo": ( + "https://upload.wikimedia.org/wikipedia/commons/thumb/0/02/" + + "OSIRIS_Mars_true_color.jpg/550px-OSIRIS_Mars_true_color.jpg" + ), + "curr_q": "Q2", + "curr_q_total_sales": "$2,532,124", + "curr_q_qoq": "0.054", + "prev_q": "Q1", + "prev_q_total_sales": "$2,413,584", + "next_q": "Q3", + "next_q_total_sales_proj": "$2,634,765", + "next_q_qoq_proj": "0.041", + "top1_sku": "Phobos", + "top1_sales": "$334,384", + "top2_sku": "Deimos", + "top2_sales": "$315,718", + "top3_sku": "Charon", + "top3_sales": "$285,727", + "top4_sku": "Nix", + "top4_sales": "$264,023", + "top5_sku": "Hydra", + "top5_sales": "$212,361", + }, + "jupiter": { + "customer_name": "Jupiter LLC", + "customer_logo": ( + "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2b/" + + "Jupiter_and_its_shrunken_Great_Red_Spot.jpg/660px-Jupiter_" + + "and_its_shrunken_Great_Red_Spot.jpg" + ), + "curr_q": "Q2", + "curr_q_total_sales": "$1,532,124", + "curr_q_qoq": "0.031", + "prev_q": "Q1", + "prev_q_total_sales": "$1,413,584", + "next_q": "Q3", + "next_q_total_sales_proj": "$1,634,765", + "next_q_qoq_proj": "0.021", + "top1_sku": "Io", + "top1_sales": "$234,384", + "top2_sku": "Europa", + "top2_sales": "$215,718", + "top3_sku": "Ganymede", + "top3_sales": "$185,727", + "top4_sku": "Callisto", + "top4_sales": "$164,023", + "top5_sku": "Amalthea", + "top5_sales": "$112,361", + }, + "saturn": { + "customer_name": "Saturn", + "customer_logo": ( + "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c7/" + + "Saturn_during_Equinox.jpg/800px-Saturn_during_Equinox.jpg" + ), + "curr_q": "Q2", + "curr_q_total_sales": "$2,532,124", + "curr_q_qoq": "0.032", + "prev_q": "Q1", + "prev_q_total_sales": "$2,413,584", + "next_q": "Q3", + "next_q_total_sales_proj": "$2,634,765", + "next_q_qoq_proj": "0.029", + "top1_sku": "Mimas", + "top1_sales": "$334,384", + "top2_sku": "Enceladus", + "top2_sales": "$315,718", + "top3_sku": "Tethys", + "top3_sales": "$285,727", + "top4_sku": "Dione", + "top4_sales": "$264,023", + "top5_sku": "Rhea", + "top5_sales": "$212,361", + }, + "neptune": { + "customer_name": "Neptune", + "customer_logo": ( + "https://upload.wikimedia.org/wikipedia/commons/thumb/5/56/" + + "Neptune_Full.jpg/600px-Neptune_Full.jpg" + ), + "curr_q": "Q2", + "curr_q_total_sales": "$2,532,124", + "curr_q_qoq": "0.027", + "prev_q": "Q1", + "prev_q_total_sales": "$2,413,584", + "next_q": "Q3", + "next_q_total_sales_proj": "$2,634,765", + "next_q_qoq_proj": "0.039", + "top1_sku": "Triton", + "top1_sales": "$334,384", + "top2_sku": "Nereid", + "top2_sales": "$315,718", + "top3_sku": "Naiad", + "top3_sales": "$285,727", + "top4_sku": "Thalassa", + "top4_sales": "$264,023", + "top5_sku": "Despina", + "top5_sales": "$212,361", + }, + } - def GetCustomerData(self, customer_id, properties): - customer_data = self._CUSTOMER_DATA[customer_id] - return [customer_data[p.lower()] for p in properties] + def GetCustomerData(self, customer_id, properties): + customer_data = self._CUSTOMER_DATA[customer_id] + return [customer_data[p.lower()] for p in properties] diff --git a/events/next18/customer_spreadsheet_reader.py b/events/next18/customer_spreadsheet_reader.py index e0c6167d..28008c89 100644 --- a/events/next18/customer_spreadsheet_reader.py +++ b/events/next18/customer_spreadsheet_reader.py @@ -21,54 +21,62 @@ class CustomerSpreadsheetReader(object): - def __init__(self, sheets_service, spreadsheet_id): - self._sheets_service = sheets_service - self._spreadsheet_id = spreadsheet_id - self._data_filters = collections.OrderedDict() + def __init__(self, sheets_service, spreadsheet_id): + self._sheets_service = sheets_service + self._spreadsheet_id = spreadsheet_id + self._data_filters = collections.OrderedDict() - def ReadColumnData(self, column_id): - data_filter = { - 'developerMetadataLookup': { - 'metadataKey': 'column_id', - 'metadataValue': column_id, - } + def ReadColumnData(self, column_id): + data_filter = { + "developerMetadataLookup": { + "metadataKey": "column_id", + "metadataValue": column_id, } - self._data_filters[column_id] = data_filter + } + self._data_filters[column_id] = data_filter - def ExecuteRead(self): - filters = list(self._data_filters.values()) - get_body = {'dataFilters': filters} - read_fields = ','.join([ - 'sheets.properties.sheetId', - 'sheets.data.rowData.values.formattedValue', - 'developerMetadata.metadataValue']) - spreadsheet = self._sheets_service.spreadsheets().getByDataFilter( - spreadsheetId=self._spreadsheet_id, body=get_body, - fields=read_fields).execute() - customer_spreadsheet = CustomerSpreadsheet( - spreadsheet, self._data_filters) - self._data_filters = collections.OrderedDict() - return customer_spreadsheet + def ExecuteRead(self): + filters = list(self._data_filters.values()) + get_body = {"dataFilters": filters} + read_fields = ",".join([ + "sheets.properties.sheetId", + "sheets.data.rowData.values.formattedValue", + "developerMetadata.metadataValue", + ]) + spreadsheet = ( + self._sheets_service.spreadsheets() + .getByDataFilter( + spreadsheetId=self._spreadsheet_id, + body=get_body, + fields=read_fields, + ) + .execute() + ) + customer_spreadsheet = CustomerSpreadsheet(spreadsheet, self._data_filters) + self._data_filters = collections.OrderedDict() + return customer_spreadsheet class CustomerSpreadsheet(object): - def __init__(self, spreadsheet, data_filters): - self._spreadsheet = spreadsheet - self._data_filters = data_filters + def __init__(self, spreadsheet, data_filters): + self._spreadsheet = spreadsheet + self._data_filters = data_filters - def GetSheetId(self): - sheet = self._spreadsheet.get('sheets')[0] - return sheet.get('properties').get('sheetId') + def GetSheetId(self): + sheet = self._spreadsheet.get("sheets")[0] + return sheet.get("properties").get("sheetId") - def GetTemplateId(self): - metadata = self._spreadsheet.get('developerMetadata')[0] - return metadata.get('metadataValue') + def GetTemplateId(self): + metadata = self._spreadsheet.get("developerMetadata")[0] + return metadata.get("metadataValue") - def GetColumnData(self, column_id): - index = list(self._data_filters.keys()).index(column_id) - data = self._spreadsheet.get('sheets')[0].get('data')[index] - values = [row.get('values')[0].get('formattedValue') - for row in data.get('rowData')] - # Remove the first value which is just the label - return values[1:] + def GetColumnData(self, column_id): + index = list(self._data_filters.keys()).index(column_id) + data = self._spreadsheet.get("sheets")[0].get("data")[index] + values = [ + row.get("values")[0].get("formattedValue") + for row in data.get("rowData") + ] + # Remove the first value which is just the label + return values[1:] diff --git a/events/next18/presentation_reader.py b/events/next18/presentation_reader.py index edc82861..4b023b50 100644 --- a/events/next18/presentation_reader.py +++ b/events/next18/presentation_reader.py @@ -24,54 +24,55 @@ class PresentationReader(object): - def __init__(self, slides_service, presentation_id): - self._slides_service = slides_service - self._presentation_id = presentation_id - self._presentation = None + def __init__(self, slides_service, presentation_id): + self._slides_service = slides_service + self._presentation_id = presentation_id + self._presentation = None - def _InitPresentation(self): - if not self._presentation: - self._presentation = self._slides_service.presentations().get( - presentationId=self._presentation_id).execute() + def _InitPresentation(self): + if not self._presentation: + self._presentation = ( + self._slides_service.presentations() + .get(presentationId=self._presentation_id) + .execute() + ) - def GetTitle(self): - self._InitPresentation() - return self._presentation.get('title') + def GetTitle(self): + self._InitPresentation() + return self._presentation.get("title") - def GetAllPlaceholders(self): - self._InitPresentation() - slides = self._presentation.get('slides') - placeholders = [] - for slide in slides: - elements = slide.get('pageElements') - for element in elements: - shape = element.get('shape') - table = element.get('table') - # Skip page elements that aren't shapes or tables since they're - # the only types that support text. - if not shape and not table: - continue - if shape: - placeholders += self._GetPlaceholdersFromText( - shape.get('text')) - elif table: - rows = table.get('tableRows') - for row in rows: - cells = row.get('tableCells') - for cell in cells: - placeholders += self._GetPlaceholdersFromText( - cell.get('text')) - # Return the unique placeholders - seen = set() - return [p for p in placeholders if not (p in seen or seen.add(p))] + def GetAllPlaceholders(self): + self._InitPresentation() + slides = self._presentation.get("slides") + placeholders = [] + for slide in slides: + elements = slide.get("pageElements") + for element in elements: + shape = element.get("shape") + table = element.get("table") + # Skip page elements that aren't shapes or tables since they're + # the only types that support text. + if not shape and not table: + continue + if shape: + placeholders += self._GetPlaceholdersFromText(shape.get("text")) + elif table: + rows = table.get("tableRows") + for row in rows: + cells = row.get("tableCells") + for cell in cells: + placeholders += self._GetPlaceholdersFromText(cell.get("text")) + # Return the unique placeholders + seen = set() + return [p for p in placeholders if not (p in seen or seen.add(p))] - def _GetPlaceholdersFromText(self, text): - if not text: - return [] - placeholders = [] - elements = text.get('textElements') - for element in elements: - if element.get('textRun'): - content = element.get('textRun').get('content') - placeholders += re.findall('{.*?}', content) - return placeholders + def _GetPlaceholdersFromText(self, text): + if not text: + return [] + placeholders = [] + elements = text.get("textElements") + for element in elements: + if element.get("textRun"): + content = element.get("textRun").get("content") + placeholders += re.findall("{.*?}", content) + return placeholders diff --git a/events/next18/presentation_writer.py b/events/next18/presentation_writer.py index 16cfb568..7436ec89 100644 --- a/events/next18/presentation_writer.py +++ b/events/next18/presentation_writer.py @@ -14,47 +14,41 @@ # pylint: disable=E1102 # python3 -"""Functionality for writing to a presentation. -""" +"""Functionality for writing to a presentation.""" class PresentationWriter(object): - """Queues writes for modifying a presentation. - - Call ExecuteBatchUpdate to flush pending writes. - """ - - def __init__(self, slides_service, presentation_id): - self._slides_service = slides_service - self._presentation_id = presentation_id - self._requests = [] - - def ReplaceAllText(self, find_text, replace_text): - request = { - 'replaceAllText': { - 'replaceText': replace_text, - 'containsText': { - 'text': find_text, - 'matchCase': True - } - } + """Queues writes for modifying a presentation. + + Call ExecuteBatchUpdate to flush pending writes. + """ + + def __init__(self, slides_service, presentation_id): + self._slides_service = slides_service + self._presentation_id = presentation_id + self._requests = [] + + def ReplaceAllText(self, find_text, replace_text): + request = { + "replaceAllText": { + "replaceText": replace_text, + "containsText": {"text": find_text, "matchCase": True}, } - self._requests.append(request) - - def ReplaceAllShapesWithImage(self, find_text, image_url): - request = { - 'replaceAllShapesWithImage': { - 'imageUrl': image_url, - 'containsText': { - 'text': find_text, - 'matchCase': True - } - } + } + self._requests.append(request) + + def ReplaceAllShapesWithImage(self, find_text, image_url): + request = { + "replaceAllShapesWithImage": { + "imageUrl": image_url, + "containsText": {"text": find_text, "matchCase": True}, } - self._requests.append(request) - - def ExecuteBatchUpdate(self): - body = {'requests': self._requests} - self._requests = [] - self._slides_service.presentations().batchUpdate( - presentationId=self._presentation_id, body=body).execute() + } + self._requests.append(request) + + def ExecuteBatchUpdate(self): + body = {"requests": self._requests} + self._requests = [] + self._slides_service.presentations().batchUpdate( + presentationId=self._presentation_id, body=body + ).execute() diff --git a/events/next18/qbr_tool.py b/events/next18/qbr_tool.py index cf1e49e8..15a06fa3 100644 --- a/events/next18/qbr_tool.py +++ b/events/next18/qbr_tool.py @@ -20,8 +20,6 @@ pushes the data to Google Slides """ -from __future__ import print_function - import argparse import re @@ -36,149 +34,163 @@ from oauth2client import file as oauth_file from oauth2client import tools -SCOPES = ['https://www.googleapis.com/auth/drive'] -store = oauth_file.Storage('token.json') +SCOPES = ["https://www.googleapis.com/auth/drive"] +store = oauth_file.Storage("token.json") creds = store.get() if not creds or creds.invalid: - flow = client.flow_from_clientsecrets('credentials.json', SCOPES) - creds = tools.run_flow(flow, store) + flow = client.flow_from_clientsecrets("credentials.json", SCOPES) + creds = tools.run_flow(flow, store) -slides_service = build('slides', 'v1', http=creds.authorize(Http())) -sheets_service = build('sheets', 'v4', http=creds.authorize(Http())) -drive_service = build('drive', 'v3', http=creds.authorize(Http())) +slides_service = build("slides", "v1", http=creds.authorize(Http())) +sheets_service = build("sheets", "v4", http=creds.authorize(Http())) +drive_service = build("drive", "v3", http=creds.authorize(Http())) def main(): - parser = argparse.ArgumentParser() - parser.add_argument( - 'command', - help='The command to run', - choices=['create_sheet', 'create_presentations', 'add_customers']) - parser.add_argument('--spreadsheet_id', help='The spreadsheet to use') - parser.add_argument( - '--template_id', help='The presentation to use as a template') - parser.add_argument( - '--customer_ids', nargs='+', help='The customers to use') - args = parser.parse_args() - - if args.command == 'create_sheet': - create_sheet(args.template_id) - elif args.command == 'create_presentations': - create_presentations(args.spreadsheet_id, args.customer_ids) - elif args.command == 'add_customers': - add_customers(args.spreadsheet_id, args.customer_ids) + parser = argparse.ArgumentParser() + parser.add_argument( + "command", + help="The command to run", + choices=["create_sheet", "create_presentations", "add_customers"], + ) + parser.add_argument("--spreadsheet_id", help="The spreadsheet to use") + parser.add_argument( + "--template_id", help="The presentation to use as a template" + ) + parser.add_argument("--customer_ids", nargs="+", help="The customers to use") + args = parser.parse_args() + + if args.command == "create_sheet": + create_sheet(args.template_id) + elif args.command == "create_presentations": + create_presentations(args.spreadsheet_id, args.customer_ids) + elif args.command == "add_customers": + add_customers(args.spreadsheet_id, args.customer_ids) def create_sheet(template_id): - pres_reader = presentation_reader.PresentationReader( - slides_service, template_id) - placeholders = pres_reader.GetAllPlaceholders() - presentation_title = pres_reader.GetTitle() - - # Create the data manager spreadsheet - spreadsheet_title = 'Data Sheet - ' + presentation_title - spreadsheet = spreadsheet_writer.CreateSpreadsheet( - sheets_service=sheets_service, - title=spreadsheet_title, - sheet_titles=['Customer Data']) - - # Get the spreadsheet ID and sheet IDs from the created spreadsheet. - spreadsheet_id = spreadsheet.get('spreadsheetId') - sheet_id = spreadsheet.get('sheets')[0].get('properties').get('sheetId') - - # Write the placeholders and metadata to the spreadsheet. - writer = spreadsheet_writer.SpreadsheetWriter( - sheets_service, spreadsheet_id) - writer.PopulateColumn( - sheet_id=sheet_id, - column_index=0, - column_id='placeholders', - values=placeholders) - writer.AddTemplateIdToSpreadsheetMetadata(template_id) - writer.ExecuteBatchUpdate() - - print('Spreadsheet URL: https://docs.google.com/spreadsheets/d/' + - spreadsheet_id) + pres_reader = presentation_reader.PresentationReader( + slides_service, template_id + ) + placeholders = pres_reader.GetAllPlaceholders() + presentation_title = pres_reader.GetTitle() + + # Create the data manager spreadsheet + spreadsheet_title = "Data Sheet - " + presentation_title + spreadsheet = spreadsheet_writer.CreateSpreadsheet( + sheets_service=sheets_service, + title=spreadsheet_title, + sheet_titles=["Customer Data"], + ) + + # Get the spreadsheet ID and sheet IDs from the created spreadsheet. + spreadsheet_id = spreadsheet.get("spreadsheetId") + sheet_id = spreadsheet.get("sheets")[0].get("properties").get("sheetId") + + # Write the placeholders and metadata to the spreadsheet. + writer = spreadsheet_writer.SpreadsheetWriter(sheets_service, spreadsheet_id) + writer.PopulateColumn( + sheet_id=sheet_id, + column_index=0, + column_id="placeholders", + values=placeholders, + ) + writer.AddTemplateIdToSpreadsheetMetadata(template_id) + writer.ExecuteBatchUpdate() + + print( + "Spreadsheet URL: https://docs.google.com/spreadsheets/d/" + + spreadsheet_id + ) def add_customers(spreadsheet_id, customer_ids): - # Read the placeholders by querying for the developer metadata we added - # while creating the spreadsheet - spreadsheet_reader = customer_spreadsheet_reader.CustomerSpreadsheetReader( - sheets_service, spreadsheet_id) - spreadsheet_reader.ReadColumnData('placeholders') - customer_spreadsheet = spreadsheet_reader.ExecuteRead() - - sheet_id = customer_spreadsheet.GetSheetId() - placeholders = customer_spreadsheet.GetColumnData('placeholders') - - # Process the placeholders into our query properties - properties = [] - for p in placeholders: - # Remove any suffix from the property name - m = re.search(r'{(\w+)(\.\w+)*}', p) - properties.append(m.group(1)) - - data_service = customer_data_service.CustomerDataService() - writer = spreadsheet_writer.SpreadsheetWriter( - sheets_service, spreadsheet_id) - - for customer_id in customer_ids: - # Get the customer data from the internal customer data service - customer_data = data_service.GetCustomerData(customer_id, properties) - - # Write the customer data to the spreadsheet - writer.InsertColumn(sheet_id=sheet_id, column_index=1) - writer.PopulateColumn( - sheet_id=sheet_id, - column_index=1, - column_id=customer_id, - values=customer_data) - - writer.ExecuteBatchUpdate() + # Read the placeholders by querying for the developer metadata we added + # while creating the spreadsheet + spreadsheet_reader = customer_spreadsheet_reader.CustomerSpreadsheetReader( + sheets_service, spreadsheet_id + ) + spreadsheet_reader.ReadColumnData("placeholders") + customer_spreadsheet = spreadsheet_reader.ExecuteRead() + + sheet_id = customer_spreadsheet.GetSheetId() + placeholders = customer_spreadsheet.GetColumnData("placeholders") + + # Process the placeholders into our query properties + properties = [] + for p in placeholders: + # Remove any suffix from the property name + m = re.search(r"{(\w+)(\.\w+)*}", p) + properties.append(m.group(1)) + + data_service = customer_data_service.CustomerDataService() + writer = spreadsheet_writer.SpreadsheetWriter(sheets_service, spreadsheet_id) + + for customer_id in customer_ids: + # Get the customer data from the internal customer data service + customer_data = data_service.GetCustomerData(customer_id, properties) + + # Write the customer data to the spreadsheet + writer.InsertColumn(sheet_id=sheet_id, column_index=1) + writer.PopulateColumn( + sheet_id=sheet_id, + column_index=1, + column_id=customer_id, + values=customer_data, + ) + + writer.ExecuteBatchUpdate() def create_presentations(spreadsheet_id, customer_ids): - spreadsheet_reader = customer_spreadsheet_reader.CustomerSpreadsheetReader( - sheets_service, spreadsheet_id) - - spreadsheet_reader.ReadColumnData('placeholders') - for customer_id in customer_ids: - spreadsheet_reader.ReadColumnData(customer_id) - - customer_spreadsheet = spreadsheet_reader.ExecuteRead() - placeholders = customer_spreadsheet.GetColumnData('placeholders') - - # Get the template presentation ID and its title - template_id = customer_spreadsheet.GetTemplateId() - pres_reader = presentation_reader.PresentationReader( - slides_service, template_id) - title = pres_reader.GetTitle() - - # Generate a presentation for each customer - for customer_id in customer_ids: - # Create a copy of the presentation - new_title = customer_id + ' - ' + title - presentation_id = drive_service.files().copy( - fileId=template_id, body={ - 'name': new_title - }).execute().get('id') - - # Replace the placeholders with the customer data in the copy - data = customer_spreadsheet.GetColumnData(customer_id) - data_dict = dict(zip(placeholders, data)) - writer = presentation_writer.PresentationWriter(slides_service, - presentation_id) - for placeholder, value in data_dict.items(): - if re.findall(r'{(\w+).image}', placeholder): - writer.ReplaceAllShapesWithImage(placeholder, value) - else: - writer.ReplaceAllText(placeholder, value) - writer.ExecuteBatchUpdate() - - print(customer_id + - ': https://docs.google.com/presentation/d/' + presentation_id) - - -if __name__ == '__main__': - main() + spreadsheet_reader = customer_spreadsheet_reader.CustomerSpreadsheetReader( + sheets_service, spreadsheet_id + ) + + spreadsheet_reader.ReadColumnData("placeholders") + for customer_id in customer_ids: + spreadsheet_reader.ReadColumnData(customer_id) + + customer_spreadsheet = spreadsheet_reader.ExecuteRead() + placeholders = customer_spreadsheet.GetColumnData("placeholders") + + # Get the template presentation ID and its title + template_id = customer_spreadsheet.GetTemplateId() + pres_reader = presentation_reader.PresentationReader( + slides_service, template_id + ) + title = pres_reader.GetTitle() + + # Generate a presentation for each customer + for customer_id in customer_ids: + # Create a copy of the presentation + new_title = customer_id + " - " + title + presentation_id = ( + drive_service.files() + .copy(fileId=template_id, body={"name": new_title}) + .execute() + .get("id") + ) + + # Replace the placeholders with the customer data in the copy + data = customer_spreadsheet.GetColumnData(customer_id) + data_dict = dict(zip(placeholders, data)) + writer = presentation_writer.PresentationWriter( + slides_service, presentation_id + ) + for placeholder, value in data_dict.items(): + if re.findall(r"{(\w+).image}", placeholder): + writer.ReplaceAllShapesWithImage(placeholder, value) + else: + writer.ReplaceAllText(placeholder, value) + writer.ExecuteBatchUpdate() + + print( + customer_id + + ": https://docs.google.com/presentation/d/" + + presentation_id + ) + + +if __name__ == "__main__": + main() diff --git a/events/next18/spreadsheet_writer.py b/events/next18/spreadsheet_writer.py index 4e7e880b..7f285ad3 100644 --- a/events/next18/spreadsheet_writer.py +++ b/events/next18/spreadsheet_writer.py @@ -18,122 +18,115 @@ def CreateSpreadsheet(sheets_service, title, sheet_titles): - """Creates an empty spreadsheet. - - It creates a spreadsheet with the provided title, and creates a sheet for - each entry in the sheet_titles list with the corresponding sheet title. - """ - sheets = [] - for sheet_title in sheet_titles: - sheet = { - 'properties': { - 'title': sheet_title, - }, - } - sheets.append(sheet) - - spreadsheet = { - 'properties': { - 'title': title, + """Creates an empty spreadsheet. + + It creates a spreadsheet with the provided title, and creates a sheet for + each entry in the sheet_titles list with the corresponding sheet title. + """ + sheets = [] + for sheet_title in sheet_titles: + sheet = { + "properties": { + "title": sheet_title, }, - 'sheets': sheets, } - return sheets_service.spreadsheets().create(body=spreadsheet).execute() + sheets.append(sheet) + + spreadsheet = { + "properties": { + "title": title, + }, + "sheets": sheets, + } + return sheets_service.spreadsheets().create(body=spreadsheet).execute() class SpreadsheetWriter(object): - """Queues writes for modifying a spreadsheet. - - Call ExecuteBatchUpdate to flush pending writes. - """ - - def __init__(self, sheets_service, spreadsheet_id): - self._sheets_service = sheets_service - self._spreadsheet_id = spreadsheet_id - self._requests = [] - - def InsertColumn(self, sheet_id, column_index): - request = { - 'insertDimension': { - 'range': { - 'sheetId': sheet_id, - 'dimension': 'COLUMNS', - 'startIndex': column_index, - 'endIndex': column_index + 1, - }, - } + """Queues writes for modifying a spreadsheet. + + Call ExecuteBatchUpdate to flush pending writes. + """ + + def __init__(self, sheets_service, spreadsheet_id): + self._sheets_service = sheets_service + self._spreadsheet_id = spreadsheet_id + self._requests = [] + + def InsertColumn(self, sheet_id, column_index): + request = { + "insertDimension": { + "range": { + "sheetId": sheet_id, + "dimension": "COLUMNS", + "startIndex": column_index, + "endIndex": column_index + 1, + }, } - self._requests.append(request) - - def PopulateColumn(self, sheet_id, column_index, column_id, values): - # Include the column ID in the column values - values = [column_id] + values - - # Populate the column with the values - rows = [] - for value in values: - row_data = { - 'values': [ - { - 'userEnteredValue': { - 'stringValue': value - } - } - ] - } - rows.append(row_data) - - update_request = { - 'updateCells': { - 'rows': rows, - 'fields': 'userEnteredValue', - 'start': { - 'sheetId': sheet_id, - 'rowIndex': 0, - 'columnIndex': column_index - } - } + } + self._requests.append(request) + + def PopulateColumn(self, sheet_id, column_index, column_id, values): + # Include the column ID in the column values + values = [column_id] + values + + # Populate the column with the values + rows = [] + for value in values: + row_data = {"values": [{"userEnteredValue": {"stringValue": value}}]} + rows.append(row_data) + + update_request = { + "updateCells": { + "rows": rows, + "fields": "userEnteredValue", + "start": { + "sheetId": sheet_id, + "rowIndex": 0, + "columnIndex": column_index, + }, } - self._requests.append(update_request) - - # Add developer metadata to the column to make it easier to read later - # by being able to just query it by the column ID - metadata_request = { - 'createDeveloperMetadata': { - 'developerMetadata': { - 'metadataKey': 'column_id', - 'metadataValue': column_id, - 'location': { - 'dimensionRange': { - 'sheetId': sheet_id, - 'dimension': 'COLUMNS', - 'startIndex': column_index, - 'endIndex': column_index + 1, - } - }, - 'visibility': 'DOCUMENT', - } + } + self._requests.append(update_request) + + # Add developer metadata to the column to make it easier to read later + # by being able to just query it by the column ID + metadata_request = { + "createDeveloperMetadata": { + "developerMetadata": { + "metadataKey": "column_id", + "metadataValue": column_id, + "location": { + "dimensionRange": { + "sheetId": sheet_id, + "dimension": "COLUMNS", + "startIndex": column_index, + "endIndex": column_index + 1, + } + }, + "visibility": "DOCUMENT", } } - self._requests.append(metadata_request) - - def AddTemplateIdToSpreadsheetMetadata(self, template_id): - request = { - 'createDeveloperMetadata': { - 'developerMetadata': { - 'metadataKey': 'template_id', - 'metadataValue': template_id, - 'location': { - 'spreadsheet': True - }, - 'visibility': 'DOCUMENT', - } + } + self._requests.append(metadata_request) + + def AddTemplateIdToSpreadsheetMetadata(self, template_id): + request = { + "createDeveloperMetadata": { + "developerMetadata": { + "metadataKey": "template_id", + "metadataValue": template_id, + "location": {"spreadsheet": True}, + "visibility": "DOCUMENT", } } - self._requests.append(request) - - def ExecuteBatchUpdate(self): - body = {'requests': self._requests} - self._requests = [] - return self._sheets_service.spreadsheets().batchUpdate( - spreadsheetId=self._spreadsheet_id, body=body).execute() + } + self._requests.append(request) + + def ExecuteBatchUpdate(self): + body = {"requests": self._requests} + self._requests = [] + return ( + self._sheets_service.spreadsheets() + .batchUpdate(spreadsheetId=self._spreadsheet_id, body=body) + .execute() + ) diff --git a/forms/quickstart/quickstart.py b/forms/quickstart/quickstart.py index 2c4ee622..7291e14a 100644 --- a/forms/quickstart/quickstart.py +++ b/forms/quickstart/quickstart.py @@ -13,8 +13,6 @@ # limitations under the License. # [START forms_quickstart] -from __future__ import print_function - from apiclient import discovery from httplib2 import Http from oauth2client import client, file, tools @@ -22,14 +20,19 @@ SCOPES = "https://www.googleapis.com/auth/forms.body" DISCOVERY_DOC = "https://forms.googleapis.com/$discovery/rest?version=v1" -store = file.Storage('token.json') +store = file.Storage("token.json") creds = None if not creds or creds.invalid: - flow = client.flow_from_clientsecrets('client_secrets.json', SCOPES) - creds = tools.run_flow(flow, store) + flow = client.flow_from_clientsecrets("client_secrets.json", SCOPES) + creds = tools.run_flow(flow, store) -form_service = discovery.build('forms', 'v1', http=creds.authorize( - Http()), discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False) +form_service = discovery.build( + "forms", + "v1", + http=creds.authorize(Http()), + discoveryServiceUrl=DISCOVERY_DOC, + static_discovery=False, +) # Request body for creating a form NEW_FORM = { @@ -40,38 +43,45 @@ # Request body to add a multiple-choice question NEW_QUESTION = { - "requests": [{ - "createItem": { - "item": { - "title": "In what year did the United States land a mission on the moon?", - "questionItem": { - "question": { - "required": True, - "choiceQuestion": { - "type": "RADIO", - "options": [ - {"value": "1965"}, - {"value": "1967"}, - {"value": "1969"}, - {"value": "1971"} - ], - "shuffle": True + "requests": [ + { + "createItem": { + "item": { + "title": ( + "In what year did the United States land a mission on" + " the moon?" + ), + "questionItem": { + "question": { + "required": True, + "choiceQuestion": { + "type": "RADIO", + "options": [ + {"value": "1965"}, + {"value": "1967"}, + {"value": "1969"}, + {"value": "1971"}, + ], + "shuffle": True, + }, } - } + }, }, - }, - "location": { - "index": 0 + "location": {"index": 0}, } } - }] + ] } # Creates the initial form result = form_service.forms().create(body=NEW_FORM).execute() # Adds the question to the form -question_setting = form_service.forms().batchUpdate(formId=result["formId"], body=NEW_QUESTION).execute() +question_setting = ( + form_service.forms() + .batchUpdate(formId=result["formId"], body=NEW_QUESTION) + .execute() +) # Prints the result to show the question has been added get_result = form_service.forms().get(formId=result["formId"]).execute() diff --git a/forms/snippets/add_item.py b/forms/snippets/add_item.py index 964404b9..b7e24671 100644 --- a/forms/snippets/add_item.py +++ b/forms/snippets/add_item.py @@ -13,8 +13,6 @@ # limitations under the License. # [START forms_add_item] -from __future__ import print_function - from apiclient import discovery from httplib2 import Http from oauth2client import client, file, tools @@ -22,14 +20,19 @@ SCOPES = "https://www.googleapis.com/auth/forms.body" DISCOVERY_DOC = "https://forms.googleapis.com/$discovery/rest?version=v1" -store = file.Storage('token.json') +store = file.Storage("token.json") creds = None if not creds or creds.invalid: - flow = client.flow_from_clientsecrets('client_secrets.json', SCOPES) - creds = tools.run_flow(flow, store) + flow = client.flow_from_clientsecrets("client_secrets.json", SCOPES) + creds = tools.run_flow(flow, store) -form_service = discovery.build('forms', 'v1', http=creds.authorize( - Http()), discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False) +form_service = discovery.build( + "forms", + "v1", + http=creds.authorize(Http()), + discoveryServiceUrl=DISCOVERY_DOC, + static_discovery=False, +) form = { "info": { @@ -42,28 +45,32 @@ # Request body to add a video item to a Form update = { - "requests": [{ - "createItem": { - "item": { - "title": "Homework video", - "description": "Quizzes in Google Forms", - "videoItem": { - "video": { - "youtubeUri": "https://www.youtube.com/watch?v=Lt5HqPvM-eI" - } - } - }, - "location": { - "index": 0 + "requests": [ + { + "createItem": { + "item": { + "title": "Homework video", + "description": "Quizzes in Google Forms", + "videoItem": { + "video": { + "youtubeUri": ( + "https://www.youtube.com/watch?v=Lt5HqPvM-eI" + ) + } + }, + }, + "location": {"index": 0}, } } - } ] } # Add the video to the form -question_setting = form_service.forms().batchUpdate( - formId=createResult["formId"], body=update).execute() +question_setting = ( + form_service.forms() + .batchUpdate(formId=createResult["formId"], body=update) + .execute() +) # Print the result to see it now has a video result = form_service.forms().get(formId=createResult["formId"]).execute() diff --git a/forms/snippets/convert_form.py b/forms/snippets/convert_form.py index bfb6ea8a..f248b613 100644 --- a/forms/snippets/convert_form.py +++ b/forms/snippets/convert_form.py @@ -13,8 +13,6 @@ # limitations under the License. # [START forms_convert_form] -from __future__ import print_function - from apiclient import discovery from httplib2 import Http from oauth2client import client, file, tools @@ -22,14 +20,19 @@ SCOPES = "https://www.googleapis.com/auth/forms.body" DISCOVERY_DOC = "https://forms.googleapis.com/$discovery/rest?version=v1" -store = file.Storage('token.json') +store = file.Storage("token.json") creds = None if not creds or creds.invalid: - flow = client.flow_from_clientsecrets('client_secrets.json', SCOPES) - creds = tools.run_flow(flow, store) + flow = client.flow_from_clientsecrets("client_secrets.json", SCOPES) + creds = tools.run_flow(flow, store) -form_service = discovery.build('forms', 'v1', http=creds.authorize( - Http()), discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False) +form_service = discovery.build( + "forms", + "v1", + http=creds.authorize(Http()), + discoveryServiceUrl=DISCOVERY_DOC, + static_discovery=False, +) form = { "info": { @@ -45,20 +48,19 @@ "requests": [ { "updateSettings": { - "settings": { - "quizSettings": { - "isQuiz": True - } - }, - "updateMask": "quizSettings.isQuiz" + "settings": {"quizSettings": {"isQuiz": True}}, + "updateMask": "quizSettings.isQuiz", } } ] } # Converts the form into a quiz -question_setting = form_service.forms().batchUpdate(formId=result["formId"], - body=update).execute() +question_setting = ( + form_service.forms() + .batchUpdate(formId=result["formId"], body=update) + .execute() +) # Print the result to see it's now a quiz getresult = form_service.forms().get(formId=result["formId"]).execute() diff --git a/forms/snippets/create_form.py b/forms/snippets/create_form.py index 97e1a767..9a86e9ae 100644 --- a/forms/snippets/create_form.py +++ b/forms/snippets/create_form.py @@ -13,8 +13,6 @@ # limitations under the License. # [START forms_create_form] -from __future__ import print_function - from apiclient import discovery from httplib2 import Http from oauth2client import client, file, tools @@ -22,14 +20,19 @@ SCOPES = "https://www.googleapis.com/auth/drive" DISCOVERY_DOC = "https://forms.googleapis.com/$discovery/rest?version=v1" -store = file.Storage('token.json') +store = file.Storage("token.json") creds = None if not creds or creds.invalid: - flow = client.flow_from_clientsecrets('client_secrets.json', SCOPES) - creds = tools.run_flow(flow, store) + flow = client.flow_from_clientsecrets("client_secrets.json", SCOPES) + creds = tools.run_flow(flow, store) -form_service = discovery.build('forms', 'v1', http=creds.authorize( - Http()), discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False) +form_service = discovery.build( + "forms", + "v1", + http=creds.authorize(Http()), + discoveryServiceUrl=DISCOVERY_DOC, + static_discovery=False, +) form = { "info": { diff --git a/forms/snippets/create_watch.py b/forms/snippets/create_watch.py index 5450d756..4211e836 100644 --- a/forms/snippets/create_watch.py +++ b/forms/snippets/create_watch.py @@ -13,8 +13,6 @@ # limitations under the License. # [START forms_create_watch] -from __future__ import print_function - from apiclient import discovery from httplib2 import Http from oauth2client import client, file, tools @@ -22,27 +20,28 @@ SCOPES = "https://www.googleapis.com/auth/drive" DISCOVERY_DOC = "https://forms.googleapis.com/$discovery/rest?version=v1" -store = file.Storage('token.json') +store = file.Storage("token.json") creds = None if not creds or creds.invalid: - flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) - creds = tools.run_flow(flow, store) + flow = client.flow_from_clientsecrets("client_secret.json", SCOPES) + creds = tools.run_flow(flow, store) -service = discovery.build('forms', 'v1', http=creds.authorize( - Http()), discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False) +service = discovery.build( + "forms", + "v1", + http=creds.authorize(Http()), + discoveryServiceUrl=DISCOVERY_DOC, + static_discovery=False, +) watch = { "watch": { - "target": { - "topic": { - "topicName": "" - } - }, - "eventType": "RESPONSES" + "target": {"topic": {"topicName": ""}}, + "eventType": "RESPONSES", } } -form_id = '' +form_id = "" # Print JSON response after form watch creation result = service.forms().watches().create(formId=form_id, body=watch).execute() diff --git a/forms/snippets/delete_watch.py b/forms/snippets/delete_watch.py index 948fc8ed..06b40ac0 100644 --- a/forms/snippets/delete_watch.py +++ b/forms/snippets/delete_watch.py @@ -13,8 +13,6 @@ # limitations under the License. # [START forms_delete_watch] -from __future__ import print_function - from apiclient import discovery from httplib2 import Http from oauth2client import client, file, tools @@ -22,18 +20,25 @@ SCOPES = "https://www.googleapis.com/auth/drive" DISCOVERY_DOC = "https://forms.googleapis.com/$discovery/rest?version=v1" -store = file.Storage('token.json') +store = file.Storage("token.json") creds = None if not creds or creds.invalid: - flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) - creds = tools.run_flow(flow, store) -service = discovery.build('forms', 'v1', http=creds.authorize( - Http()), discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False) + flow = client.flow_from_clientsecrets("client_secret.json", SCOPES) + creds = tools.run_flow(flow, store) +service = discovery.build( + "forms", + "v1", + http=creds.authorize(Http()), + discoveryServiceUrl=DISCOVERY_DOC, + static_discovery=False, +) -form_id = '' -watch_id = '' +form_id = "" +watch_id = "" # Print JSON response after deleting a form watch -result = service.forms().watches().delete(formId=form_id, watchId=watch_id).execute() +result = ( + service.forms().watches().delete(formId=form_id, watchId=watch_id).execute() +) print(result) # [END forms_delete_watch] diff --git a/forms/snippets/duplicate_form.py b/forms/snippets/duplicate_form.py index df4ca506..eb49e08a 100644 --- a/forms/snippets/duplicate_form.py +++ b/forms/snippets/duplicate_form.py @@ -13,8 +13,6 @@ # limitations under the License. # [START forms_duplicate_form] -from __future__ import print_function - import os.path from google.auth.transport.requests import Request @@ -23,38 +21,40 @@ from googleapiclient.discovery import build # If modifying these scopes, delete the file token.json. -SCOPES = ['https://www.googleapis.com/auth/drive'] +SCOPES = ["https://www.googleapis.com/auth/drive"] def main(): - """Shows copy file example in Drive v3 API. - Prints the name, id and other data of the copied file. - """ - creds = None - if os.path.exists('token.json'): - creds = Credentials.from_authorized_user_file('token.json', SCOPES) - # If there are no (valid) credentials available, let the user log in. - if not creds or not creds.valid: - if creds and creds.expired and creds.refresh_token: - creds.refresh(Request()) - else: - flow = InstalledAppFlow.from_client_secrets_file( - 'client_secrets.json', SCOPES) - creds = flow.run_local_server(port=0) - # Save the credentials for the next run - with open('token.json', 'w') as token: - token.write(creds.to_json()) - - service = build('drive', 'v3', credentials=creds) - - # Call the Drive v3 API - origin_file_id = '1ox-6vHFeKpC6mon-tL5ygBC8zpbTnTp76JCZdIg80hA' # example ID - copied_file = {'title': 'my_copy'} - results = service.files().copy( - fileId=origin_file_id, body=copied_file).execute() - print(results) - - -if __name__ == '__main__': - main() + """Shows copy file example in Drive v3 API. + Prints the name, id and other data of the copied file. + """ + creds = None + if os.path.exists("token.json"): + creds = Credentials.from_authorized_user_file("token.json", SCOPES) + # If there are no (valid) credentials available, let the user log in. + if not creds or not creds.valid: + if creds and creds.expired and creds.refresh_token: + creds.refresh(Request()) + else: + flow = InstalledAppFlow.from_client_secrets_file( + "client_secrets.json", SCOPES + ) + creds = flow.run_local_server(port=0) + # Save the credentials for the next run + with open("token.json", "w") as token: + token.write(creds.to_json()) + + service = build("drive", "v3", credentials=creds) + + # Call the Drive v3 API + origin_file_id = "1ox-6vHFeKpC6mon-tL5ygBC8zpbTnTp76JCZdIg80hA" # example ID + copied_file = {"title": "my_copy"} + results = ( + service.files().copy(fileId=origin_file_id, body=copied_file).execute() + ) + print(results) + + +if __name__ == "__main__": + main() # [END forms_duplicate_form] diff --git a/forms/snippets/list_watches.py b/forms/snippets/list_watches.py index dcb36073..eeb24c11 100644 --- a/forms/snippets/list_watches.py +++ b/forms/snippets/list_watches.py @@ -13,8 +13,6 @@ # limitations under the License. # [START forms_list_form_watches] -from __future__ import print_function - from apiclient import discovery from httplib2 import Http from oauth2client import client, file, tools @@ -22,15 +20,20 @@ SCOPES = "https://www.googleapis.com/auth/drive" DISCOVERY_DOC = "https://forms.googleapis.com/$discovery/rest?version=v1" -store = file.Storage('token.json') +store = file.Storage("token.json") creds = None if not creds or creds.invalid: - flow = client.flow_from_clientsecrets('client_secrets.json', SCOPES) - creds = tools.run_flow(flow, store) -service = discovery.build('forms', 'v1', http=creds.authorize( - Http()), discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False) + flow = client.flow_from_clientsecrets("client_secrets.json", SCOPES) + creds = tools.run_flow(flow, store) +service = discovery.build( + "forms", + "v1", + http=creds.authorize(Http()), + discoveryServiceUrl=DISCOVERY_DOC, + static_discovery=False, +) -form_id = '' +form_id = "" # Print JSON list of form watches result = service.forms().watches().list(formId=form_id).execute() diff --git a/forms/snippets/renew_watch.py b/forms/snippets/renew_watch.py index ef61df8d..1faeefda 100644 --- a/forms/snippets/renew_watch.py +++ b/forms/snippets/renew_watch.py @@ -13,8 +13,6 @@ # limitations under the License. # [START forms_renew_watch] -from __future__ import print_function - from apiclient import discovery from httplib2 import Http from oauth2client import client, file, tools @@ -22,18 +20,25 @@ SCOPES = "https://www.googleapis.com/auth/drive" DISCOVERY_DOC = "https://forms.googleapis.com/$discovery/rest?version=v1" -store = file.Storage('token.json') +store = file.Storage("token.json") creds = None if not creds or creds.invalid: - flow = client.flow_from_clientsecrets('client_secrets.json', SCOPES) - creds = tools.run_flow(flow, store) -service = discovery.build('forms', 'v1', http=creds.authorize( - Http()), discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False) + flow = client.flow_from_clientsecrets("client_secrets.json", SCOPES) + creds = tools.run_flow(flow, store) +service = discovery.build( + "forms", + "v1", + http=creds.authorize(Http()), + discoveryServiceUrl=DISCOVERY_DOC, + static_discovery=False, +) -form_id = '' -watch_id = '' +form_id = "" +watch_id = "" # Print JSON response after renewing a form watch -result = service.forms().watches().renew(formId=form_id, watchId=watch_id).execute() +result = ( + service.forms().watches().renew(formId=form_id, watchId=watch_id).execute() +) print(result) # [END forms_renew_watch] diff --git a/forms/snippets/retrieve_all_responses.py b/forms/snippets/retrieve_all_responses.py index 1cd7f340..0bf9d98c 100644 --- a/forms/snippets/retrieve_all_responses.py +++ b/forms/snippets/retrieve_all_responses.py @@ -13,8 +13,6 @@ # limitations under the License. # [START forms_retrieve_all_responses] -from __future__ import print_function - from apiclient import discovery from httplib2 import Http from oauth2client import client, file, tools @@ -22,16 +20,21 @@ SCOPES = "https://www.googleapis.com/auth/forms.responses.readonly" DISCOVERY_DOC = "https://forms.googleapis.com/$discovery/rest?version=v1" -store = file.Storage('token.json') +store = file.Storage("token.json") creds = None if not creds or creds.invalid: - flow = client.flow_from_clientsecrets('client_secrets.json', SCOPES) - creds = tools.run_flow(flow, store) -service = discovery.build('forms', 'v1', http=creds.authorize( - Http()), discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False) + flow = client.flow_from_clientsecrets("client_secrets.json", SCOPES) + creds = tools.run_flow(flow, store) +service = discovery.build( + "forms", + "v1", + http=creds.authorize(Http()), + discoveryServiceUrl=DISCOVERY_DOC, + static_discovery=False, +) # Prints the responses of your specified form: -form_id = '' +form_id = "" result = service.forms().responses().list(formId=form_id).execute() print(result) # [END forms_retrieve_all_responses] diff --git a/forms/snippets/retrieve_contents.py b/forms/snippets/retrieve_contents.py index a7395143..1144713e 100644 --- a/forms/snippets/retrieve_contents.py +++ b/forms/snippets/retrieve_contents.py @@ -13,8 +13,6 @@ # limitations under the License. # [START forms_retrieve_contents] -from __future__ import print_function - from apiclient import discovery from httplib2 import Http from oauth2client import client, file, tools @@ -22,16 +20,21 @@ SCOPES = "https://www.googleapis.com/auth/forms.body.readonly" DISCOVERY_DOC = "https://forms.googleapis.com/$discovery/rest?version=v1" -store = file.Storage('token.json') +store = file.Storage("token.json") creds = None if not creds or creds.invalid: - flow = client.flow_from_clientsecrets('client_secrets.json', SCOPES) - creds = tools.run_flow(flow, store) -service = discovery.build('forms', 'v1', http=creds.authorize( - Http()), discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False) + flow = client.flow_from_clientsecrets("client_secrets.json", SCOPES) + creds = tools.run_flow(flow, store) +service = discovery.build( + "forms", + "v1", + http=creds.authorize(Http()), + discoveryServiceUrl=DISCOVERY_DOC, + static_discovery=False, +) # Prints the title of the sample form: -form_id = '' +form_id = "" result = service.forms().get(formId=form_id).execute() print(result) # [END forms_retrieve_contents] diff --git a/forms/snippets/retrieve_single_response.py b/forms/snippets/retrieve_single_response.py index 33501143..757f65f0 100644 --- a/forms/snippets/retrieve_single_response.py +++ b/forms/snippets/retrieve_single_response.py @@ -13,8 +13,6 @@ # limitations under the License. # [START forms_retrieve_single_response] -from __future__ import print_function - from apiclient import discovery from httplib2 import Http from oauth2client import client, file, tools @@ -22,18 +20,27 @@ SCOPES = "https://www.googleapis.com/auth/forms.responses.readonly" DISCOVERY_DOC = "https://forms.googleapis.com/$discovery/rest?version=v1" -store = file.Storage('token.json') +store = file.Storage("token.json") creds = None if not creds or creds.invalid: - flow = client.flow_from_clientsecrets('client_secrets.json', SCOPES) - creds = tools.run_flow(flow, store) -service = discovery.build('forms', 'v1', http=creds.authorize( - Http()), discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False) + flow = client.flow_from_clientsecrets("client_secrets.json", SCOPES) + creds = tools.run_flow(flow, store) +service = discovery.build( + "forms", + "v1", + http=creds.authorize(Http()), + discoveryServiceUrl=DISCOVERY_DOC, + static_discovery=False, +) # Prints the specified response from your form: -form_id = '' -response_id = '' -result = service.forms().responses().get( - formId=form_id, responseId=response_id).execute() +form_id = "" +response_id = "" +result = ( + service.forms() + .responses() + .get(formId=form_id, responseId=response_id) + .execute() +) print(result) # [END forms_retrieve_single_response] diff --git a/forms/snippets/update_form.py b/forms/snippets/update_form.py index b5521d03..030cacd7 100644 --- a/forms/snippets/update_form.py +++ b/forms/snippets/update_form.py @@ -13,8 +13,6 @@ # limitations under the License. # [START forms_update_form] -from __future__ import print_function - from apiclient import discovery from httplib2 import Http from oauth2client import client, file, tools @@ -22,14 +20,19 @@ SCOPES = "https://www.googleapis.com/auth/forms.body" DISCOVERY_DOC = "https://forms.googleapis.com/$discovery/rest?version=v1" -store = file.Storage('token.json') +store = file.Storage("token.json") creds = None if not creds or creds.invalid: - flow = client.flow_from_clientsecrets('client_secrets.json', SCOPES) - creds = tools.run_flow(flow, store) + flow = client.flow_from_clientsecrets("client_secrets.json", SCOPES) + creds = tools.run_flow(flow, store) -form_service = discovery.build('forms', 'v1', http=creds.authorize( - Http()), discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False) +form_service = discovery.build( + "forms", + "v1", + http=creds.authorize(Http()), + discoveryServiceUrl=DISCOVERY_DOC, + static_discovery=False, +) form = { "info": { @@ -42,19 +45,27 @@ # Request body to add description to a Form update = { - "requests": [{ - "updateFormInfo": { - "info": { - "description": "Please complete this quiz based on this week's readings for class." - }, - "updateMask": "description" + "requests": [ + { + "updateFormInfo": { + "info": { + "description": ( + "Please complete this quiz based on this week's" + " readings for class." + ) + }, + "updateMask": "description", + } } - }] + ] } # Update the form with a description -question_setting = form_service.forms().batchUpdate( - formId=createResult["formId"], body=update).execute() +question_setting = ( + form_service.forms() + .batchUpdate(formId=createResult["formId"], body=update) + .execute() +) # Print the result to see it now has a description getresult = form_service.forms().get(formId=createResult["formId"]).execute() diff --git a/gmail/quickstart/quickstart.py b/gmail/quickstart/quickstart.py index 4509faa7..b56e73ad 100644 --- a/gmail/quickstart/quickstart.py +++ b/gmail/quickstart/quickstart.py @@ -13,8 +13,6 @@ # limitations under the License. # [START gmail_quickstart] -from __future__ import print_function - import os.path from google.auth.transport.requests import Request @@ -24,49 +22,50 @@ from googleapiclient.errors import HttpError # If modifying these scopes, delete the file token.json. -SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'] +SCOPES = ["https://www.googleapis.com/auth/gmail.readonly"] def main(): - """Shows basic usage of the Gmail API. - Lists the user's Gmail labels. - """ - creds = None - # The file token.json stores the user's access and refresh tokens, and is - # created automatically when the authorization flow completes for the first - # time. - if os.path.exists('token.json'): - creds = Credentials.from_authorized_user_file('token.json', SCOPES) - # If there are no (valid) credentials available, let the user log in. - if not creds or not creds.valid: - if creds and creds.expired and creds.refresh_token: - creds.refresh(Request()) - else: - flow = InstalledAppFlow.from_client_secrets_file( - 'credentials.json', SCOPES) - creds = flow.run_local_server(port=0) - # Save the credentials for the next run - with open('token.json', 'w') as token: - token.write(creds.to_json()) + """Shows basic usage of the Gmail API. + Lists the user's Gmail labels. + """ + creds = None + # The file token.json stores the user's access and refresh tokens, and is + # created automatically when the authorization flow completes for the first + # time. + if os.path.exists("token.json"): + creds = Credentials.from_authorized_user_file("token.json", SCOPES) + # If there are no (valid) credentials available, let the user log in. + if not creds or not creds.valid: + if creds and creds.expired and creds.refresh_token: + creds.refresh(Request()) + else: + flow = InstalledAppFlow.from_client_secrets_file( + "credentials.json", SCOPES + ) + creds = flow.run_local_server(port=0) + # Save the credentials for the next run + with open("token.json", "w") as token: + token.write(creds.to_json()) - try: - # Call the Gmail API - service = build('gmail', 'v1', credentials=creds) - results = service.users().labels().list(userId='me').execute() - labels = results.get('labels', []) + try: + # Call the Gmail API + service = build("gmail", "v1", credentials=creds) + results = service.users().labels().list(userId="me").execute() + labels = results.get("labels", []) - if not labels: - print('No labels found.') - return - print('Labels:') - for label in labels: - print(label['name']) + if not labels: + print("No labels found.") + return + print("Labels:") + for label in labels: + print(label["name"]) - except HttpError as error: - # TODO(developer) - Handle errors from gmail API. - print(f'An error occurred: {error}') + except HttpError as error: + # TODO(developer) - Handle errors from gmail API. + print(f"An error occurred: {error}") -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() # [END gmail_quickstart] diff --git a/gmail/snippet/base_test.py b/gmail/snippet/base_test.py index b09fa2ea..ec0790c4 100644 --- a/gmail/snippet/base_test.py +++ b/gmail/snippet/base_test.py @@ -20,32 +20,34 @@ class BaseTest(unittest.TestCase): - - RECIPIENT = 'gduser01@workspacesamples.dev' - TEST_USER = 'ci-test01@workspacesamples.dev' - FORWARDING_ADDRESS = 'gduser01@workspacesamples.dev' - - @classmethod - def setUpClass(cls): - cls.service = cls.create_service() - - @classmethod - def create_credentials(cls): - scope = ['https://www.googleapis.com/auth/gmail.compose', - 'https://www.googleapis.com/auth/gmail.send', - 'https://www.googleapis.com/auth/gmail.labels', - 'https://www.googleapis.com/auth/gmail.settings.basic', - 'https://www.googleapis.com/auth/gmail.settings.sharing', - 'https://mail.google.com/'] - credentials = ServiceAccountCredentials.from_json_keyfile_name(os.environ['SERVICE_ACCOUNT_CREDENTIALS'], - scopes=scope) - return credentials.create_delegated(BaseTest.TEST_USER) - - @classmethod - def create_service(cls): - credentials = cls.create_credentials() - return discovery.build('gmail', 'v1', credentials=credentials) - - -if __name__ == '__main__': - unittest.main() + RECIPIENT = "gduser01@workspacesamples.dev" + TEST_USER = "ci-test01@workspacesamples.dev" + FORWARDING_ADDRESS = "gduser01@workspacesamples.dev" + + @classmethod + def setUpClass(cls): + cls.service = cls.create_service() + + @classmethod + def create_credentials(cls): + scope = [ + "https://www.googleapis.com/auth/gmail.compose", + "https://www.googleapis.com/auth/gmail.send", + "https://www.googleapis.com/auth/gmail.labels", + "https://www.googleapis.com/auth/gmail.settings.basic", + "https://www.googleapis.com/auth/gmail.settings.sharing", + "https://mail.google.com/", + ] + credentials = ServiceAccountCredentials.from_json_keyfile_name( + os.environ["SERVICE_ACCOUNT_CREDENTIALS"], scopes=scope + ) + return credentials.create_delegated(BaseTest.TEST_USER) + + @classmethod + def create_service(cls): + credentials = cls.create_credentials() + return discovery.build("gmail", "v1", credentials=credentials) + + +if __name__ == "__main__": + unittest.main() diff --git a/gmail/snippet/send mail/create_draft.py b/gmail/snippet/send mail/create_draft.py index 3b777b4d..5b13f0a3 100644 --- a/gmail/snippet/send mail/create_draft.py +++ b/gmail/snippet/send mail/create_draft.py @@ -12,12 +12,9 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - """ -# [START gmail_create_draft] - -from __future__ import print_function +# [START gmail_create_draft] import base64 from email.message import EmailMessage @@ -27,49 +24,49 @@ def gmail_create_draft(): - """Create and insert a draft email. - Print the returned draft's message and id. - Returns: Draft object, including draft id and message meta data. + """Create and insert a draft email. + Print the returned draft's message and id. + Returns: Draft object, including draft id and message meta data. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() - try: - # create gmail api client - service = build('gmail', 'v1', credentials=creds) + try: + # create gmail api client + service = build("gmail", "v1", credentials=creds) - message = EmailMessage() + message = EmailMessage() - message.set_content('This is automated draft mail') + message.set_content("This is automated draft mail") - message['To'] = 'gduser1@workspacesamples.dev' - message['From'] = 'gduser2@workspacesamples.dev' - message['Subject'] = 'Automated draft' + message["To"] = "gduser1@workspacesamples.dev" + message["From"] = "gduser2@workspacesamples.dev" + message["Subject"] = "Automated draft" - # encoded message - encoded_message = base64.urlsafe_b64encode(message.as_bytes()).decode() + # encoded message + encoded_message = base64.urlsafe_b64encode(message.as_bytes()).decode() - create_message = { - 'message': { - 'raw': encoded_message - } - } - # pylint: disable=E1101 - draft = service.users().drafts().create(userId="me", - body=create_message).execute() + create_message = {"message": {"raw": encoded_message}} + # pylint: disable=E1101 + draft = ( + service.users() + .drafts() + .create(userId="me", body=create_message) + .execute() + ) - print(F'Draft id: {draft["id"]}\nDraft message: {draft["message"]}') + print(f'Draft id: {draft["id"]}\nDraft message: {draft["message"]}') - except HttpError as error: - print(F'An error occurred: {error}') - draft = None + except HttpError as error: + print(f"An error occurred: {error}") + draft = None - return draft + return draft -if __name__ == '__main__': - gmail_create_draft() +if __name__ == "__main__": + gmail_create_draft() # [END gmail_create_draft] diff --git a/gmail/snippet/send mail/create_draft_with_attachment.py b/gmail/snippet/send mail/create_draft_with_attachment.py index e86a82dc..ba871a23 100644 --- a/gmail/snippet/send mail/create_draft_with_attachment.py +++ b/gmail/snippet/send mail/create_draft_with_attachment.py @@ -12,9 +12,8 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START gmail_create_draft_with_attachment] -from __future__ import print_function +# [START gmail_create_draft_with_attachment] import base64 import mimetypes import os @@ -30,92 +29,90 @@ def gmail_create_draft_with_attachment(): - """Create and insert a draft email with attachment. - Print the returned draft's message and id. - Returns: Draft object, including draft id and message meta data. - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # create gmail api client - service = build('gmail', 'v1', credentials=creds) - mime_message = EmailMessage() - - # headers - mime_message['To'] = 'gduser1@workspacesamples.dev' - mime_message['From'] = 'gduser2@workspacesamples.dev' - mime_message['Subject'] = 'sample with attachment' - - # text - mime_message.set_content( - 'Hi, this is automated mail with attachment.' - 'Please do not reply.' - ) - - # attachment - attachment_filename = 'photo.jpg' - # guessing the MIME type - type_subtype, _ = mimetypes.guess_type(attachment_filename) - maintype, subtype = type_subtype.split('/') - - with open(attachment_filename, 'rb') as fp: - attachment_data = fp.read() - mime_message.add_attachment(attachment_data, maintype, subtype) - - encoded_message = base64.urlsafe_b64encode(mime_message.as_bytes()).decode() - - create_draft_request_body = { - 'message': { - 'raw': encoded_message - } - } - # pylint: disable=E1101 - draft = service.users().drafts().create(userId="me", - body=create_draft_request_body)\ - .execute() - print(F'Draft id: {draft["id"]}\nDraft message: {draft["message"]}') - except HttpError as error: - print(F'An error occurred: {error}') - draft = None - return draft + """Create and insert a draft email with attachment. + Print the returned draft's message and id. + Returns: Draft object, including draft id and message meta data. + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # create gmail api client + service = build("gmail", "v1", credentials=creds) + mime_message = EmailMessage() + + # headers + mime_message["To"] = "gduser1@workspacesamples.dev" + mime_message["From"] = "gduser2@workspacesamples.dev" + mime_message["Subject"] = "sample with attachment" + + # text + mime_message.set_content( + "Hi, this is automated mail with attachment.Please do not reply." + ) + + # attachment + attachment_filename = "photo.jpg" + # guessing the MIME type + type_subtype, _ = mimetypes.guess_type(attachment_filename) + maintype, subtype = type_subtype.split("/") + + with open(attachment_filename, "rb") as fp: + attachment_data = fp.read() + mime_message.add_attachment(attachment_data, maintype, subtype) + + encoded_message = base64.urlsafe_b64encode(mime_message.as_bytes()).decode() + + create_draft_request_body = {"message": {"raw": encoded_message}} + # pylint: disable=E1101 + draft = ( + service.users() + .drafts() + .create(userId="me", body=create_draft_request_body) + .execute() + ) + print(f'Draft id: {draft["id"]}\nDraft message: {draft["message"]}') + except HttpError as error: + print(f"An error occurred: {error}") + draft = None + return draft def build_file_part(file): - """Creates a MIME part for a file. - - Args: - file: The path to the file to be attached. - - Returns: - A MIME part that can be attached to a message. - """ - content_type, encoding = mimetypes.guess_type(file) - - if content_type is None or encoding is not None: - content_type = 'application/octet-stream' - main_type, sub_type = content_type.split('/', 1) - if main_type == 'text': - with open(file, 'rb'): - msg = MIMEText('r', _subtype=sub_type) - elif main_type == 'image': - with open(file, 'rb'): - msg = MIMEImage('r', _subtype=sub_type) - elif main_type == 'audio': - with open(file, 'rb'): - msg = MIMEAudio('r', _subtype=sub_type) - else: - with open(file, 'rb'): - msg = MIMEBase(main_type, sub_type) - msg.set_payload(file.read()) - filename = os.path.basename(file) - msg.add_header('Content-Disposition', 'attachment', filename=filename) - return msg - - -if __name__ == '__main__': - gmail_create_draft_with_attachment() - # [END gmail_create_draft_with_attachment] + """Creates a MIME part for a file. + + Args: + file: The path to the file to be attached. + + Returns: + A MIME part that can be attached to a message. + """ + content_type, encoding = mimetypes.guess_type(file) + + if content_type is None or encoding is not None: + content_type = "application/octet-stream" + main_type, sub_type = content_type.split("/", 1) + if main_type == "text": + with open(file, "rb"): + msg = MIMEText("r", _subtype=sub_type) + elif main_type == "image": + with open(file, "rb"): + msg = MIMEImage("r", _subtype=sub_type) + elif main_type == "audio": + with open(file, "rb"): + msg = MIMEAudio("r", _subtype=sub_type) + else: + with open(file, "rb"): + msg = MIMEBase(main_type, sub_type) + msg.set_payload(file.read()) + filename = os.path.basename(file) + msg.add_header("Content-Disposition", "attachment", filename=filename) + return msg + + +if __name__ == "__main__": + gmail_create_draft_with_attachment() + # [END gmail_create_draft_with_attachment] diff --git a/gmail/snippet/send mail/send_message.py b/gmail/snippet/send mail/send_message.py index 432d2cdb..697f922e 100644 --- a/gmail/snippet/send mail/send_message.py +++ b/gmail/snippet/send mail/send_message.py @@ -10,10 +10,8 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START gmail_send_message] - -from __future__ import print_function +# [START gmail_send_message] import base64 from email.message import EmailMessage @@ -23,43 +21,44 @@ def gmail_send_message(): - """Create and send an email message - Print the returned message id - Returns: Message object, including message id + """Create and send an email message + Print the returned message id + Returns: Message object, including message id - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() - try: - service = build('gmail', 'v1', credentials=creds) - message = EmailMessage() + try: + service = build("gmail", "v1", credentials=creds) + message = EmailMessage() - message.set_content('This is automated draft mail') + message.set_content("This is automated draft mail") - message['To'] = 'gduser1@workspacesamples.dev' - message['From'] = 'gduser2@workspacesamples.dev' - message['Subject'] = 'Automated draft' + message["To"] = "gduser1@workspacesamples.dev" + message["From"] = "gduser2@workspacesamples.dev" + message["Subject"] = "Automated draft" - # encoded message - encoded_message = base64.urlsafe_b64encode(message.as_bytes()) \ - .decode() + # encoded message + encoded_message = base64.urlsafe_b64encode(message.as_bytes()).decode() - create_message = { - 'raw': encoded_message - } - # pylint: disable=E1101 - send_message = (service.users().messages().send - (userId="me", body=create_message).execute()) - print(F'Message Id: {send_message["id"]}') - except HttpError as error: - print(F'An error occurred: {error}') - send_message = None - return send_message + create_message = {"raw": encoded_message} + # pylint: disable=E1101 + send_message = ( + service.users() + .messages() + .send(userId="me", body=create_message) + .execute() + ) + print(f'Message Id: {send_message["id"]}') + except HttpError as error: + print(f"An error occurred: {error}") + send_message = None + return send_message -if __name__ == '__main__': - gmail_send_message() +if __name__ == "__main__": + gmail_send_message() # [END gmail_send_message] diff --git a/gmail/snippet/send mail/test_create_draft.py b/gmail/snippet/send mail/test_create_draft.py index 9f6e813b..f8636c1f 100644 --- a/gmail/snippet/send mail/test_create_draft.py +++ b/gmail/snippet/send mail/test_create_draft.py @@ -19,14 +19,14 @@ class TestCreateDraft(unittest.TestCase): - """Unit test classs for snippet""" + """Unit test class for snippet""" - @classmethod - def test_create_draft(cls): - """Unit test for create draft""" - draft = gmail_create_draft() - cls.assertIsNotNone(cls, draft) + @classmethod + def test_create_draft(cls): + """Unit test for create draft""" + draft = gmail_create_draft() + cls.assertIsNotNone(cls, draft) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/gmail/snippet/send mail/test_create_draft_with_attachment.py b/gmail/snippet/send mail/test_create_draft_with_attachment.py index fcb010cc..502c813e 100644 --- a/gmail/snippet/send mail/test_create_draft_with_attachment.py +++ b/gmail/snippet/send mail/test_create_draft_with_attachment.py @@ -19,14 +19,14 @@ class TestCreateDraftWithAttachment(unittest.TestCase): - """Unit test classs for Change snippet""" + """Unit test class for Change snippet""" - @classmethod - def test_create_draft_with_attachment(cls): - """Test create draft with attachment""" - draft = gmail_create_draft_with_attachment() - cls.assertIsNotNone(cls, draft) + @classmethod + def test_create_draft_with_attachment(cls): + """Test create draft with attachment""" + draft = gmail_create_draft_with_attachment() + cls.assertIsNotNone(cls, draft) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/gmail/snippet/send mail/test_send_message.py b/gmail/snippet/send mail/test_send_message.py index 2d6264e4..3aecfb65 100644 --- a/gmail/snippet/send mail/test_send_message.py +++ b/gmail/snippet/send mail/test_send_message.py @@ -12,19 +12,20 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest from send_message import gmail_send_message class TestSendMessage(unittest.TestCase): - """Unit test class for snippet""" + """Unit test class for snippet""" - def test_send_message(self): - """test send message""" - send_message = gmail_send_message() - self.assertIsNotNone(self, send_message) + def test_send_message(self): + """test send message""" + send_message = gmail_send_message() + self.assertIsNotNone(self, send_message) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/gmail/snippet/send mail/test_send_message_with_attachment.py b/gmail/snippet/send mail/test_send_message_with_attachment.py index 722a15d5..79cfe0f5 100644 --- a/gmail/snippet/send mail/test_send_message_with_attachment.py +++ b/gmail/snippet/send mail/test_send_message_with_attachment.py @@ -12,19 +12,20 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest from send_message_with_attachment import gmail_send_message_with_attachment class TestSendMessageWithAttachment(unittest.TestCase): - """Unit test class for gmail snippet""" + """Unit test class for gmail snippet""" - def test_send_message_with_attachment(self): - """ test send message with attachment""" - send_message = gmail_send_message_with_attachment() - self.assertIsNotNone(self, send_message) + def test_send_message_with_attachment(self): + """test send message with attachment""" + send_message = gmail_send_message_with_attachment() + self.assertIsNotNone(self, send_message) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/gmail/snippet/settings snippets/create_filter.py b/gmail/snippet/settings snippets/create_filter.py index 17508392..35fb1724 100644 --- a/gmail/snippet/settings snippets/create_filter.py +++ b/gmail/snippet/settings snippets/create_filter.py @@ -12,52 +12,50 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START gmail_create_filter] - -from __future__ import print_function +# [START gmail_create_filter] import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def create_filter(): - """Create a filter. - Returns: Draft object, including filter id. - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # create gmail api client - service = build('gmail', 'v1', credentials=creds) - - label_name = 'IMPORTANT' - filter_content = { - 'criteria': { - 'from': 'gsuder1@workspacesamples.dev' - }, - 'action': { - 'addLabelIds': [label_name], - 'removeLabelIds': ['INBOX'] - } - } - - # pylint: disable=E1101 - result = service.users().settings().filters().create( - userId='me', body=filter_content).execute() - print(F'Created filter with id: {result.get("id")}') - - except HttpError as error: - print(F'An error occurred: {error}') - result = None - - return result.get('id') - - -if __name__ == '__main__': - create_filter() + """Create a filter. + Returns: Draft object, including filter id. + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # create gmail api client + service = build("gmail", "v1", credentials=creds) + + label_name = "IMPORTANT" + filter_content = { + "criteria": {"from": "gsuder1@workspacesamples.dev"}, + "action": {"addLabelIds": [label_name], "removeLabelIds": ["INBOX"]}, + } + + # pylint: disable=E1101 + result = ( + service.users() + .settings() + .filters() + .create(userId="me", body=filter_content) + .execute() + ) + print(f'Created filter with id: {result.get("id")}') + + except HttpError as error: + print(f"An error occurred: {error}") + result = None + + return result.get("id") + + +if __name__ == "__main__": + create_filter() # [END gmail_create_filter] diff --git a/gmail/snippet/settings snippets/enable_auto_reply.py b/gmail/snippet/settings snippets/enable_auto_reply.py index 69bd727c..fa9f3425 100644 --- a/gmail/snippet/settings snippets/enable_auto_reply.py +++ b/gmail/snippet/settings snippets/enable_auto_reply.py @@ -12,10 +12,8 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START gmail_enable_auto_reply] - -from __future__ import print_function +# [START gmail_enable_auto_reply] from datetime import datetime, timedelta import google.auth @@ -25,45 +23,50 @@ def enable_auto_reply(): - """Enable auto reply. - Returns:Draft object, including reply message and response meta data. - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # create gmail api client - service = build('gmail', 'v1', credentials=creds) - - epoch = datetime.utcfromtimestamp(0) - now = datetime.now() - start_time = (now - epoch).total_seconds() * 1000 - end_time = (now + timedelta(days=7) - epoch).total_seconds() * 1000 - vacation_settings = { - 'enableAutoReply': True, - 'responseBodyHtml': "I am on vacation and will reply when I am " - "back in the office. Thanks!", - 'restrictToDomain': True, - 'startTime': long(start_time), - 'endTime': long(end_time) - } - - # pylint: disable=E1101 - response = service.users().settings().updateVacation( - userId='me', body=vacation_settings).execute() - print(F'Enabled AutoReply with message: ' - F'{response.get("responseBodyHtml")}') - - except HttpError as error: - print(F'An error occurred: {error}') - response = None - - return response - - -if __name__ == '__main__': - enable_auto_reply() + """Enable auto reply. + Returns:Draft object, including reply message and response meta data. + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # create gmail api client + service = build("gmail", "v1", credentials=creds) + + epoch = datetime.utcfromtimestamp(0) + now = datetime.now() + start_time = (now - epoch).total_seconds() * 1000 + end_time = (now + timedelta(days=7) - epoch).total_seconds() * 1000 + vacation_settings = { + "enableAutoReply": True, + "responseBodyHtml": ( + "I am on vacation and will reply when I am " + "back in the office. Thanks!" + ), + "restrictToDomain": True, + "startTime": long(start_time), + "endTime": long(end_time), + } + + # pylint: disable=E1101 + response = ( + service.users() + .settings() + .updateVacation(userId="me", body=vacation_settings) + .execute() + ) + print(f"Enabled AutoReply with message: {response.get('responseBodyHtml')}") + + except HttpError as error: + print(f"An error occurred: {error}") + response = None + + return response + + +if __name__ == "__main__": + enable_auto_reply() # [END gmail_enable_auto_reply] diff --git a/gmail/snippet/settings snippets/enable_forwarding.py b/gmail/snippet/settings snippets/enable_forwarding.py index 97f63157..17e4b80f 100644 --- a/gmail/snippet/settings snippets/enable_forwarding.py +++ b/gmail/snippet/settings snippets/enable_forwarding.py @@ -12,52 +12,59 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START gmail_enable_forwarding] - -from __future__ import print_function +# [START gmail_enable_forwarding] import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def enable_forwarding(): - """Enable email forwarding. - Returns:Draft object, including forwarding id and result meta data. - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # create gmail api client - service = build('gmail', 'v1', credentials=creds) - - address = {'forwardingEmail': 'gduser1@workspacesamples.dev'} - - # pylint: disable=E1101 - result = service.users().settings().forwardingAddresses(). \ - create(userId='me', body=address).execute() - if result.get('verificationStatus') == 'accepted': - body = { - 'emailAddress': result.get('forwardingEmail'), - 'enabled': True, - 'disposition': 'trash' - } - # pylint: disable=E1101 - result = service.users().settings().updateAutoForwarding( - userId='me', body=body).execute() - print(F'Forwarding is enabled : {result}') - - except HttpError as error: - print(F'An error occurred: {error}') - result = None - - return result - - -if __name__ == '__main__': - enable_forwarding() + """Enable email forwarding. + Returns:Draft object, including forwarding id and result meta data. + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # create gmail api client + service = build("gmail", "v1", credentials=creds) + + address = {"forwardingEmail": "gduser1@workspacesamples.dev"} + + # pylint: disable=E1101 + result = ( + service.users() + .settings() + .forwardingAddresses() + .create(userId="me", body=address) + .execute() + ) + if result.get("verificationStatus") == "accepted": + body = { + "emailAddress": result.get("forwardingEmail"), + "enabled": True, + "disposition": "trash", + } + # pylint: disable=E1101 + result = ( + service.users() + .settings() + .updateAutoForwarding(userId="me", body=body) + .execute() + ) + print(f"Forwarding is enabled : {result}") + + except HttpError as error: + print(f"An error occurred: {error}") + result = None + + return result + + +if __name__ == "__main__": + enable_forwarding() # [END gmail_enable_forwarding] diff --git a/gmail/snippet/settings snippets/test_create_filter.py b/gmail/snippet/settings snippets/test_create_filter.py index b040a683..27a4abe8 100644 --- a/gmail/snippet/settings snippets/test_create_filter.py +++ b/gmail/snippet/settings snippets/test_create_filter.py @@ -12,20 +12,21 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest from create_filter import create_filter class TestCreateFilter(unittest.TestCase): - """Unit test class to implement test case for Snippets""" + """Unit test class to implement test case for Snippets""" - @classmethod - def test_create_file(cls): - """test to create file""" - result = create_filter() - cls.assertIsNotNone(cls, result) + @classmethod + def test_create_file(cls): + """test to create file""" + result = create_filter() + cls.assertIsNotNone(cls, result) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/gmail/snippet/settings snippets/test_enable_auto_reply.py b/gmail/snippet/settings snippets/test_enable_auto_reply.py index c2373dd0..92873a8a 100644 --- a/gmail/snippet/settings snippets/test_enable_auto_reply.py +++ b/gmail/snippet/settings snippets/test_enable_auto_reply.py @@ -12,20 +12,21 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest from enable_auto_reply import enable_auto_reply class TestEnableAutoReply(unittest.TestCase): - """Unit test class for the snippet""" + """Unit test class for the snippet""" - @classmethod - def test_enable_auto_reply(cls): - """ test to enable auto reply""" - result = enable_auto_reply() - cls.assertIsNotNone(cls, result) + @classmethod + def test_enable_auto_reply(cls): + """test to enable auto reply""" + result = enable_auto_reply() + cls.assertIsNotNone(cls, result) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/gmail/snippet/settings snippets/test_enable_forwarding.py b/gmail/snippet/settings snippets/test_enable_forwarding.py index 717f8998..22411e23 100644 --- a/gmail/snippet/settings snippets/test_enable_forwarding.py +++ b/gmail/snippet/settings snippets/test_enable_forwarding.py @@ -12,20 +12,21 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest from enable_forwarding import enable_forwarding class TestEnableForwarding(unittest.TestCase): - """Unit test class to test enable forwarding snippet""" + """Unit test class to test enable forwarding snippet""" - @classmethod - def test_enable_forwarding(cls): - """test to enable forwarding""" - result = enable_forwarding() - cls.assertIsNotNone(cls, result) + @classmethod + def test_enable_forwarding(cls): + """test to enable forwarding""" + result = enable_forwarding() + cls.assertIsNotNone(cls, result) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/gmail/snippet/settings snippets/test_update_signature.py b/gmail/snippet/settings snippets/test_update_signature.py index 30baaebd..71a60c7a 100644 --- a/gmail/snippet/settings snippets/test_update_signature.py +++ b/gmail/snippet/settings snippets/test_update_signature.py @@ -12,20 +12,21 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest from update_signature import update_signature class TestUpdateSignature(unittest.TestCase): - """Unit test class to test Update signature snippet""" + """Unit test class to test Update signature snippet""" - @classmethod - def test_update_signature(cls): - """ test to update signature""" - result = update_signature() - cls.assertIsNotNone(cls, result) + @classmethod + def test_update_signature(cls): + """test to update signature""" + result = update_signature() + cls.assertIsNotNone(cls, result) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/gmail/snippet/settings snippets/update_signature.py b/gmail/snippet/settings snippets/update_signature.py index bfa93c37..b0711616 100644 --- a/gmail/snippet/settings snippets/update_signature.py +++ b/gmail/snippet/settings snippets/update_signature.py @@ -12,57 +12,62 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START gmail_update_signature] - -from __future__ import print_function +# [START gmail_update_signature] import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def update_signature(): - """Create and update signature in gmail. - Returns:Draft object, including updated signature. - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # create gmail api client - service = build('gmail', 'v1', credentials=creds) - - primary_alias = None - - # pylint: disable=E1101 - aliases = service.users().settings().sendAs().list(userId='me')\ - .execute() - for alias in aliases.get('sendAs'): - if alias.get('isPrimary'): - primary_alias = alias - break - - send_as_configuration = { - 'displayName': primary_alias.get('sendAsEmail'), - 'signature': 'Automated Signature' - } - - # pylint: disable=E1101 - result = service.users().settings().sendAs() \ - .patch(userId='me', sendAsEmail=primary_alias.get('sendAsEmail'), - body=send_as_configuration).execute() - print(F'Updated signature for: {result.get("displayName")}') - - except HttpError as error: - print(F'An error occurred: {error}') - result = None - - return result.get('signature') - - -if __name__ == '__main__': - update_signature() + """Create and update signature in gmail. + Returns:Draft object, including updated signature. + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # create gmail api client + service = build("gmail", "v1", credentials=creds) + + primary_alias = None + + # pylint: disable=E1101 + aliases = service.users().settings().sendAs().list(userId="me").execute() + for alias in aliases.get("sendAs"): + if alias.get("isPrimary"): + primary_alias = alias + break + + send_as_configuration = { + "displayName": primary_alias.get("sendAsEmail"), + "signature": "Automated Signature", + } + + # pylint: disable=E1101 + result = ( + service.users() + .settings() + .sendAs() + .patch( + userId="me", + sendAsEmail=primary_alias.get("sendAsEmail"), + body=send_as_configuration, + ) + .execute() + ) + print(f'Updated signature for: {result.get("displayName")}') + + except HttpError as error: + print(f"An error occurred: {error}") + result = None + + return result.get("signature") + + +if __name__ == "__main__": + update_signature() # [END gmail_update_signature] diff --git a/gmail/snippet/smime snippets/create_smime_info.py b/gmail/snippet/smime snippets/create_smime_info.py index ba66e5ae..90c4325a 100644 --- a/gmail/snippet/smime snippets/create_smime_info.py +++ b/gmail/snippet/smime snippets/create_smime_info.py @@ -9,38 +9,36 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START gmail_create_smime_info] - -from __future__ import print_function +# [START gmail_create_smime_info] import base64 def create_smime_info(cert_filename, cert_password): - """Create an smimeInfo resource for a certificate from file. - Args: - cert_filename: Name of the file containing the S/MIME certificate. - cert_password: Password for the certificate file, or None if the file is not - password-protected. - Returns : Smime object, including smime information - """ - + """Create an smimeInfo resource for a certificate from file. + Args: + cert_filename: Name of the file containing the S/MIME certificate. + cert_password: Password for the certificate file, or None if the file is not + password-protected. + Returns : Smime object, including smime information + """ + + smime_info = None + try: + with open(cert_filename, "rb") as cert: + smime_info = {} + data = cert.read().encode("UTF-8") + smime_info["pkcs12"] = base64.urlsafe_b64encode(data).decode() + if cert_password and len(cert_password) > 0: + smime_info["encryptedKeyPassword"] = cert_password + + except (OSError, IOError) as error: + print(f"An error occurred while reading the certificate file: {error}") smime_info = None - try: - with open(cert_filename, 'rb') as cert: - smime_info = {} - data = cert.read().encode('UTF-8') - smime_info['pkcs12'] = base64.urlsafe_b64encode(data).decode() - if cert_password and len(cert_password) > 0: - smime_info['encryptedKeyPassword'] = cert_password - - except (OSError, IOError) as error: - print(F'An error occurred while reading the certificate file: {error}') - smime_info = None - return smime_info + return smime_info -if __name__ == '__main__': - print(create_smime_info(cert_filename='xyz', cert_password='xyz')) +if __name__ == "__main__": + print(create_smime_info(cert_filename="xyz", cert_password="xyz")) # [END gmail_create_smime_info] diff --git a/gmail/snippet/smime snippets/insert_cert_from_csv.py b/gmail/snippet/smime snippets/insert_cert_from_csv.py index a2407cda..d07fc2fa 100644 --- a/gmail/snippet/smime snippets/insert_cert_from_csv.py +++ b/gmail/snippet/smime snippets/insert_cert_from_csv.py @@ -9,10 +9,8 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START gmail_insert_cert_from_csv] - -from __future__ import print_function +# [START gmail_insert_cert_from_csv] import csv import create_smime_info @@ -20,35 +18,35 @@ def insert_cert_from_csv(csv_filename): - """Upload S/MIME certificates based on the contents of a CSV file. - Each row of the CSV file should contain a user ID, path to the certificate, - and the certificate password. - - Args: - csv_filename: Name of the CSV file. - """ - - try: - - with open(csv_filename, 'rb') as cert: - csv_reader = csv.reader(cert, delimiter=',') - next(csv_reader, None) # skip CSV file header - for row in csv_reader: - user_id = row[0] - cert_filename = row[1] - cert_password = row[2] - smime_info = create_smime_info.create_smime_info( - cert_filename=cert_filename, cert_password=cert_password) - if smime_info: - insert_smime_info.insert_smime_info() - else: - print(F'Unable to read certificate file for user_id: {user_id}') - return smime_info - - except (OSError, IOError) as error: - print(F'An error occured while reading the CSV file: {error}') - - -if __name__ == '__main__': - insert_cert_from_csv(csv_filename='xyz') + """Upload S/MIME certificates based on the contents of a CSV file. + Each row of the CSV file should contain a user ID, path to the certificate, + and the certificate password. + + Args: + csv_filename: Name of the CSV file. + """ + + try: + with open(csv_filename, "rb") as cert: + csv_reader = csv.reader(cert, delimiter=",") + next(csv_reader, None) # skip CSV file header + for row in csv_reader: + user_id = row[0] + cert_filename = row[1] + cert_password = row[2] + smime_info = create_smime_info.create_smime_info( + cert_filename=cert_filename, cert_password=cert_password + ) + if smime_info: + insert_smime_info.insert_smime_info() + else: + print(f"Unable to read certificate file for user_id: {user_id}") + return smime_info + + except (OSError, IOError) as error: + print(f"An error occured while reading the CSV file: {error}") + + +if __name__ == "__main__": + insert_cert_from_csv(csv_filename="xyz") # [END gmail_insert_cert_from_csv] diff --git a/gmail/snippet/smime snippets/insert_smime_info.py b/gmail/snippet/smime snippets/insert_smime_info.py index 46a8fe8e..19540ad7 100644 --- a/gmail/snippet/smime snippets/insert_smime_info.py +++ b/gmail/snippet/smime snippets/insert_smime_info.py @@ -9,10 +9,8 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START gmail_insert_smime_info] - -from __future__ import print_function +# [START gmail_insert_smime_info] import create_smime_info import google.auth from googleapiclient.discovery import build @@ -20,40 +18,47 @@ def insert_smime_info(): - """Upload an S/MIME certificate for the user. - Print the inserted certificate's id - Returns : Result object with inserted certificate id and other meta-data + """Upload an S/MIME certificate for the user. + Print the inserted certificate's id + Returns : Result object with inserted certificate id and other meta-data - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() - try: - # create gmail api client - service = build('gmail', 'v1', credentials=creds) + try: + # create gmail api client + service = build("gmail", "v1", credentials=creds) - user_id = 'gduser1@workspacesamples.dev' - smime_info = create_smime_info.create_smime_info(cert_filename='xyz', cert_password='xyz') - send_as_email = None + user_id = "gduser1@workspacesamples.dev" + smime_info = create_smime_info.create_smime_info( + cert_filename="xyz", cert_password="xyz" + ) + send_as_email = None - if not send_as_email: - send_as_email = user_id + if not send_as_email: + send_as_email = user_id - # pylint: disable=maybe-no-member - results = service.users().settings().sendAs().smimeInfo().\ - insert(userId=user_id, sendAsEmail=send_as_email, body=smime_info)\ - .execute() - print(F'Inserted certificate; id: {results["id"]}') + # pylint: disable=maybe-no-member + results = ( + service.users() + .settings() + .sendAs() + .smimeInfo() + .insert(userId=user_id, sendAsEmail=send_as_email, body=smime_info) + .execute() + ) + print(f'Inserted certificate; id: {results["id"]}') - except HttpError as error: - print(F'An error occurred: {error}') - results = None + except HttpError as error: + print(f"An error occurred: {error}") + results = None - return results + return results -if __name__ == '__main__': - insert_smime_info() +if __name__ == "__main__": + insert_smime_info() # [END gmail_insert_smime_info] diff --git a/gmail/snippet/smime snippets/test_create_smime_info.py b/gmail/snippet/smime snippets/test_create_smime_info.py index be98ea5b..d5a1f278 100644 --- a/gmail/snippet/smime snippets/test_create_smime_info.py +++ b/gmail/snippet/smime snippets/test_create_smime_info.py @@ -12,21 +12,22 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest from create_smime_info import create_smime_info class TestCreateSmimeInfo(unittest.TestCase): - """Unit test class to test Snippet""" + """Unit test class to test Snippet""" - @classmethod - def test_create_smime_info(cls): - """test to create smime info""" - # enter the file and password accordingly - smime_info = create_smime_info(cert_filename='abc', cert_password='abc') - cls.assertIsNotNone(cls, smime_info) + @classmethod + def test_create_smime_info(cls): + """test to create smime info""" + # enter the file and password accordingly + smime_info = create_smime_info(cert_filename="abc", cert_password="abc") + cls.assertIsNotNone(cls, smime_info) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/gmail/snippet/smime snippets/test_insert_cert_from_csv.py b/gmail/snippet/smime snippets/test_insert_cert_from_csv.py index c44ab826..4d728d2b 100644 --- a/gmail/snippet/smime snippets/test_insert_cert_from_csv.py +++ b/gmail/snippet/smime snippets/test_insert_cert_from_csv.py @@ -12,20 +12,21 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest from insert_cert_from_csv import insert_cert_from_csv class TestInsertCertFromCsv(unittest.TestCase): - """unittest class for testing the snippetts""" + """unittest class for testing the snippetts""" - @classmethod - def test_insert_cert_from_csv(cls): - """test to insert cert from csv""" - result = insert_cert_from_csv('test.csv') - cls.assertIsNotNone(cls, result) + @classmethod + def test_insert_cert_from_csv(cls): + """test to insert cert from csv""" + result = insert_cert_from_csv("test.csv") + cls.assertIsNotNone(cls, result) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/gmail/snippet/smime snippets/test_insert_smime_info.py b/gmail/snippet/smime snippets/test_insert_smime_info.py index 366e76d7..3478fcf7 100644 --- a/gmail/snippet/smime snippets/test_insert_smime_info.py +++ b/gmail/snippet/smime snippets/test_insert_smime_info.py @@ -12,20 +12,21 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest from insert_smime_info import insert_smime_info class TestInsertSmimeInfo(unittest.TestCase): - """Unit test class for snippet""" + """Unit test class for snippet""" - @classmethod - def test_insert_smime_info(cls): - """test to insert smime info""" - result = insert_smime_info() - cls.assertIsNotNone(cls, result) + @classmethod + def test_insert_smime_info(cls): + """test to insert smime info""" + result = insert_smime_info() + cls.assertIsNotNone(cls, result) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/gmail/snippet/smime snippets/test_update_smime_cert.py b/gmail/snippet/smime snippets/test_update_smime_cert.py index 70935315..54343b28 100644 --- a/gmail/snippet/smime snippets/test_update_smime_cert.py +++ b/gmail/snippet/smime snippets/test_update_smime_cert.py @@ -12,22 +12,27 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest from update_smime_cert import update_smime_cert class TestUpdateSmimeCert(unittest.TestCase): - """Unit test class for snippets""" - - @classmethod - def test_update_smime_cert(cls): - """test update smime cert""" - result = update_smime_cert(user_id='xyz', send_as_email='yzx', - cert_filename='abc', cert_password='abc', - expire_dt='cde') - cls.assertIsNotNone(cls, result) - - -if __name__ == '__main__': - unittest.main() + """Unit test class for snippets""" + + @classmethod + def test_update_smime_cert(cls): + """test update smime cert""" + result = update_smime_cert( + user_id="xyz", + send_as_email="yzx", + cert_filename="abc", + cert_password="abc", + expire_dt="cde", + ) + cls.assertIsNotNone(cls, result) + + +if __name__ == "__main__": + unittest.main() diff --git a/gmail/snippet/smime snippets/test_update_smime_from_csv.py b/gmail/snippet/smime snippets/test_update_smime_from_csv.py index d976cf86..f03d082f 100644 --- a/gmail/snippet/smime snippets/test_update_smime_from_csv.py +++ b/gmail/snippet/smime snippets/test_update_smime_from_csv.py @@ -12,20 +12,21 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest from update_smime_from_csv import update_smime_from_csv class TestUpdateSmimeFromCsv(unittest.TestCase): - """unit test class for snippets""" + """unit test class for snippets""" - @classmethod - def test_update_smime_from_csv(cls): - """test to update smime from csv""" - result = update_smime_from_csv(csv_filename='abc') - cls.assertIsNotNone(cls, result) + @classmethod + def test_update_smime_from_csv(cls): + """test to update smime from csv""" + result = update_smime_from_csv(csv_filename="abc") + cls.assertIsNotNone(cls, result) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/gmail/snippet/smime snippets/update_smime_cert.py b/gmail/snippet/smime snippets/update_smime_cert.py index cce80df1..34d72ded 100644 --- a/gmail/snippet/smime snippets/update_smime_cert.py +++ b/gmail/snippet/smime snippets/update_smime_cert.py @@ -9,10 +9,8 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START gmail_update_smime_certs] - -from __future__ import print_function +# [START gmail_update_smime_certs] from datetime import datetime import create_smime_info @@ -22,94 +20,107 @@ from googleapiclient.errors import HttpError -def update_smime_cert(user_id, send_as_email, cert_filename, cert_password, - expire_dt): - """Update S/MIME certificates for the user. - - First performs a lookup of all certificates for a user. If there are no - certificates, or they all expire before the specified date/time, uploads the - certificate in the specified file. If the default certificate is expired or - there was no default set, chooses the certificate with the expiration furthest - into the future and sets it as default. - - Args: - user_id: User's email address. - send_as_email: The "send as" email address, or None if it should be the same - as user_id. - cert_filename: Name of the file containing the S/MIME certificate. - cert_password: Password for the certificate file, or None if the file is not - password-protected. - expire_dt: DateTime object against which the certificate expiration is - compared. If None, uses the current time. - - Returns: - The ID of the default certificate. - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - if not send_as_email: - send_as_email = user_id - - creds, _ = google.auth.default() - - try: - # create gmail api client - service = build('gmail', 'v1', credentials=creds) - - # pylint: disable=maybe-no-member - results = service.users().settings().sendAs().smimeInfo().list( - userId=user_id, sendAsEmail=send_as_email).execute() - - except HttpError as error: - print(F'An error occurred during list: {error}') - return None - - default_cert_id = None - best_cert_id = (None, datetime.datetime.fromtimestamp(0)) - - if not expire_dt: - expire_dt = datetime.datetime.now() - if results and 'smimeInfo' in results: - for smime_info in results['smimeInfo']: - cert_id = smime_info['id'] - is_default_cert = smime_info['isDefault'] - if is_default_cert: - default_cert_id = cert_id - exp = datetime.datetime.fromtimestamp(smime_info['expiration'] / 1000) - if exp > expire_dt: - if exp > best_cert_id[1]: - best_cert_id = (cert_id, exp) - else: - if is_default_cert: - default_cert_id = None - - if not default_cert_id: - default_id = best_cert_id[0] - if not default_id and cert_filename: - create_smime_info.create_smime_info(cert_filename=cert_filename, - cert_password=cert_password) - results = insert_smime_info.insert_smime_info() - if results: - default_id = results['id'] - - if default_id: - try: - # pylint: disable=maybe-no-member - service.users().settings().sendAs().smimeInfo().setDefault( - userId=user_id, sendAsEmail=send_as_email, id=default_id) \ - .execute() - return default_id - except HttpError as error: - print(F'An error occurred during setDefault: {error}') - else: - return default_cert_id - +def update_smime_cert( + user_id, send_as_email, cert_filename, cert_password, expire_dt +): + """Update S/MIME certificates for the user. + + First performs a lookup of all certificates for a user. If there are no + certificates, or they all expire before the specified date/time, uploads the + certificate in the specified file. If the default certificate is expired or + there was no default set, chooses the certificate with the expiration furthest + into the future and sets it as default. + + Args: + user_id: User's email address. + send_as_email: The "send as" email address, or None if it should be the same + as user_id. + cert_filename: Name of the file containing the S/MIME certificate. + cert_password: Password for the certificate file, or None if the file is not + password-protected. + expire_dt: DateTime object against which the certificate expiration is + compared. If None, uses the current time. + + Returns: + The ID of the default certificate. + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + if not send_as_email: + send_as_email = user_id + + creds, _ = google.auth.default() + + try: + # create gmail api client + service = build("gmail", "v1", credentials=creds) + + # pylint: disable=maybe-no-member + results = ( + service.users() + .settings() + .sendAs() + .smimeInfo() + .list(userId=user_id, sendAsEmail=send_as_email) + .execute() + ) + + except HttpError as error: + print(f"An error occurred during list: {error}") return None - -if __name__ == '__main__': - update_smime_cert(user_id='xyz', send_as_email=None, cert_filename='xyz', - cert_password='xyz', expire_dt=None) + default_cert_id = None + best_cert_id = (None, datetime.datetime.fromtimestamp(0)) + + if not expire_dt: + expire_dt = datetime.datetime.now() + if results and "smimeInfo" in results: + for smime_info in results["smimeInfo"]: + cert_id = smime_info["id"] + is_default_cert = smime_info["isDefault"] + if is_default_cert: + default_cert_id = cert_id + exp = datetime.datetime.fromtimestamp(smime_info["expiration"] / 1000) + if exp > expire_dt: + if exp > best_cert_id[1]: + best_cert_id = (cert_id, exp) + else: + if is_default_cert: + default_cert_id = None + + if not default_cert_id: + default_id = best_cert_id[0] + if not default_id and cert_filename: + create_smime_info.create_smime_info( + cert_filename=cert_filename, cert_password=cert_password + ) + results = insert_smime_info.insert_smime_info() + if results: + default_id = results["id"] + + if default_id: + try: + # pylint: disable=maybe-no-member + service.users().settings().sendAs().smimeInfo().setDefault( + userId=user_id, sendAsEmail=send_as_email, id=default_id + ).execute() + return default_id + except HttpError as error: + print(f"An error occurred during setDefault: {error}") + else: + return default_cert_id + + return None + + +if __name__ == "__main__": + update_smime_cert( + user_id="xyz", + send_as_email=None, + cert_filename="xyz", + cert_password="xyz", + expire_dt=None, + ) # [END gmail_update_smime_certs] diff --git a/gmail/snippet/smime snippets/update_smime_from_csv.py b/gmail/snippet/smime snippets/update_smime_from_csv.py index 39afa3f7..6e38e07f 100644 --- a/gmail/snippet/smime snippets/update_smime_from_csv.py +++ b/gmail/snippet/smime snippets/update_smime_from_csv.py @@ -9,8 +9,8 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START gmail_update_smime_from_csv] +# [START gmail_update_smime_from_csv] import csv import update_smime_cert @@ -18,34 +18,35 @@ # pylint: disable-this-line-in-some-way def update_smime_from_csv(csv_filename, expire_dt=None): - """Update S/MIME certificates based on the contents of a CSV file. - - Each row of the CSV file should contain a user ID, path to the certificate, - and the certificate password. - - Args: - csv_filename: Name of the CSV file. - expire_dt: DateTime object against which the certificate expiration is - compared. If None, uses the current time. - """ - ret0 = '' - try: - with open(csv_filename, 'rb') as cert: - csv_reader = csv.reader(cert, delimiter=',') - next(csv_reader, None) # skip CSV file header - for row in csv_reader: - user_id = row[0] - ret0 = update_smime_cert.update_smime_cert( - user_id, - send_as_email=user_id, - cert_filename=row[1], - cert_password=row[2], - expire_dt=expire_dt) - return ret0 - except (OSError, IOError) as error: - print(F'An error occured while reading the CSV file: {error}') - - -if __name__ == '__main__': - update_smime_from_csv(csv_filename='xyz') + """Update S/MIME certificates based on the contents of a CSV file. + + Each row of the CSV file should contain a user ID, path to the certificate, + and the certificate password. + + Args: + csv_filename: Name of the CSV file. + expire_dt: DateTime object against which the certificate expiration is + compared. If None, uses the current time. + """ + ret0 = "" + try: + with open(csv_filename, "rb") as cert: + csv_reader = csv.reader(cert, delimiter=",") + next(csv_reader, None) # skip CSV file header + for row in csv_reader: + user_id = row[0] + ret0 = update_smime_cert.update_smime_cert( + user_id, + send_as_email=user_id, + cert_filename=row[1], + cert_password=row[2], + expire_dt=expire_dt, + ) + return ret0 + except (OSError, IOError) as error: + print(f"An error occured while reading the CSV file: {error}") + + +if __name__ == "__main__": + update_smime_from_csv(csv_filename="xyz") # [END gmail_update_smime_from_csv] diff --git a/gmail/snippet/thread/test_thread.py b/gmail/snippet/thread/test_thread.py index e57b660d..a365fa28 100644 --- a/gmail/snippet/thread/test_thread.py +++ b/gmail/snippet/thread/test_thread.py @@ -12,20 +12,21 @@ See the License for the specific language governing permissions and limitations under the License. """ + import unittest from threads import show_chatty_threads class TestThreads(unittest.TestCase): - """unit test class for snippets""" + """unit test class for snippets""" - @classmethod - def test_threads(cls): - """to test threads""" - result = show_chatty_threads() - cls.assertIsNotNone(cls, result) + @classmethod + def test_threads(cls): + """to test threads""" + result = show_chatty_threads() + cls.assertIsNotNone(cls, result) -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/gmail/snippet/thread/threads.py b/gmail/snippet/thread/threads.py index bb34f3f3..973316a3 100644 --- a/gmail/snippet/thread/threads.py +++ b/gmail/snippet/thread/threads.py @@ -9,52 +9,54 @@ See the License for the specific language governing permissions and limitations under the License. """ -# [START gmail_show_chatty_threads] - -from __future__ import print_function +# [START gmail_show_chatty_threads] import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def show_chatty_threads(): - """Display threads with long conversations(>= 3 messages) - Return: None - - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - - try: - # create gmail api client - service = build('gmail', 'v1', credentials=creds) - - # pylint: disable=maybe-no-member - # pylint: disable:R1710 - threads = service.users().threads().list(userId='me').execute().get('threads', []) - for thread in threads: - tdata = service.users().threads().get(userId='me', id=thread['id']).execute() - nmsgs = len(tdata['messages']) - - # skip if <3 msgs in thread - if nmsgs > 2: - msg = tdata['messages'][0]['payload'] - subject = '' - for header in msg['headers']: - if header['name'] == 'Subject': - subject = header['value'] - break - if subject: # skip if no Subject line - print(F'- {subject}, {nmsgs}') - return threads - - except HttpError as error: - print(F'An error occurred: {error}') - - -if __name__ == '__main__': - show_chatty_threads() + """Display threads with long conversations(>= 3 messages) + Return: None + + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + + try: + # create gmail api client + service = build("gmail", "v1", credentials=creds) + + # pylint: disable=maybe-no-member + # pylint: disable:R1710 + threads = ( + service.users().threads().list(userId="me").execute().get("threads", []) + ) + for thread in threads: + tdata = ( + service.users().threads().get(userId="me", id=thread["id"]).execute() + ) + nmsgs = len(tdata["messages"]) + + # skip if <3 msgs in thread + if nmsgs > 2: + msg = tdata["messages"][0]["payload"] + subject = "" + for header in msg["headers"]: + if header["name"] == "Subject": + subject = header["value"] + break + if subject: # skip if no Subject line + print(f"- {subject}, {nmsgs}") + return threads + + except HttpError as error: + print(f"An error occurred: {error}") + + +if __name__ == "__main__": + show_chatty_threads() # [END gmail_show_chatty_threads] diff --git a/people/quickstart/quickstart.py b/people/quickstart/quickstart.py index 65a07282..3129e453 100644 --- a/people/quickstart/quickstart.py +++ b/people/quickstart/quickstart.py @@ -13,8 +13,6 @@ # limitations under the License. # [START people_quickstart] -from __future__ import print_function - import os.path from google.auth.transport.requests import Request @@ -24,51 +22,58 @@ from googleapiclient.errors import HttpError # If modifying these scopes, delete the file token.json. -SCOPES = ['https://www.googleapis.com/auth/contacts.readonly'] +SCOPES = ["https://www.googleapis.com/auth/contacts.readonly"] def main(): - """Shows basic usage of the People API. - Prints the name of the first 10 connections. - """ - creds = None - # The file token.json stores the user's access and refresh tokens, and is - # created automatically when the authorization flow completes for the first - # time. - if os.path.exists('token.json'): - creds = Credentials.from_authorized_user_file('token.json', SCOPES) - # If there are no (valid) credentials available, let the user log in. - if not creds or not creds.valid: - if creds and creds.expired and creds.refresh_token: - creds.refresh(Request()) - else: - flow = InstalledAppFlow.from_client_secrets_file( - 'credentials.json', SCOPES) - creds = flow.run_local_server(port=0) - # Save the credentials for the next run - with open('token.json', 'w') as token: - token.write(creds.to_json()) + """Shows basic usage of the People API. + Prints the name of the first 10 connections. + """ + creds = None + # The file token.json stores the user's access and refresh tokens, and is + # created automatically when the authorization flow completes for the first + # time. + if os.path.exists("token.json"): + creds = Credentials.from_authorized_user_file("token.json", SCOPES) + # If there are no (valid) credentials available, let the user log in. + if not creds or not creds.valid: + if creds and creds.expired and creds.refresh_token: + creds.refresh(Request()) + else: + flow = InstalledAppFlow.from_client_secrets_file( + "credentials.json", SCOPES + ) + creds = flow.run_local_server(port=0) + # Save the credentials for the next run + with open("token.json", "w") as token: + token.write(creds.to_json()) - try: - service = build('people', 'v1', credentials=creds) + try: + service = build("people", "v1", credentials=creds) - # Call the People API - print('List 10 connection names') - results = service.people().connections().list( - resourceName='people/me', + # Call the People API + print("List 10 connection names") + results = ( + service.people() + .connections() + .list( + resourceName="people/me", pageSize=10, - personFields='names,emailAddresses').execute() - connections = results.get('connections', []) + personFields="names,emailAddresses", + ) + .execute() + ) + connections = results.get("connections", []) - for person in connections: - names = person.get('names', []) - if names: - name = names[0].get('displayName') - print(name) - except HttpError as err: - print(err) + for person in connections: + names = person.get("names", []) + if names: + name = names[0].get("displayName") + print(name) + except HttpError as err: + print(err) -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() # [END people_quickstart] diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 00000000..eaaa7420 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,5 @@ +[tool.pyink] +line-length = 80 +preview = true +pyink-indentation = 2 +pyink-use-majority-quotes = true \ No newline at end of file diff --git a/sheets/quickstart/quickstart.py b/sheets/quickstart/quickstart.py index 236ab878..6cb90a21 100644 --- a/sheets/quickstart/quickstart.py +++ b/sheets/quickstart/quickstart.py @@ -13,8 +13,6 @@ # limitations under the License. # [START sheets_quickstart] -from __future__ import print_function - import os.path from google.auth.transport.requests import Request @@ -24,56 +22,60 @@ from googleapiclient.errors import HttpError # If modifying these scopes, delete the file token.json. -SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'] +SCOPES = ["https://www.googleapis.com/auth/spreadsheets.readonly"] # The ID and range of a sample spreadsheet. -SAMPLE_SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms' -SAMPLE_RANGE_NAME = 'Class Data!A2:E' +SAMPLE_SPREADSHEET_ID = "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms" +SAMPLE_RANGE_NAME = "Class Data!A2:E" def main(): - """Shows basic usage of the Sheets API. - Prints values from a sample spreadsheet. - """ - creds = None - # The file token.json stores the user's access and refresh tokens, and is - # created automatically when the authorization flow completes for the first - # time. - if os.path.exists('token.json'): - creds = Credentials.from_authorized_user_file('token.json', SCOPES) - # If there are no (valid) credentials available, let the user log in. - if not creds or not creds.valid: - if creds and creds.expired and creds.refresh_token: - creds.refresh(Request()) - else: - flow = InstalledAppFlow.from_client_secrets_file( - 'credentials.json', SCOPES) - creds = flow.run_local_server(port=0) - # Save the credentials for the next run - with open('token.json', 'w') as token: - token.write(creds.to_json()) + """Shows basic usage of the Sheets API. + Prints values from a sample spreadsheet. + """ + creds = None + # The file token.json stores the user's access and refresh tokens, and is + # created automatically when the authorization flow completes for the first + # time. + if os.path.exists("token.json"): + creds = Credentials.from_authorized_user_file("token.json", SCOPES) + # If there are no (valid) credentials available, let the user log in. + if not creds or not creds.valid: + if creds and creds.expired and creds.refresh_token: + creds.refresh(Request()) + else: + flow = InstalledAppFlow.from_client_secrets_file( + "credentials.json", SCOPES + ) + creds = flow.run_local_server(port=0) + # Save the credentials for the next run + with open("token.json", "w") as token: + token.write(creds.to_json()) - try: - service = build('sheets', 'v4', credentials=creds) + try: + service = build("sheets", "v4", credentials=creds) - # Call the Sheets API - sheet = service.spreadsheets() - result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID, - range=SAMPLE_RANGE_NAME).execute() - values = result.get('values', []) + # Call the Sheets API + sheet = service.spreadsheets() + result = ( + sheet.values() + .get(spreadsheetId=SAMPLE_SPREADSHEET_ID, range=SAMPLE_RANGE_NAME) + .execute() + ) + values = result.get("values", []) - if not values: - print('No data found.') - return + if not values: + print("No data found.") + return - print('Name, Major:') - for row in values: - # Print columns A and E, which correspond to indices 0 and 4. - print('%s, %s' % (row[0], row[4])) - except HttpError as err: - print(err) + print("Name, Major:") + for row in values: + # Print columns A and E, which correspond to indices 0 and 4. + print(f"{row[0]}, {row[4]}") + except HttpError as err: + print(err) -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() # [END sheets_quickstart] diff --git a/sheets/snippets/base_test.py b/sheets/snippets/base_test.py index 4f189163..56ea3116 100644 --- a/sheets/snippets/base_test.py +++ b/sheets/snippets/base_test.py @@ -12,8 +12,6 @@ # See the License for the specific language governing permissions and # limitations under the License. -from __future__ import print_function - import sys import unittest @@ -24,75 +22,74 @@ class BaseTest(unittest.TestCase): - @classmethod - def setUpClass(cls): - cls.credentials = cls.create_credentials() - http = cls.credentials.authorize(httplib2.Http()) - cls.credentials.refresh(http) - cls.service = build('sheets', 'v4', http=http) - cls.drive_service = build('drive', 'v3', http=http) - # Hide STDOUT output generated by snippets. - cls.stdout = sys.stdout - sys.stdout = None - @classmethod - def tearDownClass(cls): - # Restore STDOUT. - sys.stdout = cls.stdout + @classmethod + def setUpClass(cls): + cls.credentials = cls.create_credentials() + http = cls.credentials.authorize(httplib2.Http()) + cls.credentials.refresh(http) + cls.service = build("sheets", "v4", http=http) + cls.drive_service = build("drive", "v3", http=http) + # Hide STDOUT output generated by snippets. + cls.stdout = sys.stdout + sys.stdout = None - @classmethod - def create_credentials(cls): - cls.credentials = GoogleCredentials.get_application_default() - scope = ['https://www.googleapis.com/auth/drive'] - return cls.credentials.create_scoped(scope) + @classmethod + def tearDownClass(cls): + # Restore STDOUT. + sys.stdout = cls.stdout - def setUp(self): - self.files_to_delete = [] + @classmethod + def create_credentials(cls): + cls.credentials = GoogleCredentials.get_application_default() + scope = ["https://www.googleapis.com/auth/drive"] + return cls.credentials.create_scoped(scope) - def tearDown(self): - for file_id in self.files_to_delete: - try: - self.drive_service.files().delete(fileId=file_id).execute() - except errors.HttpError: - print('Unable to delete file %s' % file_id, file=sys.stderr) + def setUp(self): + self.files_to_delete = [] - def delete_file_on_cleanup(self, file_id): - self.files_to_delete.append(file_id) + def tearDown(self): + for file_id in self.files_to_delete: + try: + self.drive_service.files().delete(fileId=file_id).execute() + except errors.HttpError: + print(f"Unable to delete file {file_id}", file=sys.stderr) - def create_test_spreadsheet(self): - spreadsheet = { - 'properties': { - 'title': 'Sales Report' - } - } - spreadsheet = self.service.spreadsheets().create(body=spreadsheet, - fields='spreadsheetId').execute() - self.delete_file_on_cleanup(spreadsheet.get('spreadsheetId')) - return spreadsheet.get('spreadsheetId') + def delete_file_on_cleanup(self, file_id): + self.files_to_delete.append(file_id) - def populate_values(self, spreadsheet_id): - body = { - 'requests': [{ - 'repeatCell': { - 'range': { - 'sheetId': 0, - 'startRowIndex': 0, - 'endRowIndex': 10, - 'startColumnIndex': 0, - 'endColumnIndex': 10 - }, - 'cell': { - 'userEnteredValue': { - 'stringValue': 'Hello' - } + def create_test_spreadsheet(self): + spreadsheet = {"properties": {"title": "Sales Report"}} + spreadsheet = ( + self.service.spreadsheets() + .create(body=spreadsheet, fields="spreadsheetId") + .execute() + ) + self.delete_file_on_cleanup(spreadsheet.get("spreadsheetId")) + return spreadsheet.get("spreadsheetId") + + def populate_values(self, spreadsheet_id): + body = { + "requests": [ + { + "repeatCell": { + "range": { + "sheetId": 0, + "startRowIndex": 0, + "endRowIndex": 10, + "startColumnIndex": 0, + "endColumnIndex": 10, }, - 'fields': 'userEnteredValue' + "cell": {"userEnteredValue": {"stringValue": "Hello"}}, + "fields": "userEnteredValue", } - }] - } - self.service.spreadsheets().batchUpdate( - spreadsheetId=spreadsheet_id, body=body).execute() + } + ] + } + self.service.spreadsheets().batchUpdate( + spreadsheetId=spreadsheet_id, body=body + ).execute() -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/sheets/snippets/sheets_append_values.py b/sheets/snippets/sheets_append_values.py index f86c18b0..3fba74f5 100644 --- a/sheets/snippets/sheets_append_values.py +++ b/sheets/snippets/sheets_append_values.py @@ -15,55 +15,58 @@ """ # [START sheets_append_values] -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError -def append_values(spreadsheet_id, range_name, value_input_option, - _values): - """ - Creates the batch_update the user has access to. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - # pylint: disable=maybe-no-member - try: - service = build('sheets', 'v4', credentials=creds) +def append_values(spreadsheet_id, range_name, value_input_option, _values): + """ + Creates the batch_update the user has access to. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + # pylint: disable=maybe-no-member + try: + service = build("sheets", "v4", credentials=creds) - values = [ - [ - # Cell values ... - ], - # Additional rows ... - ] - # [START_EXCLUDE silent] - values = _values - # [END_EXCLUDE] - body = { - 'values': values - } - result = service.spreadsheets().values().append( - spreadsheetId=spreadsheet_id, range=range_name, - valueInputOption=value_input_option, body=body).execute() - print(f"{(result.get('updates').get('updatedCells'))} cells appended.") - return result + values = [ + [ + # Cell values ... + ], + # Additional rows ... + ] + # [START_EXCLUDE silent] + values = _values + # [END_EXCLUDE] + body = {"values": values} + result = ( + service.spreadsheets() + .values() + .append( + spreadsheetId=spreadsheet_id, + range=range_name, + valueInputOption=value_input_option, + body=body, + ) + .execute() + ) + print(f"{(result.get('updates').get('updatedCells'))} cells appended.") + return result - except HttpError as error: - print(f"An error occurred: {error}") - return error + except HttpError as error: + print(f"An error occurred: {error}") + return error -if __name__ == '__main__': - # Pass: spreadsheet_id, range_name value_input_option and _values) - append_values("1CM29gwKIzeXsAppeNwrc8lbYaVMmUclprLuLYuHog4k", - "A1:C2", "USER_ENTERED", - [ - ['F', 'B'], - ['C', 'D'] - ]) - # [END sheets_append_values] +if __name__ == "__main__": + # Pass: spreadsheet_id, range_name value_input_option and _values) + append_values( + "1CM29gwKIzeXsAppeNwrc8lbYaVMmUclprLuLYuHog4k", + "A1:C2", + "USER_ENTERED", + [["F", "B"], ["C", "D"]], + ) + # [END sheets_append_values] diff --git a/sheets/snippets/sheets_batch_get_values.py b/sheets/snippets/sheets_batch_get_values.py index 3f186fd2..65666839 100644 --- a/sheets/snippets/sheets_batch_get_values.py +++ b/sheets/snippets/sheets_batch_get_values.py @@ -15,42 +15,44 @@ """ # [START sheets_batch_get_values] -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def batch_get_values(spreadsheet_id, _range_names): - """ - Creates the batch_update the user has access to. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - # pylint: disable=maybe-no-member - try: - service = build('sheets', 'v4', credentials=creds) - range_names = [ - # Range names ... - ] - # [START_EXCLUDE silent] - range_names = _range_names - # [END_EXCLUDE] - result = service.spreadsheets().values().batchGet( - spreadsheetId=spreadsheet_id, ranges=range_names).execute() - ranges = result.get('valueRanges', []) - print(f"{len(ranges)} ranges retrieved") - return result - except HttpError as error: - print(f"An error occurred: {error}") - return error - - -if __name__ == '__main__': - # Pass: spreadsheet_id, and range_name - - batch_get_values("1CM29gwKIzeXsAppeNwrc8lbYaVMmUclprLuLYuHog4k", "A1:C2") - # [END sheets_batch_get_values] + """ + Creates the batch_update the user has access to. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + # pylint: disable=maybe-no-member + try: + service = build("sheets", "v4", credentials=creds) + range_names = [ + # Range names ... + ] + # [START_EXCLUDE silent] + range_names = _range_names + # [END_EXCLUDE] + result = ( + service.spreadsheets() + .values() + .batchGet(spreadsheetId=spreadsheet_id, ranges=range_names) + .execute() + ) + ranges = result.get("valueRanges", []) + print(f"{len(ranges)} ranges retrieved") + return result + except HttpError as error: + print(f"An error occurred: {error}") + return error + + +if __name__ == "__main__": + # Pass: spreadsheet_id, and range_name + + batch_get_values("1CM29gwKIzeXsAppeNwrc8lbYaVMmUclprLuLYuHog4k", "A1:C2") + # [END sheets_batch_get_values] diff --git a/sheets/snippets/sheets_batch_update.py b/sheets/snippets/sheets_batch_update.py index fcab4cda..037db84c 100644 --- a/sheets/snippets/sheets_batch_update.py +++ b/sheets/snippets/sheets_batch_update.py @@ -12,69 +12,68 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - """ -# [START sheets_batch_update] - -from __future__ import print_function +# [START sheets_batch_update] import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def sheets_batch_update(spreadsheet_id, title, find, replacement): - - """ - Update the sheet details in batch, the user has access to. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - - creds, _ = google.auth.default() - # pylint: disable=maybe-no-member - - try: - service = build('sheets', 'v4', credentials=creds) - - requests = [] - # Change the spreadsheet's title. - requests.append({ - 'updateSpreadsheetProperties': { - 'properties': { - 'title': title - }, - 'fields': 'title' + """ + Update the sheet details in batch, the user has access to. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + + creds, _ = google.auth.default() + # pylint: disable=maybe-no-member + + try: + service = build("sheets", "v4", credentials=creds) + + requests = [] + # Change the spreadsheet's title. + requests.append( + { + "updateSpreadsheetProperties": { + "properties": {"title": title}, + "fields": "title", } - }) - # Find and replace text - requests.append({ - 'findReplace': { - 'find': find, - 'replacement': replacement, - 'allSheets': True + } + ) + # Find and replace text + requests.append( + { + "findReplace": { + "find": find, + "replacement": replacement, + "allSheets": True, } - }) - # Add additional requests (operations) ... - - body = { - 'requests': requests } - response = service.spreadsheets().batchUpdate( - spreadsheetId=spreadsheet_id, - body=body).execute() - find_replace_response = response.get('replies')[1].get('findReplace') - print('{0} replacements made.'.format( - find_replace_response.get('occurrencesChanged'))) - return response - - except HttpError as error: - print(f"An error occurred: {error}") - return error - - -if __name__ == '__main__': - sheets_batch_update('spreadsheet_id', 'title', 'find', 'replacement') + ) + # Add additional requests (operations) ... + + body = {"requests": requests} + response = ( + service.spreadsheets() + .batchUpdate(spreadsheetId=spreadsheet_id, body=body) + .execute() + ) + find_replace_response = response.get("replies")[1].get("findReplace") + print( + f"{find_replace_response.get('occurrencesChanged')} replacements made." + ) + return response + + except HttpError as error: + print(f"An error occurred: {error}") + return error + + +if __name__ == "__main__": + sheets_batch_update("spreadsheet_id", "title", "find", "replacement") # [END sheets_batch_update] diff --git a/sheets/snippets/sheets_batch_update_values.py b/sheets/snippets/sheets_batch_update_values.py index 745621de..c125ccbd 100644 --- a/sheets/snippets/sheets_batch_update_values.py +++ b/sheets/snippets/sheets_batch_update_values.py @@ -15,61 +15,58 @@ """ # [START sheets_batch_update_values] -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError -def batch_update_values(spreadsheet_id, range_name, - value_input_option, _values): - """ - Creates the batch_update the user has access to. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - # pylint: disable=maybe-no-member - try: - service = build('sheets', 'v4', credentials=creds) +def batch_update_values( + spreadsheet_id, range_name, value_input_option, _values +): + """ + Creates the batch_update the user has access to. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + # pylint: disable=maybe-no-member + try: + service = build("sheets", "v4", credentials=creds) - values = [ - [ - # Cell values ... - ], - # Additional rows - ] - # [START_EXCLUDE silent] - values = _values - # [END_EXCLUDE] - data = [ - { - 'range': range_name, - 'values': values - }, - # Additional ranges to update ... - ] - body = { - 'valueInputOption': value_input_option, - 'data': data - } - result = service.spreadsheets().values().batchUpdate( - spreadsheetId=spreadsheet_id, body=body).execute() - print(f"{(result.get('totalUpdatedCells'))} cells updated.") - return result - except HttpError as error: - print(f"An error occurred: {error}") - return error + values = [ + [ + # Cell values ... + ], + # Additional rows + ] + # [START_EXCLUDE silent] + values = _values + # [END_EXCLUDE] + data = [ + {"range": range_name, "values": values}, + # Additional ranges to update ... + ] + body = {"valueInputOption": value_input_option, "data": data} + result = ( + service.spreadsheets() + .values() + .batchUpdate(spreadsheetId=spreadsheet_id, body=body) + .execute() + ) + print(f"{(result.get('totalUpdatedCells'))} cells updated.") + return result + except HttpError as error: + print(f"An error occurred: {error}") + return error -if __name__ == '__main__': - # Pass: spreadsheet_id, range_name value_input_option and _values) - batch_update_values("1CM29gwKIzeXsAppeNwrc8lbYaVMmUclprLuLYuHog4k", - "A1:C2", "USER_ENTERED", - [ - ['F', 'B'], - ['C', 'D'] - ]) - # [END sheets_batch_update_values] +if __name__ == "__main__": + # Pass: spreadsheet_id, range_name value_input_option and _values) + batch_update_values( + "1CM29gwKIzeXsAppeNwrc8lbYaVMmUclprLuLYuHog4k", + "A1:C2", + "USER_ENTERED", + [["F", "B"], ["C", "D"]], + ) + # [END sheets_batch_update_values] diff --git a/sheets/snippets/sheets_conditional_formatting.py b/sheets/snippets/sheets_conditional_formatting.py index e4ae979f..d8951f1d 100644 --- a/sheets/snippets/sheets_conditional_formatting.py +++ b/sheets/snippets/sheets_conditional_formatting.py @@ -15,91 +15,97 @@ """ # [START sheets_conditional_formatting] -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def conditional_formatting(spreadsheet_id): - """ - Creates the batch_update the user has access to. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - # pylint: disable=maybe-no-member - try: - service = build('sheets', 'v4', credentials=creds) + """ + Creates the batch_update the user has access to. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + # pylint: disable=maybe-no-member + try: + service = build("sheets", "v4", credentials=creds) - my_range = { - 'sheetId': 0, - 'startRowIndex': 1, - 'endRowIndex': 11, - 'startColumnIndex': 0, - 'endColumnIndex': 4, - } - requests = [{ - 'addConditionalFormatRule': { - 'rule': { - 'ranges': [my_range], - 'booleanRule': { - 'condition': { - 'type': 'CUSTOM_FORMULA', - 'values': [{ - 'userEnteredValue': - '=GT($D2,median($D$2:$D$11))' - }] + my_range = { + "sheetId": 0, + "startRowIndex": 1, + "endRowIndex": 11, + "startColumnIndex": 0, + "endColumnIndex": 4, + } + requests = [ + { + "addConditionalFormatRule": { + "rule": { + "ranges": [my_range], + "booleanRule": { + "condition": { + "type": "CUSTOM_FORMULA", + "values": [ + { + "userEnteredValue": ( + "=GT($D2,median($D$2:$D$11))" + ) + } + ], }, - 'format': { - 'textFormat': { - 'foregroundColor': {'red': 0.8} - } - } - } + "format": { + "textFormat": {"foregroundColor": {"red": 0.8}} + }, + }, }, - 'index': 0 + "index": 0, } - }, { - 'addConditionalFormatRule': { - 'rule': { - 'ranges': [my_range], - 'booleanRule': { - 'condition': { - 'type': 'CUSTOM_FORMULA', - 'values': [{ - 'userEnteredValue': - '=LT($D2,median($D$2:$D$11))' - }] + }, + { + "addConditionalFormatRule": { + "rule": { + "ranges": [my_range], + "booleanRule": { + "condition": { + "type": "CUSTOM_FORMULA", + "values": [ + { + "userEnteredValue": ( + "=LT($D2,median($D$2:$D$11))" + ) + } + ], }, - 'format': { - 'backgroundColor': { - 'red': 1, - 'green': 0.4, - 'blue': 0.4 + "format": { + "backgroundColor": { + "red": 1, + "green": 0.4, + "blue": 0.4, } - } - } + }, + }, }, - 'index': 0 + "index": 0, } - }] - body = { - 'requests': requests - } - response = service.spreadsheets() \ - .batchUpdate(spreadsheetId=spreadsheet_id, body=body).execute() - print(f"{(len(response.get('replies')))} cells updated.") - return response + }, + ] + body = {"requests": requests} + response = ( + service.spreadsheets() + .batchUpdate(spreadsheetId=spreadsheet_id, body=body) + .execute() + ) + print(f"{(len(response.get('replies')))} cells updated.") + return response - except HttpError as error: - print(f"An error occurred: {error}") - return error + except HttpError as error: + print(f"An error occurred: {error}") + return error -if __name__ == '__main__': - # Pass: spreadsheet_id - conditional_formatting("1CM29gwKIzeXsAppeNwrc8lbYaVMmUclprLuLYuHog4k") - # [END sheets_conditional_formatting] +if __name__ == "__main__": + # Pass: spreadsheet_id + conditional_formatting("1CM29gwKIzeXsAppeNwrc8lbYaVMmUclprLuLYuHog4k") + # [END sheets_conditional_formatting] diff --git a/sheets/snippets/sheets_create.py b/sheets/snippets/sheets_create.py index c9ddce27..20585f12 100644 --- a/sheets/snippets/sheets_create.py +++ b/sheets/snippets/sheets_create.py @@ -15,40 +15,36 @@ """ # [START sheets_create] -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def create(title): - """ - Creates the Sheet the user has access to. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - # pylint: disable=maybe-no-member - try: - service = build('sheets', 'v4', credentials=creds) - spreadsheet = { - 'properties': { - 'title': title - } - } - spreadsheet = service.spreadsheets().create(body=spreadsheet, - fields='spreadsheetId') \ - .execute() - print(f"Spreadsheet ID: {(spreadsheet.get('spreadsheetId'))}") - return spreadsheet.get('spreadsheetId') - except HttpError as error: - print(f"An error occurred: {error}") - return error - - -if __name__ == '__main__': - # Pass: title - create("mysheet1") - # [END sheets_create] + """ + Creates the Sheet the user has access to. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + # pylint: disable=maybe-no-member + try: + service = build("sheets", "v4", credentials=creds) + spreadsheet = {"properties": {"title": title}} + spreadsheet = ( + service.spreadsheets() + .create(body=spreadsheet, fields="spreadsheetId") + .execute() + ) + print(f"Spreadsheet ID: {(spreadsheet.get('spreadsheetId'))}") + return spreadsheet.get("spreadsheetId") + except HttpError as error: + print(f"An error occurred: {error}") + return error + + +if __name__ == "__main__": + # Pass: title + create("mysheet1") + # [END sheets_create] diff --git a/sheets/snippets/sheets_filter_views.py b/sheets/snippets/sheets_filter_views.py index 16a7bdfa..d11fbbcf 100644 --- a/sheets/snippets/sheets_filter_views.py +++ b/sheets/snippets/sheets_filter_views.py @@ -15,106 +15,102 @@ """ # [START sheets_filter_views] -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def filter_views(spreadsheet_id): - """ - Creates the batch_update the user has access to. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - # pylint: disable=maybe-no-member - try: - service = build('sheets', 'v4', credentials=creds) + """ + Creates the batch_update the user has access to. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + # pylint: disable=maybe-no-member + try: + service = build("sheets", "v4", credentials=creds) - my_range = { - 'sheetId': 0, - 'startRowIndex': 0, - 'startColumnIndex': 0, - } - addfilterviewrequest = { - 'addFilterView': { - 'filter': { - 'title': 'Sample Filter', - 'range': my_range, - 'sortSpecs': [{ - 'dimensionIndex': 3, - 'sortOrder': 'DESCENDING' - }], - 'criteria': { - 0: { - 'hiddenValues': ['Panel'] - }, - 6: { - 'condition': { - 'type': 'DATE_BEFORE', - 'values': { - 'userEnteredValue': '4/30/2016' - } - } + my_range = { + "sheetId": 0, + "startRowIndex": 0, + "startColumnIndex": 0, + } + addfilterviewrequest = { + "addFilterView": { + "filter": { + "title": "Sample Filter", + "range": my_range, + "sortSpecs": [{"dimensionIndex": 3, "sortOrder": "DESCENDING"}], + "criteria": { + 0: {"hiddenValues": ["Panel"]}, + 6: { + "condition": { + "type": "DATE_BEFORE", + "values": {"userEnteredValue": "4/30/2016"}, } - } - } + }, + }, } } + } - body = {'requests': [addfilterviewrequest]} - addfilterviewresponse = service.spreadsheets() \ - .batchUpdate(spreadsheetId=spreadsheet_id, body=body).execute() + body = {"requests": [addfilterviewrequest]} + addfilterviewresponse = ( + service.spreadsheets() + .batchUpdate(spreadsheetId=spreadsheet_id, body=body) + .execute() + ) - duplicatefilterviewrequest = { - 'duplicateFilterView': { - 'filterId': - addfilterviewresponse['replies'][0] - ['addFilterView']['filter'] - ['filterViewId'] - } + duplicatefilterviewrequest = { + "duplicateFilterView": { + "filterId": addfilterviewresponse["replies"][0]["addFilterView"][ + "filter" + ]["filterViewId"] } + } - body = {'requests': [duplicatefilterviewrequest]} - duplicatefilterviewresponse = service.spreadsheets() \ - .batchUpdate(spreadsheetId=spreadsheet_id, body=body).execute() + body = {"requests": [duplicatefilterviewrequest]} + duplicatefilterviewresponse = ( + service.spreadsheets() + .batchUpdate(spreadsheetId=spreadsheet_id, body=body) + .execute() + ) - updatefilterviewrequest = { - 'updateFilterView': { - 'filter': { - 'filterViewId': duplicatefilterviewresponse['replies'][0] - ['duplicateFilterView']['filter']['filterViewId'], - 'title': 'Updated Filter', - 'criteria': { - 0: {}, - 3: { - 'condition': { - 'type': 'NUMBER_GREATER', - 'values': { - 'userEnteredValue': '5' - } - } + updatefilterviewrequest = { + "updateFilterView": { + "filter": { + "filterViewId": duplicatefilterviewresponse["replies"][0][ + "duplicateFilterView" + ]["filter"]["filterViewId"], + "title": "Updated Filter", + "criteria": { + 0: {}, + 3: { + "condition": { + "type": "NUMBER_GREATER", + "values": {"userEnteredValue": "5"}, } - } + }, }, - 'fields': { - 'paths': ['criteria', 'title'] - } - } + }, + "fields": {"paths": ["criteria", "title"]}, } + } - body = {'requests': [updatefilterviewrequest]} - updatefilterviewresponse = service.spreadsheets() \ - .batchUpdate(spreadsheetId=spreadsheet_id, body=body).execute() - print(str(updatefilterviewresponse)) - except HttpError as error: - print(f"An error occurred: {error}") + body = {"requests": [updatefilterviewrequest]} + updatefilterviewresponse = ( + service.spreadsheets() + .batchUpdate(spreadsheetId=spreadsheet_id, body=body) + .execute() + ) + print(str(updatefilterviewresponse)) + except HttpError as error: + print(f"An error occurred: {error}") -if __name__ == '__main__': - # Pass: spreadsheet_id - filter_views("1CM29gwKIzeXsAppeNwrc8lbYaVMmUclprLuLYuHog4k") - # [END sheets_filter_views] +if __name__ == "__main__": + # Pass: spreadsheet_id + filter_views("1CM29gwKIzeXsAppeNwrc8lbYaVMmUclprLuLYuHog4k") + # [END sheets_filter_views] diff --git a/sheets/snippets/sheets_get_values.py b/sheets/snippets/sheets_get_values.py index 75f55395..d0d46d6a 100644 --- a/sheets/snippets/sheets_get_values.py +++ b/sheets/snippets/sheets_get_values.py @@ -15,36 +15,38 @@ """ # [START sheets_get_values] -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def get_values(spreadsheet_id, range_name): - """ - Creates the batch_update the user has access to. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - # pylint: disable=maybe-no-member - try: - service = build('sheets', 'v4', credentials=creds) - - result = service.spreadsheets().values().get( - spreadsheetId=spreadsheet_id, range=range_name).execute() - rows = result.get('values', []) - print(f"{len(rows)} rows retrieved") - return result - except HttpError as error: - print(f"An error occurred: {error}") - return error - - -if __name__ == '__main__': - # Pass: spreadsheet_id, and range_name - get_values("1CM29gwKIzeXsAppeNwrc8lbYaVMmUclprLuLYuHog4k", "A1:C2") - # [END sheets_get_values] + """ + Creates the batch_update the user has access to. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + # pylint: disable=maybe-no-member + try: + service = build("sheets", "v4", credentials=creds) + + result = ( + service.spreadsheets() + .values() + .get(spreadsheetId=spreadsheet_id, range=range_name) + .execute() + ) + rows = result.get("values", []) + print(f"{len(rows)} rows retrieved") + return result + except HttpError as error: + print(f"An error occurred: {error}") + return error + + +if __name__ == "__main__": + # Pass: spreadsheet_id, and range_name + get_values("1CM29gwKIzeXsAppeNwrc8lbYaVMmUclprLuLYuHog4k", "A1:C2") + # [END sheets_get_values] diff --git a/sheets/snippets/sheets_pivot_tables.py b/sheets/snippets/sheets_pivot_tables.py index fd3ad5a0..86524c32 100644 --- a/sheets/snippets/sheets_pivot_tables.py +++ b/sheets/snippets/sheets_pivot_tables.py @@ -15,101 +15,100 @@ """ # [START sheets_pivot_tables] -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def pivot_tables(spreadsheet_id): - """ - Creates the batch_update the user has access to. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - # pylint: disable=maybe-no-member - try: - service = build('sheets', 'v4', credentials=creds) - # Create two sheets for our pivot table. - body = { - 'requests': [{ - 'addSheet': {} - }, { - 'addSheet': {} - }] - } - batch_update_response = service.spreadsheets() \ - .batchUpdate(spreadsheetId=spreadsheet_id, body=body).execute() - source_sheet_id = batch_update_response.get('replies')[0] \ - .get('addSheet').get('properties').get('sheetId') - target_sheet_id = batch_update_response.get('replies')[1] \ - .get('addSheet').get('properties').get('sheetId') - requests = [] - requests.append({ - 'updateCells': { - 'rows': { - 'values': [ + """ + Creates the batch_update the user has access to. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + # pylint: disable=maybe-no-member + try: + service = build("sheets", "v4", credentials=creds) + # Create two sheets for our pivot table. + body = {"requests": [{"addSheet": {}}, {"addSheet": {}}]} + batch_update_response = ( + service.spreadsheets() + .batchUpdate(spreadsheetId=spreadsheet_id, body=body) + .execute() + ) + source_sheet_id = ( + batch_update_response.get("replies")[0] + .get("addSheet") + .get("properties") + .get("sheetId") + ) + target_sheet_id = ( + batch_update_response.get("replies")[1] + .get("addSheet") + .get("properties") + .get("sheetId") + ) + requests = [] + requests.append( + { + "updateCells": { + "rows": { + "values": [ { - 'pivotTable': { - 'source': { - 'sheetId': source_sheet_id, - 'startRowIndex': 0, - 'startColumnIndex': 0, - 'endRowIndex': 20, - 'endColumnIndex': 7 + "pivotTable": { + "source": { + "sheetId": source_sheet_id, + "startRowIndex": 0, + "startColumnIndex": 0, + "endRowIndex": 20, + "endColumnIndex": 7, }, - 'rows': [ + "rows": [ { - 'sourceColumnOffset': 1, - 'showTotals': True, - 'sortOrder': 'ASCENDING', - + "sourceColumnOffset": 1, + "showTotals": True, + "sortOrder": "ASCENDING", }, - - ], - 'columns': [ - { - 'sourceColumnOffset': 4, - 'sortOrder': 'ASCENDING', - 'showTotals': True, - - } - ], - 'values': [ - { - 'summarizeFunction': 'COUNTA', - 'sourceColumnOffset': 4 - } ], - 'valueLayout': 'HORIZONTAL' + "columns": [{ + "sourceColumnOffset": 4, + "sortOrder": "ASCENDING", + "showTotals": True, + }], + "values": [{ + "summarizeFunction": "COUNTA", + "sourceColumnOffset": 4, + }], + "valueLayout": "HORIZONTAL", } } ] }, - 'start': { - 'sheetId': target_sheet_id, - 'rowIndex': 0, - 'columnIndex': 0 + "start": { + "sheetId": target_sheet_id, + "rowIndex": 0, + "columnIndex": 0, }, - 'fields': 'pivotTable' + "fields": "pivotTable", } - }) - body = { - 'requests': requests } - response = service.spreadsheets() \ - .batchUpdate(spreadsheetId=spreadsheet_id, body=body).execute() - return response + ) + body = {"requests": requests} + response = ( + service.spreadsheets() + .batchUpdate(spreadsheetId=spreadsheet_id, body=body) + .execute() + ) + return response - except HttpError as error: - print(f"An error occurred: {error}") - return error + except HttpError as error: + print(f"An error occurred: {error}") + return error -if __name__ == '__main__': - # Pass: spreadsheet_id - pivot_tables("1CM29gwKIzeXsAppeNwrc8lbYaVMmUclprLuLYuHog4k") - # [END sheets_pivot_tables] +if __name__ == "__main__": + # Pass: spreadsheet_id + pivot_tables("1CM29gwKIzeXsAppeNwrc8lbYaVMmUclprLuLYuHog4k") + # [END sheets_pivot_tables] diff --git a/sheets/snippets/sheets_update_values.py b/sheets/snippets/sheets_update_values.py index c82bcc5a..962b8cc3 100644 --- a/sheets/snippets/sheets_update_values.py +++ b/sheets/snippets/sheets_update_values.py @@ -15,54 +15,56 @@ """ # [START sheets_update_values] -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError -def update_values(spreadsheet_id, range_name, value_input_option, - _values): - """ - Creates the batch_update the user has access to. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - # pylint: disable=maybe-no-member - try: - - service = build('sheets', 'v4', credentials=creds) - values = [ - [ - # Cell values ... - ], - # Additional rows ... - ] - # [START_EXCLUDE silent] - values = _values - # [END_EXCLUDE] - body = { - 'values': values - } - result = service.spreadsheets().values().update( - spreadsheetId=spreadsheet_id, range=range_name, - valueInputOption=value_input_option, body=body).execute() - print(f"{result.get('updatedCells')} cells updated.") - return result - except HttpError as error: - print(f"An error occurred: {error}") - return error +def update_values(spreadsheet_id, range_name, value_input_option, _values): + """ + Creates the batch_update the user has access to. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + # pylint: disable=maybe-no-member + try: + service = build("sheets", "v4", credentials=creds) + values = [ + [ + # Cell values ... + ], + # Additional rows ... + ] + # [START_EXCLUDE silent] + values = _values + # [END_EXCLUDE] + body = {"values": values} + result = ( + service.spreadsheets() + .values() + .update( + spreadsheetId=spreadsheet_id, + range=range_name, + valueInputOption=value_input_option, + body=body, + ) + .execute() + ) + print(f"{result.get('updatedCells')} cells updated.") + return result + except HttpError as error: + print(f"An error occurred: {error}") + return error -if __name__ == '__main__': - # Pass: spreadsheet_id, range_name, value_input_option and _values - update_values("1CM29gwKIzeXsAppeNwrc8lbYaVMmUclprLuLYuHog4k", - "A1:C2", "USER_ENTERED", - [ - ['A', 'B'], - ['C', 'D'] - ]) - # [END sheets_update_values] +if __name__ == "__main__": + # Pass: spreadsheet_id, range_name, value_input_option and _values + update_values( + "1CM29gwKIzeXsAppeNwrc8lbYaVMmUclprLuLYuHog4k", + "A1:C2", + "USER_ENTERED", + [["A", "B"], ["C", "D"]], + ) + # [END sheets_update_values] diff --git a/sheets/snippets/test_sheets_append_values.py b/sheets/snippets/test_sheets_append_values.py index 3cdfe1a3..1a2257dd 100644 --- a/sheets/snippets/test_sheets_append_values.py +++ b/sheets/snippets/test_sheets_append_values.py @@ -18,25 +18,23 @@ class Testappendvalues(BaseTest): - """Unit test for append value Sheet snippet""" + """Unit test for append value Sheet snippet""" - def test_append_values(self): - """test append values function""" - spreadsheet_id = self.create_test_spreadsheet() - self.populate_values(spreadsheet_id) - result = sheets_append_values.append_values(spreadsheet_id, - 'Sheet1', 'USER_ENTERED', [ - ['A', 'B'], - ['C', 'D'] - ]) - self.assertIsNotNone(result) - self.assertEqual('Sheet1!A1:J10', result.get('tableRange')) - updates = result.get('updates') - self.assertEqual('Sheet1!A11:B12', updates.get('updatedRange')) - self.assertEqual(2, updates.get('updatedRows')) - self.assertEqual(2, updates.get('updatedColumns')) - self.assertEqual(4, updates.get('updatedCells')) + def test_append_values(self): + """test append values function""" + spreadsheet_id = self.create_test_spreadsheet() + self.populate_values(spreadsheet_id) + result = sheets_append_values.append_values( + spreadsheet_id, "Sheet1", "USER_ENTERED", [["A", "B"], ["C", "D"]] + ) + self.assertIsNotNone(result) + self.assertEqual("Sheet1!A1:J10", result.get("tableRange")) + updates = result.get("updates") + self.assertEqual("Sheet1!A11:B12", updates.get("updatedRange")) + self.assertEqual(2, updates.get("updatedRows")) + self.assertEqual(2, updates.get("updatedColumns")) + self.assertEqual(4, updates.get("updatedCells")) if __name__ == "__main__": - unittest.main() + unittest.main() diff --git a/sheets/snippets/test_sheets_batch_get_values.py b/sheets/snippets/test_sheets_batch_get_values.py index aa912f3a..cd87729f 100644 --- a/sheets/snippets/test_sheets_batch_get_values.py +++ b/sheets/snippets/test_sheets_batch_get_values.py @@ -18,21 +18,22 @@ class Testgetvalues(BaseTest): - """Unit test class for get value Sheet snippet""" + """Unit test class for get value Sheet snippet""" - def test_batch_get_values(self): - """test batch get values function""" - spreadsheet_id = self.create_test_spreadsheet() - self.populate_values(spreadsheet_id) - result = sheets_batch_get_values.batch_get_values(spreadsheet_id, - ['A1:A3', 'B1:C1']) - self.assertIsNotNone(result) - valueranges = result.get('valueRanges') - self.assertIsNotNone(valueranges) - self.assertEqual(2, len(valueranges)) - values = valueranges[0].get('values') - self.assertEqual(3, len(values)) + def test_batch_get_values(self): + """test batch get values function""" + spreadsheet_id = self.create_test_spreadsheet() + self.populate_values(spreadsheet_id) + result = sheets_batch_get_values.batch_get_values( + spreadsheet_id, ["A1:A3", "B1:C1"] + ) + self.assertIsNotNone(result) + valueranges = result.get("valueRanges") + self.assertIsNotNone(valueranges) + self.assertEqual(2, len(valueranges)) + values = valueranges[0].get("values") + self.assertEqual(3, len(values)) if __name__ == "__main__": - unittest.main() + unittest.main() diff --git a/sheets/snippets/test_sheets_batch_update.py b/sheets/snippets/test_sheets_batch_update.py index 70550ace..e371e5da 100644 --- a/sheets/snippets/test_sheets_batch_update.py +++ b/sheets/snippets/test_sheets_batch_update.py @@ -19,23 +19,23 @@ class Testbatchupdate(BaseTest): - """Unit test class for Batch update Sheet snippet""" + """Unit test class for Batch update Sheet snippet""" - def test_batch_update(self): - """test_batch_update function """ - spreadsheet_id = sheets_create.create('Title') - self.populate_values(spreadsheet_id) - response = sheets_batch_update.\ - sheets_batch_update(spreadsheet_id, 'New Title', - 'Hello', 'Goodbye') - self.assertIsNotNone(response) - replies = response.get('replies') - self.assertIsNotNone(replies) - self.assertEqual(2, len(replies)) - find_replace_response = replies[1].get('findReplace') - self.assertIsNotNone(find_replace_response) - self.assertEqual(100, find_replace_response.get('occurrencesChanged')) + def test_batch_update(self): + """test_batch_update function""" + spreadsheet_id = sheets_create.create("Title") + self.populate_values(spreadsheet_id) + response = sheets_batch_update.sheets_batch_update( + spreadsheet_id, "New Title", "Hello", "Goodbye" + ) + self.assertIsNotNone(response) + replies = response.get("replies") + self.assertIsNotNone(replies) + self.assertEqual(2, len(replies)) + find_replace_response = replies[1].get("findReplace") + self.assertIsNotNone(find_replace_response) + self.assertEqual(100, find_replace_response.get("occurrencesChanged")) if __name__ == "__main__": - unittest.main() + unittest.main() diff --git a/sheets/snippets/test_sheets_batch_update_values.py b/sheets/snippets/test_sheets_batch_update_values.py index 4701f904..c594a0a8 100644 --- a/sheets/snippets/test_sheets_batch_update_values.py +++ b/sheets/snippets/test_sheets_batch_update_values.py @@ -18,23 +18,20 @@ class Testbatchupdatevalues(BaseTest): - """Unit test for Batch update value Sheet snippet""" + """Unit test for Batch update value Sheet snippet""" - def test_batch_update_values(self): - """batch updates values""" - spreadsheet_id = self.create_test_spreadsheet() - result = sheets_batch_update_values. \ - batch_update_values(spreadsheet_id, - 'A1:B2', 'USER_ENTERED', [ - ['A', 'B'], - ['C', 'D'] - ]) - self.assertIsNotNone(result) - self.assertEqual(1, len(result.get('responses'))) - self.assertEqual(2, result.get('totalUpdatedRows')) - self.assertEqual(2, result.get('totalUpdatedColumns')) - self.assertEqual(4, result.get('totalUpdatedCells')) + def test_batch_update_values(self): + """batch updates values""" + spreadsheet_id = self.create_test_spreadsheet() + result = sheets_batch_update_values.batch_update_values( + spreadsheet_id, "A1:B2", "USER_ENTERED", [["A", "B"], ["C", "D"]] + ) + self.assertIsNotNone(result) + self.assertEqual(1, len(result.get("responses"))) + self.assertEqual(2, result.get("totalUpdatedRows")) + self.assertEqual(2, result.get("totalUpdatedColumns")) + self.assertEqual(4, result.get("totalUpdatedCells")) if __name__ == "__main__": - unittest.main() + unittest.main() diff --git a/sheets/snippets/test_sheets_conditional_formatting.py b/sheets/snippets/test_sheets_conditional_formatting.py index 6003ae10..2bf78657 100644 --- a/sheets/snippets/test_sheets_conditional_formatting.py +++ b/sheets/snippets/test_sheets_conditional_formatting.py @@ -18,16 +18,17 @@ class Testconditionalformatting(BaseTest): - """Unit test for sheets conditional_formatting value Sheet snippet""" + """Unit test for sheets conditional_formatting value Sheet snippet""" - def test_conditional_formatting(self): - """sheets_conditional_formatting function""" - spreadsheet_id = self.create_test_spreadsheet() - self.populate_values(spreadsheet_id) - response = sheets_conditional_formatting.\ - conditional_formatting(spreadsheet_id) - self.assertEqual(2, len(response.get('replies'))) + def test_conditional_formatting(self): + """sheets_conditional_formatting function""" + spreadsheet_id = self.create_test_spreadsheet() + self.populate_values(spreadsheet_id) + response = sheets_conditional_formatting.conditional_formatting( + spreadsheet_id + ) + self.assertEqual(2, len(response.get("replies"))) if __name__ == "__main__": - unittest.main() + unittest.main() diff --git a/sheets/snippets/test_sheets_create.py b/sheets/snippets/test_sheets_create.py index f6aa236a..3ac529e5 100644 --- a/sheets/snippets/test_sheets_create.py +++ b/sheets/snippets/test_sheets_create.py @@ -18,13 +18,14 @@ class Testsheetscreate(BaseTest): - """Unit test class for Create Sheet snippet""" - def test_create(self): - """sheet function for Create sheet """ - spreadsheet_id = sheets_create.create('Title') - self.assertIsNotNone(spreadsheet_id) - self.delete_file_on_cleanup(spreadsheet_id) + """Unit test class for Create Sheet snippet""" + + def test_create(self): + """sheet function for Create sheet""" + spreadsheet_id = sheets_create.create("Title") + self.assertIsNotNone(spreadsheet_id) + self.delete_file_on_cleanup(spreadsheet_id) if __name__ == "__main__": - unittest.main() + unittest.main() diff --git a/sheets/snippets/test_sheets_filter_views.py b/sheets/snippets/test_sheets_filter_views.py index d09b7eab..6ccc1d71 100644 --- a/sheets/snippets/test_sheets_filter_views.py +++ b/sheets/snippets/test_sheets_filter_views.py @@ -18,14 +18,14 @@ class Testfilterviews(BaseTest): - """Unit test for sheets conditional_formatting value Sheet snippet""" + """Unit test for sheets conditional_formatting value Sheet snippet""" - def test_filter_views(self): - """test filter view function""" - spreadsheet_id = self.create_test_spreadsheet() - self.populate_values(spreadsheet_id) - sheets_filter_views.filter_views(spreadsheet_id) + def test_filter_views(self): + """test filter view function""" + spreadsheet_id = self.create_test_spreadsheet() + self.populate_values(spreadsheet_id) + sheets_filter_views.filter_views(spreadsheet_id) if __name__ == "__main__": - unittest.main() + unittest.main() diff --git a/sheets/snippets/test_sheets_get_values.py b/sheets/snippets/test_sheets_get_values.py index 329e1739..912914e6 100644 --- a/sheets/snippets/test_sheets_get_values.py +++ b/sheets/snippets/test_sheets_get_values.py @@ -18,19 +18,19 @@ class Testgetvalues(BaseTest): - """Unit test class for get value Sheet snippet""" + """Unit test class for get value Sheet snippet""" - def test_get_values(self): - """test_get_values""" - spreadsheet_id = self.create_test_spreadsheet() - self.populate_values(spreadsheet_id) - result = sheets_get_values.get_values(spreadsheet_id, 'A1:C2') - self.assertIsNotNone(result) - values = result.get('values') - self.assertIsNotNone(values) - self.assertEqual(2, len(values)) - self.assertEqual(3, len(values[0])) + def test_get_values(self): + """test_get_values""" + spreadsheet_id = self.create_test_spreadsheet() + self.populate_values(spreadsheet_id) + result = sheets_get_values.get_values(spreadsheet_id, "A1:C2") + self.assertIsNotNone(result) + values = result.get("values") + self.assertIsNotNone(values) + self.assertEqual(2, len(values)) + self.assertEqual(3, len(values[0])) if __name__ == "__main__": - unittest.main() + unittest.main() diff --git a/sheets/snippets/test_sheets_pivot_tables.py b/sheets/snippets/test_sheets_pivot_tables.py index 7f64a0f3..42acc343 100644 --- a/sheets/snippets/test_sheets_pivot_tables.py +++ b/sheets/snippets/test_sheets_pivot_tables.py @@ -18,15 +18,15 @@ class Testpivottables(BaseTest): - """Unit test for Pivot tables value Sheet snippet""" + """Unit test for Pivot tables value Sheet snippet""" - def test_pivot_tables(self): - """pivot table function""" - spreadsheet_id = self.create_test_spreadsheet() - self.populate_values(spreadsheet_id) - response = sheets_pivot_tables.pivot_tables(spreadsheet_id) - self.assertIsNotNone(response) + def test_pivot_tables(self): + """pivot table function""" + spreadsheet_id = self.create_test_spreadsheet() + self.populate_values(spreadsheet_id) + response = sheets_pivot_tables.pivot_tables(spreadsheet_id) + self.assertIsNotNone(response) if __name__ == "__main__": - unittest.main() + unittest.main() diff --git a/sheets/snippets/test_sheets_update_values.py b/sheets/snippets/test_sheets_update_values.py index 82efa71d..2367ae3a 100644 --- a/sheets/snippets/test_sheets_update_values.py +++ b/sheets/snippets/test_sheets_update_values.py @@ -18,21 +18,19 @@ class Testupdatesvalues(BaseTest): - """Unit test for update value Sheet snippet""" + """Unit test for update value Sheet snippet""" - def test_update_values(self): - """test updates_values""" - spreadsheet_id = self.create_test_spreadsheet() - result = sheets_update_values.update_values(spreadsheet_id, - 'A1:B2', 'USER_ENTERED', [ - ['A', 'B'], - ['C', 'D'] - ]) - self.assertIsNotNone(result) - self.assertEqual(2, result.get('updatedRows')) - self.assertEqual(2, result.get('updatedColumns')) - self.assertEqual(4, result.get('updatedCells')) + def test_update_values(self): + """test updates_values""" + spreadsheet_id = self.create_test_spreadsheet() + result = sheets_update_values.update_values( + spreadsheet_id, "A1:B2", "USER_ENTERED", [["A", "B"], ["C", "D"]] + ) + self.assertIsNotNone(result) + self.assertEqual(2, result.get("updatedRows")) + self.assertEqual(2, result.get("updatedColumns")) + self.assertEqual(4, result.get("updatedCells")) if __name__ == "__main__": - unittest.main() + unittest.main() diff --git a/slides/quickstart/quickstart.py b/slides/quickstart/quickstart.py index 157b0a72..f7c17aa3 100644 --- a/slides/quickstart/quickstart.py +++ b/slides/quickstart/quickstart.py @@ -13,8 +13,6 @@ # limitations under the License. # [START slides_quickstart] -from __future__ import print_function - import os.path from google.auth.transport.requests import Request @@ -24,50 +22,54 @@ from googleapiclient.errors import HttpError # If modifying these scopes, delete the file token.json. -SCOPES = ['https://www.googleapis.com/auth/presentations.readonly'] +SCOPES = ["https://www.googleapis.com/auth/presentations.readonly"] # The ID of a sample presentation. -PRESENTATION_ID = '1EAYk18WDjIG-zp_0vLm3CsfQh_i8eXc67Jo2O9C6Vuc' +PRESENTATION_ID = "1EAYk18WDjIG-zp_0vLm3CsfQh_i8eXc67Jo2O9C6Vuc" def main(): - """Shows basic usage of the Slides API. - Prints the number of slides and elements in a sample presentation. - """ - creds = None - # The file token.json stores the user's access and refresh tokens, and is - # created automatically when the authorization flow completes for the first - # time. - if os.path.exists('token.json'): - creds = Credentials.from_authorized_user_file('token.json', SCOPES) - # If there are no (valid) credentials available, let the user log in. - if not creds or not creds.valid: - if creds and creds.expired and creds.refresh_token: - creds.refresh(Request()) - else: - flow = InstalledAppFlow.from_client_secrets_file( - 'credentials.json', SCOPES) - creds = flow.run_local_server(port=0) - # Save the credentials for the next run - with open('token.json', 'w') as token: - token.write(creds.to_json()) + """Shows basic usage of the Slides API. + Prints the number of slides and elements in a sample presentation. + """ + creds = None + # The file token.json stores the user's access and refresh tokens, and is + # created automatically when the authorization flow completes for the first + # time. + if os.path.exists("token.json"): + creds = Credentials.from_authorized_user_file("token.json", SCOPES) + # If there are no (valid) credentials available, let the user log in. + if not creds or not creds.valid: + if creds and creds.expired and creds.refresh_token: + creds.refresh(Request()) + else: + flow = InstalledAppFlow.from_client_secrets_file( + "credentials.json", SCOPES + ) + creds = flow.run_local_server(port=0) + # Save the credentials for the next run + with open("token.json", "w") as token: + token.write(creds.to_json()) - try: - service = build('slides', 'v1', credentials=creds) + try: + service = build("slides", "v1", credentials=creds) - # Call the Slides API - presentation = service.presentations().get( - presentationId=PRESENTATION_ID).execute() - slides = presentation.get('slides') + # Call the Slides API + presentation = ( + service.presentations().get(presentationId=PRESENTATION_ID).execute() + ) + slides = presentation.get("slides") - print('The presentation contains {} slides:'.format(len(slides))) - for i, slide in enumerate(slides): - print('- Slide #{} contains {} elements.'.format( - i + 1, len(slide.get('pageElements')))) - except HttpError as err: - print(err) + print(f"The presentation contains {len(slides)} slides:") + for i, slide in enumerate(slides): + print( + f"- Slide #{i + 1} contains" + f" {len(slide.get('pageElements'))} elements." + ) + except HttpError as err: + print(err) -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() # [END slides_quickstart] diff --git a/slides/snippets/base_test.py b/slides/snippets/base_test.py index 7bcd1ac7..60952df2 100644 --- a/slides/snippets/base_test.py +++ b/slides/snippets/base_test.py @@ -12,8 +12,6 @@ # See the License for the specific language governing permissions and # limitations under the License. -from __future__ import print_function - import sys import unittest @@ -24,155 +22,150 @@ class BaseTest(unittest.TestCase): - @classmethod - def setUpClass(cls): - cls.credentials = cls.create_credentials() - http = cls.credentials.authorize(httplib2.Http()) - cls.credentials.refresh(http) - cls.service = build('slides', 'v1', http=http) - cls.drive_service = build('drive', 'v3', http=http) - cls.sheets_service = build('sheets', 'v4', http=http) - # Hide STDOUT output generated by snippets. - cls.stdout = sys.stdout - sys.stdout = None - - @classmethod - def tearDownClass(cls): - # Restore STDOUT. - sys.stdout = cls.stdout - - @classmethod - def create_credentials(cls): - credentials = GoogleCredentials.get_application_default() - scope = [ - 'https://www.googleapis.com/auth/drive', - ] - return credentials.create_scoped(scope) - - def setUp(self): - self.files_to_delete = [] - - def tearDown(self): - for file_id in self.files_to_delete: - try: - self.drive_service.files().delete(fileId=file_id).execute() - except errors.HttpError: - print('Unable to delete file %s' % file_id, file=sys.stderr) - - def delete_file_on_cleanup(self, file_id): - self.files_to_delete.append(file_id) - - def create_test_presentation(self): - presentation = { - 'title': 'Test Preso' - } - presentation = self.service.presentations().create( - body=presentation).execute() - self.delete_file_on_cleanup(presentation.get('presentationId')) - return presentation.get('presentationId') - - def add_slides(self, presentation_id, num, layout='TITLE_AND_TWO_COLUMNS'): - requests = [] - slide_ids = [] - for i in range(num): - slide_id = 'slide_{0}'.format(i) - slide_ids.append(slide_id) - requests.append({ - 'createSlide': { - 'objectId': slide_ids[i], - 'slideLayoutReference': { - 'predefinedLayout': layout - } - } - }) - body = { - 'requests': requests - } - self.service.presentations().batchUpdate( - presentationId=presentation_id, body=body).execute() - return slide_ids - - def create_test_textbox(self, presentation_id, page_id): - box_id = 'MyTextBox_01' - pt350 = { - 'magnitude': 350, - 'unit': 'PT' - } - requests = [] - requests.append({ - 'createShape': { - 'objectId': box_id, - 'shapeType': 'TEXT_BOX', - 'elementProperties': { - 'pageObjectId': page_id, - 'size': { - 'height': pt350, - 'width': pt350 + + @classmethod + def setUpClass(cls): + cls.credentials = cls.create_credentials() + http = cls.credentials.authorize(httplib2.Http()) + cls.credentials.refresh(http) + cls.service = build("slides", "v1", http=http) + cls.drive_service = build("drive", "v3", http=http) + cls.sheets_service = build("sheets", "v4", http=http) + # Hide STDOUT output generated by snippets. + cls.stdout = sys.stdout + sys.stdout = None + + @classmethod + def tearDownClass(cls): + # Restore STDOUT. + sys.stdout = cls.stdout + + @classmethod + def create_credentials(cls): + credentials = GoogleCredentials.get_application_default() + scope = [ + "https://www.googleapis.com/auth/drive", + ] + return credentials.create_scoped(scope) + + def setUp(self): + self.files_to_delete = [] + + def tearDown(self): + for file_id in self.files_to_delete: + try: + self.drive_service.files().delete(fileId=file_id).execute() + except errors.HttpError: + print(f"Unable to delete file {file_id}", file=sys.stderr) + + def delete_file_on_cleanup(self, file_id): + self.files_to_delete.append(file_id) + + def create_test_presentation(self): + presentation = {"title": "Test Preso"} + presentation = ( + self.service.presentations().create(body=presentation).execute() + ) + self.delete_file_on_cleanup(presentation.get("presentationId")) + return presentation.get("presentationId") + + def add_slides(self, presentation_id, num, layout="TITLE_AND_TWO_COLUMNS"): + requests = [] + slide_ids = [] + for i in range(num): + slide_id = f"slide_{i}" + slide_ids.append(slide_id) + requests.append( + { + "createSlide": { + "objectId": slide_ids[i], + "slideLayoutReference": {"predefinedLayout": layout}, + } + } + ) + body = {"requests": requests} + self.service.presentations().batchUpdate( + presentationId=presentation_id, body=body + ).execute() + return slide_ids + + def create_test_textbox(self, presentation_id, page_id): + box_id = "MyTextBox_01" + pt350 = {"magnitude": 350, "unit": "PT"} + requests = [] + requests.append( + { + "createShape": { + "objectId": box_id, + "shapeType": "TEXT_BOX", + "elementProperties": { + "pageObjectId": page_id, + "size": {"height": pt350, "width": pt350}, + "transform": { + "scaleX": 1, + "scaleY": 1, + "translateX": 350, + "translateY": 100, + "unit": "PT", }, - 'transform': { - 'scaleX': 1, - 'scaleY': 1, - 'translateX': 350, - 'translateY': 100, - 'unit': 'PT' - } - } + }, } - }) - requests.append({ - 'insertText': { - 'objectId': box_id, - 'insertionIndex': 0, - 'text': 'New Box Text Inserted' - } - }) - - body = { - 'requests': requests } - response = self.service.presentations().batchUpdate( - presentationId=presentation_id, body=body).execute() - return response.get('replies')[0].get('createShape').get('objectId') - - def create_test_sheets_chart( - self, presentation_id, page_id, spreadsheet_id, sheet_chart_id): - chart_id = 'MyChart_01' - emu4M = { - 'magnitude': 4000000, - 'unit': 'EMU' + ) + requests.append( + { + "insertText": { + "objectId": box_id, + "insertionIndex": 0, + "text": "New Box Text Inserted", + } } - requests = [] - requests.append({ - 'createSheetsChart': { - 'objectId': chart_id, - 'spreadsheetId': spreadsheet_id, - 'chartId': sheet_chart_id, - 'linkingMode': 'LINKED', - 'elementProperties': { - 'pageObjectId': page_id, - 'size': { - 'height': emu4M, - 'width': emu4M + ) + + body = {"requests": requests} + response = ( + self.service.presentations() + .batchUpdate(presentationId=presentation_id, body=body) + .execute() + ) + return response.get("replies")[0].get("createShape").get("objectId") + + def create_test_sheets_chart( + self, presentation_id, page_id, spreadsheet_id, sheet_chart_id + ): + chart_id = "MyChart_01" + emu4M = {"magnitude": 4000000, "unit": "EMU"} + requests = [] + requests.append( + { + "createSheetsChart": { + "objectId": chart_id, + "spreadsheetId": spreadsheet_id, + "chartId": sheet_chart_id, + "linkingMode": "LINKED", + "elementProperties": { + "pageObjectId": page_id, + "size": {"height": emu4M, "width": emu4M}, + "transform": { + "scaleX": 1, + "scaleY": 1, + "translateX": 100000, + "translateY": 100000, + "unit": "EMU", }, - 'transform': { - 'scaleX': 1, - 'scaleY': 1, - 'translateX': 100000, - 'translateY': 100000, - 'unit': 'EMU' - } - } + }, } - }) - - body = { - 'requests': requests } - response = self.service.presentations().batchUpdate( - presentationId=presentation_id, body=body).execute() - return response.get('replies')[0] \ - .get('createSheetsChart').get('objectId') + ) + + body = {"requests": requests} + response = ( + self.service.presentations() + .batchUpdate(presentationId=presentation_id, body=body) + .execute() + ) + return response.get("replies")[0].get("createSheetsChart").get("objectId") -if __name__ == '__main__': - unittest.main() +if __name__ == "__main__": + unittest.main() diff --git a/slides/snippets/slides_copy_presentation.py b/slides/snippets/slides_copy_presentation.py index 5b4ad584..fc4c0343 100644 --- a/slides/snippets/slides_copy_presentation.py +++ b/slides/snippets/slides_copy_presentation.py @@ -15,42 +15,39 @@ """ # [START slides_copy_presentation] -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def copy_presentation(presentation_id, copy_title): - """ - Creates the copy Presentation the user has access to. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - - creds, _ = google.auth.default() - # pylint: disable=maybe-no-member - try: - drive_service = build('drive', 'v3', credentials=creds) - body = { - 'name': copy_title - } - drive_response = drive_service.files().copy( - fileId=presentation_id, body=body).execute() - presentation_copy_id = drive_response.get('id') - - except HttpError as error: - print(f"An error occurred: {error}") - print("Presentations not copied") - return error - - return presentation_copy_id - # [END slides_copy_presentation] - - -if __name__ == '__main__': - # Put the presentation_id, Page_id of slides whose list needs - # to be submitted. - copy_presentation("16eRvJHRrM8Sej5YA0yCHVzQCPLz31-JhbOa4XpP8Yko", "wspace") + """ + Creates the copy Presentation the user has access to. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + + creds, _ = google.auth.default() + # pylint: disable=maybe-no-member + try: + drive_service = build("drive", "v3", credentials=creds) + body = {"name": copy_title} + drive_response = ( + drive_service.files().copy(fileId=presentation_id, body=body).execute() + ) + presentation_copy_id = drive_response.get("id") + + except HttpError as error: + print(f"An error occurred: {error}") + print("Presentations not copied") + return error + + return presentation_copy_id + # [END slides_copy_presentation] + + +if __name__ == "__main__": + # Put the presentation_id, Page_id of slides whose list needs + # to be submitted. + copy_presentation("16eRvJHRrM8Sej5YA0yCHVzQCPLz31-JhbOa4XpP8Yko", "wspace") diff --git a/slides/snippets/slides_create_bulleted_text.py b/slides/snippets/slides_create_bulleted_text.py index 89c88c5c..e7051222 100644 --- a/slides/snippets/slides_create_bulleted_text.py +++ b/slides/snippets/slides_create_bulleted_text.py @@ -15,55 +15,53 @@ """ # [START slides_create_bulleted_text] -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def create_bulleted_text(presentation_id, shape_id): - """ - Run create_bulleted_text the user has access to. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - # pylint: disable=maybe-no-member - try: - - slides_service = build('slides', 'v1', credentials=creds) - # Add arrow-diamond-disc bullets to all text in the shape. - requests = [ - { - 'createParagraphBullets': { - 'objectId': shape_id, - 'textRange': { - 'type': 'ALL' - }, - 'bulletPreset': 'BULLET_ARROW_DIAMOND_DISC' - } + """ + Run create_bulleted_text the user has access to. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + # pylint: disable=maybe-no-member + try: + slides_service = build("slides", "v1", credentials=creds) + # Add arrow-diamond-disc bullets to all text in the shape. + requests = [ + { + "createParagraphBullets": { + "objectId": shape_id, + "textRange": {"type": "ALL"}, + "bulletPreset": "BULLET_ARROW_DIAMOND_DISC", } - ] - - # Execute the requests. - body = { - 'requests': requests } - response = slides_service.presentations().batchUpdate( - presentationId=presentation_id, body=body).execute() - print(f"Added bullets to text in shape with ID: {shape_id}") + ] + + # Execute the requests. + body = {"requests": requests} + response = ( + slides_service.presentations() + .batchUpdate(presentationId=presentation_id, body=body) + .execute() + ) + print(f"Added bullets to text in shape with ID: {shape_id}") - return response - except HttpError as error: - print(f"An error occurred: {error}") - return error + return response + except HttpError as error: + print(f"An error occurred: {error}") + return error -if __name__ == '__main__': - # Put the presentation_id and shape_id - # to be submitted. - create_bulleted_text("1VD1xmi1-9DonI4zmCKENTzlVxIL5SdGGTmbHmnBjQ1E", "MyTextBox_9") +if __name__ == "__main__": + # Put the presentation_id and shape_id + # to be submitted. + create_bulleted_text( + "1VD1xmi1-9DonI4zmCKENTzlVxIL5SdGGTmbHmnBjQ1E", "MyTextBox_9" + ) # [END slides_create_bulleted_text] diff --git a/slides/snippets/slides_create_image.py b/slides/snippets/slides_create_image.py index a4b34e75..e0152156 100644 --- a/slides/snippets/slides_create_image.py +++ b/slides/snippets/slides_create_image.py @@ -15,75 +15,71 @@ """ # [START slides_create_image] -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def create_image(presentation_id, page_id): - """ - Creates images the user has access to. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ + """ + Creates images the user has access to. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ - creds, _ = google.auth.default() - # pylint: disable=maybe-no-member - try: - service = build('slides', 'v1', credentials=creds) - # pylint: disable = invalid-name - IMAGE_URL = ('https://www.google.com/images/branding/' - 'googlelogo/2x/googlelogo_color_272x92dp.png') - # pylint: disable=invalid-name - requests = [] - image_id = 'MyImage_11' - emu4M = { - 'magnitude': 4000000, - 'unit': 'EMU' - } - requests.append({ - 'createImage': { - 'objectId': image_id, - 'url': IMAGE_URL, - 'elementProperties': { - 'pageObjectId': page_id, - 'size': { - 'height': emu4M, - 'width': emu4M + creds, _ = google.auth.default() + # pylint: disable=maybe-no-member + try: + service = build("slides", "v1", credentials=creds) + # pylint: disable = invalid-name + IMAGE_URL = ( + "https://www.google.com/images/branding/" + "googlelogo/2x/googlelogo_color_272x92dp.png" + ) + # pylint: disable=invalid-name + requests = [] + image_id = "MyImage_11" + emu4M = {"magnitude": 4000000, "unit": "EMU"} + requests.append( + { + "createImage": { + "objectId": image_id, + "url": IMAGE_URL, + "elementProperties": { + "pageObjectId": page_id, + "size": {"height": emu4M, "width": emu4M}, + "transform": { + "scaleX": 1, + "scaleY": 1, + "translateX": 100000, + "translateY": 100000, + "unit": "EMU", }, - 'transform': { - 'scaleX': 1, - 'scaleY': 1, - 'translateX': 100000, - 'translateY': 100000, - 'unit': 'EMU' - } - } + }, } - }) - - # Execute the request. - body = { - 'requests': requests } - response = service.presentations() \ - .batchUpdate(presentationId=presentation_id, body=body).execute() - create_image_response = response.get('replies')[0].get('createImage') - print(f"Created image with ID: " - f"{(create_image_response.get('objectId'))}") + ) + + # Execute the request. + body = {"requests": requests} + response = ( + service.presentations() + .batchUpdate(presentationId=presentation_id, body=body) + .execute() + ) + create_image_response = response.get("replies")[0].get("createImage") + print(f"Created image with ID: {(create_image_response.get('objectId'))}") - return response - except HttpError as error: - print(f"An error occurred: {error}") - print("Images not created") - return error + return response + except HttpError as error: + print(f"An error occurred: {error}") + print("Images not created") + return error -if __name__ == '__main__': - # Put the presentation_id, Page_id of slides whose list needs - # to be submitted. - create_image("12SQU9Ik-ShXecJoMtT-LlNwEPiFR7AadnxV2KiBXCnE", "My2ndpage") - # [END slides_create_image] +if __name__ == "__main__": + # Put the presentation_id, Page_id of slides whose list needs + # to be submitted. + create_image("12SQU9Ik-ShXecJoMtT-LlNwEPiFR7AadnxV2KiBXCnE", "My2ndpage") + # [END slides_create_image] diff --git a/slides/snippets/slides_create_presentation.py b/slides/snippets/slides_create_presentation.py index 33777e29..2f683e6c 100644 --- a/slides/snippets/slides_create_presentation.py +++ b/slides/snippets/slides_create_presentation.py @@ -15,43 +15,39 @@ """ # [START slides_create_presentation] -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def create_presentation(title): - """ - Creates the Presentation the user has access to. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - # pylint: disable=maybe-no-member - try: - service = build('slides', 'v1', credentials=creds) - - body = { - 'title': title - } - presentation = service.presentations() \ - .create(body=body).execute() - print(f"Created presentation with ID:" - f"{(presentation.get('presentationId'))}") - return presentation - - except HttpError as error: - print(f"An error occurred: {error}") - print("presentation not created") - return error - - -if __name__ == '__main__': - # Put the title of the presentation - - create_presentation("finalp") + """ + Creates the Presentation the user has access to. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + # pylint: disable=maybe-no-member + try: + service = build("slides", "v1", credentials=creds) + + body = {"title": title} + presentation = service.presentations().create(body=body).execute() + print( + f"Created presentation with ID:{(presentation.get('presentationId'))}" + ) + return presentation + + except HttpError as error: + print(f"An error occurred: {error}") + print("presentation not created") + return error + + +if __name__ == "__main__": + # Put the title of the presentation + + create_presentation("finalp") # [END slides_create_presentation] diff --git a/slides/snippets/slides_create_sheets_chart.py b/slides/snippets/slides_create_sheets_chart.py index a1f286af..9efa3d64 100644 --- a/slides/snippets/slides_create_sheets_chart.py +++ b/slides/snippets/slides_create_sheets_chart.py @@ -15,80 +15,76 @@ """ # [START slides_create_sheets_chart] -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError -def create_sheets_chart(presentation_id, page_id, spreadsheet_id, - sheet_chart_id): - """ - create_sheets_chart the user has access to. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - # pylint: disable=maybe-no-member - try: - slides_service = build('slides', 'v1', credentials=creds) - # Embed a Sheets chart (indicated by the spreadsheet_id and - # sheet_chart_id) onto a page in the presentation. - # Setting the linking mode as "LINKED" allows the - # chart to be refreshed if the Sheets version is updated. +def create_sheets_chart( + presentation_id, page_id, spreadsheet_id, sheet_chart_id +): + """ + create_sheets_chart the user has access to. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + # pylint: disable=maybe-no-member + try: + slides_service = build("slides", "v1", credentials=creds) + # Embed a Sheets chart (indicated by the spreadsheet_id and + # sheet_chart_id) onto a page in the presentation. + # Setting the linking mode as "LINKED" allows the + # chart to be refreshed if the Sheets version is updated. - emu4m = { - 'magnitude': 4000000, - 'unit': 'EMU' - } + emu4m = {"magnitude": 4000000, "unit": "EMU"} - presentation_chart_id = 'MyEmbeddedChart' - requests = [ - { - 'createSheetsChart': { - 'objectId': presentation_chart_id, - 'spreadsheetId': spreadsheet_id, - 'chartId': sheet_chart_id, - 'linkingMode': 'LINKED', - 'elementProperties': { - 'pageObjectId': page_id, - 'size': { - 'height': emu4m, - 'width': emu4m - }, - 'transform': { - 'scaleX': 1, - 'scaleY': 1, - 'translateX': 100000, - 'translateY': 100000, - 'unit': 'EMU' - } - } - } + presentation_chart_id = "MyEmbeddedChart" + requests = [ + { + "createSheetsChart": { + "objectId": presentation_chart_id, + "spreadsheetId": spreadsheet_id, + "chartId": sheet_chart_id, + "linkingMode": "LINKED", + "elementProperties": { + "pageObjectId": page_id, + "size": {"height": emu4m, "width": emu4m}, + "transform": { + "scaleX": 1, + "scaleY": 1, + "translateX": 100000, + "translateY": 100000, + "unit": "EMU", + }, + }, } - ] - - # Execute the request. - body = { - 'requests': requests } - response = slides_service.presentations().batchUpdate( - presentationId=presentation_id, body=body).execute() - print(f"Added a linked Sheets chart with ID: {presentation_chart_id}") - return response - except HttpError as error: - print(f"An error occurred: {error}") - return error + ] + + # Execute the request. + body = {"requests": requests} + response = ( + slides_service.presentations() + .batchUpdate(presentationId=presentation_id, body=body) + .execute() + ) + print(f"Added a linked Sheets chart with ID: {presentation_chart_id}") + return response + except HttpError as error: + print(f"An error occurred: {error}") + return error -if __name__ == '__main__': - # Put the presentation_id, Page_id of slides - # spreadsheet_id and sheet_chart_id to be submitted. - create_sheets_chart("10QnVUx1X2qHsL17WUidGpPh_SQhXYx40CgIxaKk8jU4", - "FIRSTSLIDE", - "17eqFZl_WK4WVixX8PjvjfLD77DraoFwMDXeiHB3dvuM", - "1107320627") +if __name__ == "__main__": + # Put the presentation_id, Page_id of slides + # spreadsheet_id and sheet_chart_id to be submitted. + create_sheets_chart( + "10QnVUx1X2qHsL17WUidGpPh_SQhXYx40CgIxaKk8jU4", + "FIRSTSLIDE", + "17eqFZl_WK4WVixX8PjvjfLD77DraoFwMDXeiHB3dvuM", + "1107320627", + ) # [END slides_create_sheets_chart] diff --git a/slides/snippets/slides_create_slide.py b/slides/snippets/slides_create_slide.py index 8f16e1d2..fafbfa78 100644 --- a/slides/snippets/slides_create_slide.py +++ b/slides/snippets/slides_create_slide.py @@ -15,60 +15,58 @@ """ # [START slides_create_slide] -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def create_slide(presentation_id, page_id): - """ - Creates the Presentation the user has access to. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application.\n - """ - creds, _ = google.auth.default() - # pylint: disable=maybe-no-member - try: - service = build('slides', 'v1', credentials=creds) - # Add a slide at index 1 using the predefined - # 'TITLE_AND_TWO_COLUMNS' layout and the ID page_id. - requests = [ - { - 'createSlide': { - 'objectId': page_id, - 'insertionIndex': '1', - 'slideLayoutReference': { - 'predefinedLayout': 'TITLE_AND_TWO_COLUMNS' - } - } + """ + Creates the Presentation the user has access to. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application.\n + """ + creds, _ = google.auth.default() + # pylint: disable=maybe-no-member + try: + service = build("slides", "v1", credentials=creds) + # Add a slide at index 1 using the predefined + # 'TITLE_AND_TWO_COLUMNS' layout and the ID page_id. + requests = [ + { + "createSlide": { + "objectId": page_id, + "insertionIndex": "1", + "slideLayoutReference": { + "predefinedLayout": "TITLE_AND_TWO_COLUMNS" + }, } - ] + } + ] - # If you wish to populate the slide with elements, - # add element create requests here, using the page_id. + # If you wish to populate the slide with elements, + # add element create requests here, using the page_id. - # Execute the request. - body = { - 'requests': requests - } - response = service.presentations() \ - .batchUpdate(presentationId=presentation_id, body=body).execute() - create_slide_response = response.get('replies')[0].get('createSlide') - print(f"Created slide with ID:" - f"{(create_slide_response.get('objectId'))}") - except HttpError as error: - print(f"An error occurred: {error}") - print("Slides not created") - return error + # Execute the request. + body = {"requests": requests} + response = ( + service.presentations() + .batchUpdate(presentationId=presentation_id, body=body) + .execute() + ) + create_slide_response = response.get("replies")[0].get("createSlide") + print(f"Created slide with ID:{(create_slide_response.get('objectId'))}") + except HttpError as error: + print(f"An error occurred: {error}") + print("Slides not created") + return error - return response + return response -if __name__ == '__main__': - # Put the presentation_id, Page_id of slides whose list needs - # to be submitted. - create_slide("12SQU9Ik-ShXecJoMtT-LlNwEPiFR7AadnxV2KiBXCnE", "My4ndpage") - # [END slides_create_slide] +if __name__ == "__main__": + # Put the presentation_id, Page_id of slides whose list needs + # to be submitted. + create_slide("12SQU9Ik-ShXecJoMtT-LlNwEPiFR7AadnxV2KiBXCnE", "My4ndpage") + # [END slides_create_slide] diff --git a/slides/snippets/slides_create_textbox_with_text.py b/slides/snippets/slides_create_textbox_with_text.py index 2f1e1889..d3879d19 100644 --- a/slides/snippets/slides_create_textbox_with_text.py +++ b/slides/snippets/slides_create_textbox_with_text.py @@ -15,83 +15,75 @@ """ # [START slides_create_textbox_with_text] -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def create_textbox_with_text(presentation_id, page_id): - """ - Creates the textbox with text, the user has access to. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - # pylint: disable=maybe-no-member - try: - service = build('slides', 'v1', credentials=creds) - # Create a new square textbox, using the supplied element ID. - element_id = 'MyTextBox_10' - pt350 = { - 'magnitude': 350, - 'unit': 'PT' - } - requests = [ - { - 'createShape': { - 'objectId': element_id, - 'shapeType': 'TEXT_BOX', - 'elementProperties': { - 'pageObjectId': page_id, - 'size': { - 'height': pt350, - 'width': pt350 - }, - 'transform': { - 'scaleX': 1, - 'scaleY': 1, - 'translateX': 350, - 'translateY': 100, - 'unit': 'PT' - } - } - } - }, - - # Insert text into the box, using the supplied element ID. - { - 'insertText': { - 'objectId': element_id, - 'insertionIndex': 0, - 'text': 'New Box Text Inserted!' - } + """ + Creates the textbox with text, the user has access to. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + # pylint: disable=maybe-no-member + try: + service = build("slides", "v1", credentials=creds) + # Create a new square textbox, using the supplied element ID. + element_id = "MyTextBox_10" + pt350 = {"magnitude": 350, "unit": "PT"} + requests = [ + { + "createShape": { + "objectId": element_id, + "shapeType": "TEXT_BOX", + "elementProperties": { + "pageObjectId": page_id, + "size": {"height": pt350, "width": pt350}, + "transform": { + "scaleX": 1, + "scaleY": 1, + "translateX": 350, + "translateY": 100, + "unit": "PT", + }, + }, + } + }, + # Insert text into the box, using the supplied element ID. + { + "insertText": { + "objectId": element_id, + "insertionIndex": 0, + "text": "New Box Text Inserted!", } - ] + }, + ] - # Execute the request. - body = { - 'requests': requests - } - response = service.presentations() \ - .batchUpdate(presentationId=presentation_id, body=body).execute() - create_shape_response = response.get('replies')[0].get('createShape') - print(f"Created textbox with ID:" - f"{(create_shape_response.get('objectId'))}") - except HttpError as error: - print(f'An error occurred: {error}') + # Execute the request. + body = {"requests": requests} + response = ( + service.presentations() + .batchUpdate(presentationId=presentation_id, body=body) + .execute() + ) + create_shape_response = response.get("replies")[0].get("createShape") + print(f"Created textbox with ID:{(create_shape_response.get('objectId'))}") + except HttpError as error: + print(f"An error occurred: {error}") - return error + return error - return response + return response -if __name__ == '__main__': - # Put the presentation_id, Page_id of slides whose list needs - # to be submitted. - create_textbox_with_text("12SQU9Ik-ShXecJoMtT-LlNwEPiFR7AadnxV2KiBXCnE", - "Myfirstpage") +if __name__ == "__main__": + # Put the presentation_id, Page_id of slides whose list needs + # to be submitted. + create_textbox_with_text( + "12SQU9Ik-ShXecJoMtT-LlNwEPiFR7AadnxV2KiBXCnE", "Myfirstpage" + ) # [END slides_create_textbox_with_text] diff --git a/slides/snippets/slides_image_merging.py b/slides/snippets/slides_image_merging.py index ef3de918..571d7aa0 100644 --- a/slides/snippets/slides_image_merging.py +++ b/slides/snippets/slides_image_merging.py @@ -15,96 +15,98 @@ """ # [START slides_image_merging] -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError -def image_merging(template_presentation_id, - image_url, customer_name): - """image_merging require template_presentation_id, - image_url and customer_name - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - # pylint: disable=maybe-no-member - try: - - slides_service = build('slides', 'v1', credentials=creds) - drive_service = build('drive', 'v3', credentials=creds) - logo_url = image_url - - customer_graphic_url = image_url - - # Duplicate the template presentation using the Drive API. - copy_title = customer_name + ' presentation' - drive_response = drive_service.files().copy( - fileId=template_presentation_id, - body={'name': copy_title}).execute() - presentation_copy_id = drive_response.get('id') - - # Create the image merge (replaceAllShapesWithImage) requests. - requests = [] - requests.append({ - 'replaceAllShapesWithImage': { - 'imageUrl': logo_url, - 'replaceMethod': 'CENTER_INSIDE', - 'containsText': { - 'text': '{{company-logo}}', - 'matchCase': True - } +def image_merging(template_presentation_id, image_url, customer_name): + """image_merging require template_presentation_id, + image_url and customer_name + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + # pylint: disable=maybe-no-member + try: + slides_service = build("slides", "v1", credentials=creds) + drive_service = build("drive", "v3", credentials=creds) + logo_url = image_url + + customer_graphic_url = image_url + + # Duplicate the template presentation using the Drive API. + copy_title = customer_name + " presentation" + drive_response = ( + drive_service.files() + .copy(fileId=template_presentation_id, body={"name": copy_title}) + .execute() + ) + presentation_copy_id = drive_response.get("id") + + # Create the image merge (replaceAllShapesWithImage) requests. + requests = [] + requests.append( + { + "replaceAllShapesWithImage": { + "imageUrl": logo_url, + "replaceMethod": "CENTER_INSIDE", + "containsText": {"text": "{{company-logo}}", "matchCase": True}, } - }) - requests.append({ - 'replaceAllShapesWithImage': { - 'imageUrl': customer_graphic_url, - 'replaceMethod': 'CENTER_INSIDE', - 'containsText': { - 'text': '{{customer-graphic}}', - 'matchCase': True - } + } + ) + requests.append( + { + "replaceAllShapesWithImage": { + "imageUrl": customer_graphic_url, + "replaceMethod": "CENTER_INSIDE", + "containsText": { + "text": "{{customer-graphic}}", + "matchCase": True, + }, } - }) - - # Execute the requests. - body = { - 'requests': requests } - response = slides_service.presentations().batchUpdate( - presentationId=presentation_copy_id, body=body).execute() + ) + + # Execute the requests. + body = {"requests": requests} + response = ( + slides_service.presentations() + .batchUpdate(presentationId=presentation_copy_id, body=body) + .execute() + ) - # Count the number of replacements made. - num_replacements = 0 + # Count the number of replacements made. + num_replacements = 0 - for reply in response.get('replies'): - # add below line + for reply in response.get("replies"): + # add below line - if reply.get('occurrencesChanged') is not None: - # end tag - num_replacements += reply.get('replaceAllShapesWithImage') \ - .get('occurrencesChanged') + if reply.get("occurrencesChanged") is not None: + # end tag + num_replacements += reply.get("replaceAllShapesWithImage").get( + "occurrencesChanged" + ) - print(f"Created merged presentation with ID:" - f"{presentation_copy_id}") - print(f"Replaced {num_replacements} shapes with images") - except HttpError as error: - print(f"An error occurred: {error}") - print('Images is not merged') - return error + print(f"Created merged presentation with ID:{presentation_copy_id}") + print(f"Replaced {num_replacements} shapes with images") + except HttpError as error: + print(f"An error occurred: {error}") + print("Images is not merged") + return error - return response + return response -if __name__ == '__main__': - # Put the template_presentation_id, image_url and customer_name +if __name__ == "__main__": + # Put the template_presentation_id, image_url and customer_name - image_merging("10QnVUx1X2qHsL17WUidGpPh_SQhXYx40CgIxaKk8jU4", - 'https://www.google.com/images/branding/' - 'googlelogo/2x/googlelogo_color_272x92dp.png', - 'Fake Customer') + image_merging( + "10QnVUx1X2qHsL17WUidGpPh_SQhXYx40CgIxaKk8jU4", + "https://www.google.com/images/branding/" + "googlelogo/2x/googlelogo_color_272x92dp.png", + "Fake Customer", + ) - # [END slides_image_merging] + # [END slides_image_merging] diff --git a/slides/snippets/slides_refresh_sheets_chart.py b/slides/snippets/slides_refresh_sheets_chart.py index 4a962eae..a0179a4f 100644 --- a/slides/snippets/slides_refresh_sheets_chart.py +++ b/slides/snippets/slides_refresh_sheets_chart.py @@ -15,48 +15,43 @@ """ # [START slides_refresh_sheets_chart] -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def refresh_sheets_chart(presentation_id, presentation_chart_id): - """ - refresh_sheets_chart the user has access to. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - # pylint: disable=maybe-no-member - try: - slides_service = build('slides', 'v1', credentials=creds) - # Refresh an existing linked Sheets chart embedded in a presentation. - requests = [ - { - 'refreshSheetsChart': { - 'objectId': presentation_chart_id - } - } - ] - - # Execute the request. - body = { - 'requests': requests - } - response = slides_service.presentations().batchUpdate( - presentationId=presentation_id, body=body).execute() - print(f"Refreshed a linked Sheets chart with ID:{presentation_chart_id}") - return response - except HttpError as error: - print(f"An error occurred: {error}") - return error - - -if __name__ == '__main__': - # Put the presentation_id, presentation_chart_id - # to be submitted. - refresh_sheets_chart("10QnVUx1X2qHsL17WUidGpPh_SQhXYx40CgIxaKk8jU4", "1107320627") - # [END slides_refresh_sheets_chart] + """ + refresh_sheets_chart the user has access to. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + # pylint: disable=maybe-no-member + try: + slides_service = build("slides", "v1", credentials=creds) + # Refresh an existing linked Sheets chart embedded in a presentation. + requests = [{"refreshSheetsChart": {"objectId": presentation_chart_id}}] + + # Execute the request. + body = {"requests": requests} + response = ( + slides_service.presentations() + .batchUpdate(presentationId=presentation_id, body=body) + .execute() + ) + print(f"Refreshed a linked Sheets chart with ID:{presentation_chart_id}") + return response + except HttpError as error: + print(f"An error occurred: {error}") + return error + + +if __name__ == "__main__": + # Put the presentation_id, presentation_chart_id + # to be submitted. + refresh_sheets_chart( + "10QnVUx1X2qHsL17WUidGpPh_SQhXYx40CgIxaKk8jU4", "1107320627" + ) + # [END slides_refresh_sheets_chart] diff --git a/slides/snippets/slides_simple_text_replace.py b/slides/snippets/slides_simple_text_replace.py index 23acde4c..bd4adaaa 100644 --- a/slides/snippets/slides_simple_text_replace.py +++ b/slides/snippets/slides_simple_text_replace.py @@ -15,60 +15,58 @@ """ # [START slides_simple_text_replace] -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def simple_text_replace(presentation_id, shape_id, replacement_text): - """ - Run simple_text_replace the user has access to. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - # pylint: disable=maybe-no-member - try: - slides_service = build('slides', 'v1', credentials=creds) - # Remove existing text in the shape, then insert new text. - requests = [] - requests.append({ - 'deleteText': { - 'objectId': shape_id, - 'textRange': { - 'type': 'ALL' - } - } - }) - requests.append({ - 'insertText': { - 'objectId': shape_id, - 'insertionIndex': 0, - 'text': replacement_text + """ + Run simple_text_replace the user has access to. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + # pylint: disable=maybe-no-member + try: + slides_service = build("slides", "v1", credentials=creds) + # Remove existing text in the shape, then insert new text. + requests = [] + requests.append( + {"deleteText": {"objectId": shape_id, "textRange": {"type": "ALL"}}} + ) + requests.append( + { + "insertText": { + "objectId": shape_id, + "insertionIndex": 0, + "text": replacement_text, } - }) - - # Execute the requests. - body = { - 'requests': requests } - response = slides_service.presentations().batchUpdate( - presentationId=presentation_id, body=body).execute() - print(f"Replaced text in shape with ID: {shape_id}") - return response - except HttpError as error: - print(f"An error occurred: {error}") - print("Text is not merged") - return error + ) + + # Execute the requests. + body = {"requests": requests} + response = ( + slides_service.presentations() + .batchUpdate(presentationId=presentation_id, body=body) + .execute() + ) + print(f"Replaced text in shape with ID: {shape_id}") + return response + except HttpError as error: + print(f"An error occurred: {error}") + print("Text is not merged") + return error -if __name__ == '__main__': - # Put the presentation_id, shape_id and replacement_text - simple_text_replace('10QnVUx1X2qHsL17WUidGpPh_SQhXYx40CgIxaKk8jU4', - 'MyTextBox_6', - 'GWSpace_now') +if __name__ == "__main__": + # Put the presentation_id, shape_id and replacement_text + simple_text_replace( + "10QnVUx1X2qHsL17WUidGpPh_SQhXYx40CgIxaKk8jU4", + "MyTextBox_6", + "GWSpace_now", + ) # [END slides_simple_text_replace] diff --git a/slides/snippets/slides_text_merging.py b/slides/snippets/slides_text_merging.py index 602a2d78..690ac1ab 100644 --- a/slides/snippets/slides_text_merging.py +++ b/slides/snippets/slides_text_merging.py @@ -15,107 +15,115 @@ """ # [START slides_text_merging] -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def text_merging(template_presentation_id, data_spreadsheet_id): - """ - Run Text merging the user has access to. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - # pylint: disable=maybe-no-member - - try: - service = build('slides', 'v1', credentials=creds) - sheets_service = build('sheets', 'v4', credentials=creds) - drive_service = build('drive', 'v3', credentials=creds) - # Use the Sheets API to load data, one record per row. - data_range_notation = 'Customers!A2:M6' - sheets_response = sheets_service.spreadsheets().values().get( - spreadsheetId=data_spreadsheet_id, - range=data_range_notation).execute() - values = sheets_response.get('values') - - # For each record, create a new merged presentation. - for row in values: - customer_name = row[2] # name in column 3 - case_description = row[5] # case description in column 6 - total_portfolio = row[11] # total portfolio in column 12 - - # Duplicate the template presentation using the Drive API. - copy_title = customer_name + ' presentation' - body = { - 'name': copy_title - } - drive_response = drive_service.files().copy( - fileId=template_presentation_id, body=body).execute() - presentation_copy_id = drive_response.get('id') - - # Create the text merge (replaceAllText) requests - # for this presentation. - requests = [ - { - 'replaceAllText': { - 'containsText': { - 'text': '{{customer-name}}', - 'matchCase': True - }, - 'replaceText': customer_name - } - }, - { - 'replaceAllText': { - 'containsText': { - 'text': '{{case-description}}', - 'matchCase': True - }, - 'replaceText': case_description - } - }, - { - 'replaceAllText': { - 'containsText': { - 'text': '{{total-portfolio}}', - 'matchCase': True - }, - 'replaceText': total_portfolio - } - } - ] - - # Execute the requests for this presentation. - body = { - 'requests': requests - } - response = service.presentations().batchUpdate( - presentationId=presentation_copy_id, body=body).execute() - - # Count the total number of replacements made. - num_replacements = 0 - for reply in response.get('replies'): - if reply.get('occurrencesChanged') is not None: - num_replacements += reply.get('replaceAllText') \ - .get('occurrencesChanged') - print(f"Created presentation for " - f"{customer_name} with ID: {presentation_copy_id}") - print(f"Replaced {num_replacements} text instances") - - except HttpError as error: - print(f"An error occurred: {error}") - return error - - -if __name__ == '__main__': - # Put the template_presentation_id, data_spreadsheet_id - # of slides - - text_merging("10QnVUx1X2qHsL17WUidGpPh_SQhXYx40CgIxaKk8jU4", - "17eqFZl_WK4WVixX8PjvjfLD77DraoFwMDXeiHB3dvuM") - # [END slides_text_merging] + """ + Run Text merging the user has access to. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + # pylint: disable=maybe-no-member + + try: + service = build("slides", "v1", credentials=creds) + sheets_service = build("sheets", "v4", credentials=creds) + drive_service = build("drive", "v3", credentials=creds) + # Use the Sheets API to load data, one record per row. + data_range_notation = "Customers!A2:M6" + sheets_response = ( + sheets_service.spreadsheets() + .values() + .get(spreadsheetId=data_spreadsheet_id, range=data_range_notation) + .execute() + ) + values = sheets_response.get("values") + + # For each record, create a new merged presentation. + for row in values: + customer_name = row[2] # name in column 3 + case_description = row[5] # case description in column 6 + total_portfolio = row[11] # total portfolio in column 12 + + # Duplicate the template presentation using the Drive API. + copy_title = customer_name + " presentation" + body = {"name": copy_title} + drive_response = ( + drive_service.files() + .copy(fileId=template_presentation_id, body=body) + .execute() + ) + presentation_copy_id = drive_response.get("id") + + # Create the text merge (replaceAllText) requests + # for this presentation. + requests = [ + { + "replaceAllText": { + "containsText": { + "text": "{{customer-name}}", + "matchCase": True, + }, + "replaceText": customer_name, + } + }, + { + "replaceAllText": { + "containsText": { + "text": "{{case-description}}", + "matchCase": True, + }, + "replaceText": case_description, + } + }, + { + "replaceAllText": { + "containsText": { + "text": "{{total-portfolio}}", + "matchCase": True, + }, + "replaceText": total_portfolio, + } + }, + ] + + # Execute the requests for this presentation. + body = {"requests": requests} + response = ( + service.presentations() + .batchUpdate(presentationId=presentation_copy_id, body=body) + .execute() + ) + + # Count the total number of replacements made. + num_replacements = 0 + for reply in response.get("replies"): + if reply.get("occurrencesChanged") is not None: + num_replacements += reply.get("replaceAllText").get( + "occurrencesChanged" + ) + print( + "Created presentation for " + f"{customer_name} with ID: {presentation_copy_id}" + ) + print(f"Replaced {num_replacements} text instances") + + except HttpError as error: + print(f"An error occurred: {error}") + return error + + +if __name__ == "__main__": + # Put the template_presentation_id, data_spreadsheet_id + # of slides + + text_merging( + "10QnVUx1X2qHsL17WUidGpPh_SQhXYx40CgIxaKk8jU4", + "17eqFZl_WK4WVixX8PjvjfLD77DraoFwMDXeiHB3dvuM", + ) + # [END slides_text_merging] diff --git a/slides/snippets/slides_text_style_update.py b/slides/snippets/slides_text_style_update.py index 96b3d40b..36cb4644 100644 --- a/slides/snippets/slides_text_style_update.py +++ b/slides/snippets/slides_text_style_update.py @@ -15,105 +15,91 @@ """ # [START slides_text_style_update] -from __future__ import print_function - import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def text_style_update(presentation_id, shape_id): - """ - create_sheets_chart the user has access to. - Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity - for guides on implementing OAuth2 for the application. - """ - creds, _ = google.auth.default() - # pylint: disable=maybe-no-member - try: - service = build('slides', 'v1', credentials=creds) - # Update the text style so that the first 5 characters are bolded - # and italicized, the next 5 are displayed in blue 14 pt Times - # New Roman font, and the next 5 are hyperlinked. - requests = [ - { - 'updateTextStyle': { - 'objectId': shape_id, - 'textRange': { - 'type': 'FIXED_RANGE', - 'startIndex': 0, - 'endIndex': 5 - }, - 'style': { - 'bold': True, - 'italic': True - }, - 'fields': 'bold,italic' - } - }, - { - 'updateTextStyle': { - 'objectId': shape_id, - 'textRange': { - 'type': 'FIXED_RANGE', - 'startIndex': 5, - 'endIndex': 10 - }, - 'style': { - 'fontFamily': 'Times New Roman', - 'fontSize': { - 'magnitude': 14, - 'unit': 'PT' - }, - 'foregroundColor': { - 'opaqueColor': { - 'rgbColor': { - 'blue': 1.0, - 'green': 0.0, - 'red': 0.0 - } - } - } - }, - 'fields': 'foregroundColor,fontFamily,fontSize' - } - }, - { - 'updateTextStyle': { - 'objectId': shape_id, - 'textRange': { - 'type': 'FIXED_RANGE', - 'startIndex': 10, - 'endIndex': 15 - }, - 'style': { - 'link': { - 'url': 'www.example.com' + """ + create_sheets_chart the user has access to. + Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity + for guides on implementing OAuth2 for the application. + """ + creds, _ = google.auth.default() + # pylint: disable=maybe-no-member + try: + service = build("slides", "v1", credentials=creds) + # Update the text style so that the first 5 characters are bolded + # and italicized, the next 5 are displayed in blue 14 pt Times + # New Roman font, and the next 5 are hyperlinked. + requests = [ + { + "updateTextStyle": { + "objectId": shape_id, + "textRange": { + "type": "FIXED_RANGE", + "startIndex": 0, + "endIndex": 5, + }, + "style": {"bold": True, "italic": True}, + "fields": "bold,italic", + } + }, + { + "updateTextStyle": { + "objectId": shape_id, + "textRange": { + "type": "FIXED_RANGE", + "startIndex": 5, + "endIndex": 10, + }, + "style": { + "fontFamily": "Times New Roman", + "fontSize": {"magnitude": 14, "unit": "PT"}, + "foregroundColor": { + "opaqueColor": { + "rgbColor": {"blue": 1.0, "green": 0.0, "red": 0.0} } }, - 'fields': 'link' - } + }, + "fields": "foregroundColor,fontFamily,fontSize", + } + }, + { + "updateTextStyle": { + "objectId": shape_id, + "textRange": { + "type": "FIXED_RANGE", + "startIndex": 10, + "endIndex": 15, + }, + "style": {"link": {"url": "www.example.com"}}, + "fields": "link", } - ] + }, + ] - # Execute the requests. - body = { - 'requests': requests - } - response = service.presentations().batchUpdate( - presentationId=presentation_id, body=body).execute() - print(f"Updated the text style for shape with ID:{shape_id}") + # Execute the requests. + body = {"requests": requests} + response = ( + service.presentations() + .batchUpdate(presentationId=presentation_id, body=body) + .execute() + ) + print(f"Updated the text style for shape with ID:{shape_id}") - return response - except HttpError as error: - print(f"An error occurred: {error}") - return error + return response + except HttpError as error: + print(f"An error occurred: {error}") + return error -if __name__ == '__main__': - # Put the presentation_id, shape_id of slides - # to be submitted. - text_style_update("10QnVUx1X2qHsL17WUidGpPh_SQhXYx40CgIxaKk8jU4", - "MyTextBox_9") +if __name__ == "__main__": + # Put the presentation_id, shape_id of slides + # to be submitted. + text_style_update( + "10QnVUx1X2qHsL17WUidGpPh_SQhXYx40CgIxaKk8jU4", "MyTextBox_9" + ) # [END slides_text_style_update] diff --git a/slides/snippets/test_slides_copy_presentation.py b/slides/snippets/test_slides_copy_presentation.py index 70d1e260..c72c829c 100644 --- a/slides/snippets/test_slides_copy_presentation.py +++ b/slides/snippets/test_slides_copy_presentation.py @@ -18,16 +18,17 @@ class TestCopyPresentation(BaseTest): - """Unit test for Copy presentation snippet""" + """Unit test for Copy presentation snippet""" - def test_copy_presentation(self): - """set title for copy presentation""" - presentation_id = self.create_test_presentation() - copy_id = slides_copy_presentation.copy_presentation( - presentation_id, 'My Duplicate Presentation') - self.assertIsNotNone(copy_id) - self.delete_file_on_cleanup(copy_id) + def test_copy_presentation(self): + """set title for copy presentation""" + presentation_id = self.create_test_presentation() + copy_id = slides_copy_presentation.copy_presentation( + presentation_id, "My Duplicate Presentation" + ) + self.assertIsNotNone(copy_id) + self.delete_file_on_cleanup(copy_id) if __name__ == "__main__": - unittest.main() + unittest.main() diff --git a/slides/snippets/test_slides_create_bulleted_text.py b/slides/snippets/test_slides_create_bulleted_text.py index e3b9c4ab..885862e6 100644 --- a/slides/snippets/test_slides_create_bulleted_text.py +++ b/slides/snippets/test_slides_create_bulleted_text.py @@ -19,18 +19,18 @@ class TestCreateBulletedText(BaseTest): - """Unit test for create_bulleted_text snippet""" + """Unit test for create_bulleted_text snippet""" - def test_create_bulleted_text(self): - """create_bulleted_text function""" - presentation_id = self.create_test_presentation() - page_id = self.add_slides(presentation_id, 1, 'BLANK')[0] - box_id = self.create_test_textbox(presentation_id, page_id) - response = slides_create_bulleted_text.\ - create_bulleted_text(presentation_id, box_id) - self.assertEqual(1, len(response.get('replies')), - msg=pformat(response)) + def test_create_bulleted_text(self): + """create_bulleted_text function""" + presentation_id = self.create_test_presentation() + page_id = self.add_slides(presentation_id, 1, "BLANK")[0] + box_id = self.create_test_textbox(presentation_id, page_id) + response = slides_create_bulleted_text.create_bulleted_text( + presentation_id, box_id + ) + self.assertEqual(1, len(response.get("replies")), msg=pformat(response)) if __name__ == "__main__": - unittest.main() + unittest.main() diff --git a/slides/snippets/test_slides_create_image.py b/slides/snippets/test_slides_create_image.py index 075041f1..e8bb4237 100644 --- a/slides/snippets/test_slides_create_image.py +++ b/slides/snippets/test_slides_create_image.py @@ -19,19 +19,17 @@ class TestCreateTextboxWithText(BaseTest): - """Unit test case for create_image snippet""" + """Unit test case for create_image snippet""" - def test_create_image(self): - """presentation id and page id for create image""" - presentation_id = self.create_test_presentation() - page_id = self.add_slides(presentation_id, 1, 'BLANK')[0] - response = slides_create_image.create_image(presentation_id, page_id) - self.assertEqual(1, len(response.get('replies')), - msg=pformat(response)) - image_id = response.get('replies')[0].get( - 'createImage').get('objectId') - self.assertIsNotNone(image_id, msg=pformat(response)) + def test_create_image(self): + """presentation id and page id for create image""" + presentation_id = self.create_test_presentation() + page_id = self.add_slides(presentation_id, 1, "BLANK")[0] + response = slides_create_image.create_image(presentation_id, page_id) + self.assertEqual(1, len(response.get("replies")), msg=pformat(response)) + image_id = response.get("replies")[0].get("createImage").get("objectId") + self.assertIsNotNone(image_id, msg=pformat(response)) if __name__ == "__main__": - unittest.main() + unittest.main() diff --git a/slides/snippets/test_slides_create_presentation.py b/slides/snippets/test_slides_create_presentation.py index aaa69b24..06fd5f01 100644 --- a/slides/snippets/test_slides_create_presentation.py +++ b/slides/snippets/test_slides_create_presentation.py @@ -18,14 +18,14 @@ class TestCreatePresentation(BaseTest): - """Unit test for create presentation snippet""" + """Unit test for create presentation snippet""" - def test_create_presentation(self): - """Set title for create presentation""" - presentation = slides_create_presentation.create_presentation('Title') - self.assertIsNotNone(presentation) - self.delete_file_on_cleanup(presentation.get('presentationId')) + def test_create_presentation(self): + """Set title for create presentation""" + presentation = slides_create_presentation.create_presentation("Title") + self.assertIsNotNone(presentation) + self.delete_file_on_cleanup(presentation.get("presentationId")) if __name__ == "__main__": - unittest.main() + unittest.main() diff --git a/slides/snippets/test_slides_create_sheets_chart.py b/slides/snippets/test_slides_create_sheets_chart.py index de8f5e1c..e9c1b8f3 100644 --- a/slides/snippets/test_slides_create_sheets_chart.py +++ b/slides/snippets/test_slides_create_sheets_chart.py @@ -19,24 +19,24 @@ class TestCreateSheetsChart(BaseTest): - """Unit test for create_sheets_chart snippet""" - DATA_SPREADSHEET_ID = '17eqFZl_WK4WVixX8PjvjfLD77DraoFwMDXeiHB3dvuM' - CHART_ID = 1107320627 - - def test_create_sheets_chart(self): - """create_sheet chart method """ - presentation_id = self.create_test_presentation() - page_id = self.add_slides(presentation_id, 1, 'BLANK')[0] - response = slides_create_sheets_chart. \ - create_sheets_chart(presentation_id, page_id, - self.DATA_SPREADSHEET_ID, - self.CHART_ID) - self.assertEqual(1, len(response.get('replies')), - msg=pformat(response)) - chart_id = response.get('replies')[0].get('createSheetsChart') \ - .get('objectId') - self.assertIsNotNone(chart_id, msg=pformat(response)) + """Unit test for create_sheets_chart snippet""" + + DATA_SPREADSHEET_ID = "17eqFZl_WK4WVixX8PjvjfLD77DraoFwMDXeiHB3dvuM" + CHART_ID = 1107320627 + + def test_create_sheets_chart(self): + """create_sheet chart method""" + presentation_id = self.create_test_presentation() + page_id = self.add_slides(presentation_id, 1, "BLANK")[0] + response = slides_create_sheets_chart.create_sheets_chart( + presentation_id, page_id, self.DATA_SPREADSHEET_ID, self.CHART_ID + ) + self.assertEqual(1, len(response.get("replies")), msg=pformat(response)) + chart_id = ( + response.get("replies")[0].get("createSheetsChart").get("objectId") + ) + self.assertIsNotNone(chart_id, msg=pformat(response)) if __name__ == "__main__": - unittest.main() + unittest.main() diff --git a/slides/snippets/test_slides_create_slide.py b/slides/snippets/test_slides_create_slide.py index eabf36f8..b23d30c2 100644 --- a/slides/snippets/test_slides_create_slide.py +++ b/slides/snippets/test_slides_create_slide.py @@ -18,18 +18,18 @@ class TestCreateSlide(BaseTest): - """Unit test for create Slide snippet""" + """Unit test for create Slide snippet""" - def test_create_slide(self): - """pass presentation_id and page_id for creating the slides""" - presentation_id = self.create_test_presentation() - self.add_slides(presentation_id, 3) - page_id = 'my_page_id' - response = slides_create_slide.create_slide(presentation_id, page_id) - self.assertEqual(page_id, - response.get('replies')[0].get('createSlide'). - get('objectId')) + def test_create_slide(self): + """pass presentation_id and page_id for creating the slides""" + presentation_id = self.create_test_presentation() + self.add_slides(presentation_id, 3) + page_id = "my_page_id" + response = slides_create_slide.create_slide(presentation_id, page_id) + self.assertEqual( + page_id, response.get("replies")[0].get("createSlide").get("objectId") + ) if __name__ == "__main__": - unittest.main() + unittest.main() diff --git a/slides/snippets/test_slides_create_textbox_with_text.py b/slides/snippets/test_slides_create_textbox_with_text.py index d8e25e18..36b0b70a 100644 --- a/slides/snippets/test_slides_create_textbox_with_text.py +++ b/slides/snippets/test_slides_create_textbox_with_text.py @@ -19,19 +19,19 @@ class TestCreateTextboxWithText(BaseTest): - """Unit test for TestCreateTextboxWithText snippet""" + """Unit test for TestCreateTextboxWithText snippet""" - def test_create_textbox_with_text(self): - """Pass Presentation id and page id """ - presentation_id = self.create_test_presentation() - page_id = self.add_slides(presentation_id, 1, 'BLANK')[0] - response = slides_create_textbox_with_text.create_textbox_with_text( - presentation_id, page_id) - self.assertEqual(2, len(response.get('replies')), - msg=pformat(response)) - box_id = response.get('replies')[0].get('createShape').get('objectId') - self.assertIsNotNone(box_id, msg=pformat(response)) + def test_create_textbox_with_text(self): + """Pass Presentation id and page id""" + presentation_id = self.create_test_presentation() + page_id = self.add_slides(presentation_id, 1, "BLANK")[0] + response = slides_create_textbox_with_text.create_textbox_with_text( + presentation_id, page_id + ) + self.assertEqual(2, len(response.get("replies")), msg=pformat(response)) + box_id = response.get("replies")[0].get("createShape").get("objectId") + self.assertIsNotNone(box_id, msg=pformat(response)) if __name__ == "__main__": - unittest.main() + unittest.main() diff --git a/slides/snippets/test_slides_image_merging.py b/slides/snippets/test_slides_image_merging.py index 116c58ed..844480ea 100644 --- a/slides/snippets/test_slides_image_merging.py +++ b/slides/snippets/test_slides_image_merging.py @@ -19,30 +19,30 @@ class TestTextMerging(BaseTest): - """Unit test for text merging snippet""" - TEMPLATE_PRESENTATION_ID = '10QnVUx1X2qHsL17WUidGpPh_SQhXYx40CgIxaKk8jU4' - DATA_SPREADSHEET_ID = '17eqFZl_WK4WVixX8PjvjfLD77DraoFwMDXeiHB3dvuM' - IMAGE_URL = 'https://picsum.photos/200' - CHART_ID = 1107320627 - CUSTOMER_NAME = 'Fake Customer' - - def test_image_merging(self): - """image merging function """ - response = slides_image_merging.image_merging( - self.TEMPLATE_PRESENTATION_ID, - self.IMAGE_URL, - self.CUSTOMER_NAME) - presentation_id = response.get('presentationId') - self.delete_file_on_cleanup(presentation_id) - self.assertIsNotNone(presentation_id, msg=pformat(response)) - self.assertEqual(2, len(response.get('replies')), - msg=pformat(response)) - num_replacements = 0 - for reply in response.get('replies'): - if isinstance(reply, int): - num_replacements += reply.get('replaceAllShapesWithImage') \ - .get('occurrencesChanged') + """Unit test for text merging snippet""" + + TEMPLATE_PRESENTATION_ID = "10QnVUx1X2qHsL17WUidGpPh_SQhXYx40CgIxaKk8jU4" + DATA_SPREADSHEET_ID = "17eqFZl_WK4WVixX8PjvjfLD77DraoFwMDXeiHB3dvuM" + IMAGE_URL = "https://picsum.photos/200" + CHART_ID = 1107320627 + CUSTOMER_NAME = "Fake Customer" + + def test_image_merging(self): + """image merging function""" + response = slides_image_merging.image_merging( + self.TEMPLATE_PRESENTATION_ID, self.IMAGE_URL, self.CUSTOMER_NAME + ) + presentation_id = response.get("presentationId") + self.delete_file_on_cleanup(presentation_id) + self.assertIsNotNone(presentation_id, msg=pformat(response)) + self.assertEqual(2, len(response.get("replies")), msg=pformat(response)) + num_replacements = 0 + for reply in response.get("replies"): + if isinstance(reply, int): + num_replacements += reply.get("replaceAllShapesWithImage").get( + "occurrencesChanged" + ) if __name__ == "__main__": - unittest.main() + unittest.main() diff --git a/slides/snippets/test_slides_refresh_sheets_chart.py b/slides/snippets/test_slides_refresh_sheets_chart.py index 5fa717af..9ecb7723 100644 --- a/slides/snippets/test_slides_refresh_sheets_chart.py +++ b/slides/snippets/test_slides_refresh_sheets_chart.py @@ -19,23 +19,23 @@ class TestCreateSheetsChart(BaseTest): - """Unit test for refresh_sheets_chart snippet""" - DATA_SPREADSHEET_ID = '17eqFZl_WK4WVixX8PjvjfLD77DraoFwMDXeiHB3dvuM' - CHART_ID = 1107320627 - - def test_refresh_sheets_chart(self): - """ refresh_sheets_chart method """ - presentation_id = self.create_test_presentation() - page_id = self.add_slides(presentation_id, 1, 'BLANK')[0] - chart_id = self.create_test_sheets_chart(presentation_id, - page_id, - self.DATA_SPREADSHEET_ID, - self.CHART_ID) - response = slides_refresh_sheets_chart.refresh_sheets_chart( - presentation_id, chart_id) - self.assertEqual(1, len(response.get('replies')), - msg=pformat(response)) + """Unit test for refresh_sheets_chart snippet""" + + DATA_SPREADSHEET_ID = "17eqFZl_WK4WVixX8PjvjfLD77DraoFwMDXeiHB3dvuM" + CHART_ID = 1107320627 + + def test_refresh_sheets_chart(self): + """refresh_sheets_chart method""" + presentation_id = self.create_test_presentation() + page_id = self.add_slides(presentation_id, 1, "BLANK")[0] + chart_id = self.create_test_sheets_chart( + presentation_id, page_id, self.DATA_SPREADSHEET_ID, self.CHART_ID + ) + response = slides_refresh_sheets_chart.refresh_sheets_chart( + presentation_id, chart_id + ) + self.assertEqual(1, len(response.get("replies")), msg=pformat(response)) if __name__ == "__main__": - unittest.main() + unittest.main() diff --git a/slides/snippets/test_slides_simple_text_replace.py b/slides/snippets/test_slides_simple_text_replace.py index 26334b2c..bbf854a2 100644 --- a/slides/snippets/test_slides_simple_text_replace.py +++ b/slides/snippets/test_slides_simple_text_replace.py @@ -19,18 +19,18 @@ class TestSimpleTextReplace(BaseTest): - """Unit test for SimpleTextReplace snippet""" + """Unit test for SimpleTextReplace snippet""" - def test_simple_text_replace(self): - """ test_simple_text_replace function""" - presentation_id = self.create_test_presentation() - page_id = self.add_slides(presentation_id, 1, 'BLANK')[0] - box_id = self.create_test_textbox(presentation_id, page_id) - response = slides_simple_text_replace.simple_text_replace( - presentation_id, box_id, 'MY NEW TEXT') - self.assertEqual(2, len(response.get('replies')), - msg=pformat(response)) + def test_simple_text_replace(self): + """test_simple_text_replace function""" + presentation_id = self.create_test_presentation() + page_id = self.add_slides(presentation_id, 1, "BLANK")[0] + box_id = self.create_test_textbox(presentation_id, page_id) + response = slides_simple_text_replace.simple_text_replace( + presentation_id, box_id, "MY NEW TEXT" + ) + self.assertEqual(2, len(response.get("replies")), msg=pformat(response)) if __name__ == "__main__": - unittest.main() + unittest.main() diff --git a/slides/snippets/test_slides_text_merging.py b/slides/snippets/test_slides_text_merging.py index a994c8d0..f3f0ac54 100644 --- a/slides/snippets/test_slides_text_merging.py +++ b/slides/snippets/test_slides_text_merging.py @@ -18,16 +18,17 @@ class TestTextMerging(BaseTest): - """Unit test for SimpleTextReplace snippet""" - TEMPLATE_PRESENTATION_ID = '10QnVUx1X2qHsL17WUidGpPh_SQhXYx40CgIxaKk8jU4' - DATA_SPREADSHEET_ID = '17eqFZl_WK4WVixX8PjvjfLD77DraoFwMDXeiHB3dvuM' + """Unit test for SimpleTextReplace snippet""" - def test_text_merging(self): - """ text_merging method """ - slides_text_merging.text_merging( - self.TEMPLATE_PRESENTATION_ID, - self.DATA_SPREADSHEET_ID) + TEMPLATE_PRESENTATION_ID = "10QnVUx1X2qHsL17WUidGpPh_SQhXYx40CgIxaKk8jU4" + DATA_SPREADSHEET_ID = "17eqFZl_WK4WVixX8PjvjfLD77DraoFwMDXeiHB3dvuM" + + def test_text_merging(self): + """text_merging method""" + slides_text_merging.text_merging( + self.TEMPLATE_PRESENTATION_ID, self.DATA_SPREADSHEET_ID + ) if __name__ == "__main__": - unittest.main() + unittest.main() diff --git a/slides/snippets/test_slides_text_style_update.py b/slides/snippets/test_slides_text_style_update.py index 98fd9a57..1e7e8df0 100644 --- a/slides/snippets/test_slides_text_style_update.py +++ b/slides/snippets/test_slides_text_style_update.py @@ -19,18 +19,18 @@ class TestTextStyleUpdate(BaseTest): - """Unit test for SimpleTextReplace snippet""" + """Unit test for SimpleTextReplace snippet""" - def test_text_style_update(self): - """ test_text_style_update function""" - presentation_id = self.create_test_presentation() - page_id = self.add_slides(presentation_id, 1, 'BLANK')[0] - box_id = self.create_test_textbox(presentation_id, page_id) - response = slides_text_style_update.\ - text_style_update(presentation_id, box_id) - self.assertEqual(3, len(response.get('replies')), - msg=pformat(response)) + def test_text_style_update(self): + """test_text_style_update function""" + presentation_id = self.create_test_presentation() + page_id = self.add_slides(presentation_id, 1, "BLANK")[0] + box_id = self.create_test_textbox(presentation_id, page_id) + response = slides_text_style_update.text_style_update( + presentation_id, box_id + ) + self.assertEqual(3, len(response.get("replies")), msg=pformat(response)) if __name__ == "__main__": - unittest.main() + unittest.main() diff --git a/tasks/quickstart/quickstart.py b/tasks/quickstart/quickstart.py index ab0882b5..6f380c22 100644 --- a/tasks/quickstart/quickstart.py +++ b/tasks/quickstart/quickstart.py @@ -13,8 +13,6 @@ # limitations under the License. # [START tasks_quickstart] -from __future__ import print_function - import os.path from google.auth.transport.requests import Request @@ -24,49 +22,50 @@ from googleapiclient.errors import HttpError # If modifying these scopes, delete the file token.json. -SCOPES = ['https://www.googleapis.com/auth/tasks.readonly'] +SCOPES = ["https://www.googleapis.com/auth/tasks.readonly"] def main(): - """Shows basic usage of the Tasks API. - Prints the title and ID of the first 10 task lists. - """ - creds = None - # The file token.json stores the user's access and refresh tokens, and is - # created automatically when the authorization flow completes for the first - # time. - if os.path.exists('token.json'): - creds = Credentials.from_authorized_user_file('token.json', SCOPES) - # If there are no (valid) credentials available, let the user log in. - if not creds or not creds.valid: - if creds and creds.expired and creds.refresh_token: - creds.refresh(Request()) - else: - flow = InstalledAppFlow.from_client_secrets_file( - 'credentials.json', SCOPES) - creds = flow.run_local_server(port=0) - # Save the credentials for the next run - with open('token.json', 'w') as token: - token.write(creds.to_json()) + """Shows basic usage of the Tasks API. + Prints the title and ID of the first 10 task lists. + """ + creds = None + # The file token.json stores the user's access and refresh tokens, and is + # created automatically when the authorization flow completes for the first + # time. + if os.path.exists("token.json"): + creds = Credentials.from_authorized_user_file("token.json", SCOPES) + # If there are no (valid) credentials available, let the user log in. + if not creds or not creds.valid: + if creds and creds.expired and creds.refresh_token: + creds.refresh(Request()) + else: + flow = InstalledAppFlow.from_client_secrets_file( + "credentials.json", SCOPES + ) + creds = flow.run_local_server(port=0) + # Save the credentials for the next run + with open("token.json", "w") as token: + token.write(creds.to_json()) - try: - service = build('tasks', 'v1', credentials=creds) + try: + service = build("tasks", "v1", credentials=creds) - # Call the Tasks API - results = service.tasklists().list(maxResults=10).execute() - items = results.get('items', []) + # Call the Tasks API + results = service.tasklists().list(maxResults=10).execute() + items = results.get("items", []) - if not items: - print('No task lists found.') - return + if not items: + print("No task lists found.") + return - print('Task lists:') - for item in items: - print(u'{0} ({1})'.format(item['title'], item['id'])) - except HttpError as err: - print(err) + print("Task lists:") + for item in items: + print(f"{item['title']} ({item['id']})") + except HttpError as err: + print(err) -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() # [END tasks_quickstart] diff --git a/vault/quickstart/quickstart.py b/vault/quickstart/quickstart.py index cfd5f6ff..57dadd95 100644 --- a/vault/quickstart/quickstart.py +++ b/vault/quickstart/quickstart.py @@ -13,8 +13,6 @@ # limitations under the License. # [START vault_quickstart] -from __future__ import print_function - import os.path from google.auth.transport.requests import Request @@ -24,50 +22,50 @@ from googleapiclient.errors import HttpError # If modifying these scopes, delete the file token.json. -SCOPES = ['https://www.googleapis.com/auth/ediscovery'] +SCOPES = ["https://www.googleapis.com/auth/ediscovery"] def main(): - """Shows basic usage of the Vault API. - Prints the names and IDs of the first 10 matters in Vault. - """ - creds = None - # The file token.json stores the user's access and refresh tokens, and is - # created automatically when the authorization flow completes for the first - # time. - if os.path.exists('token.json'): - creds = Credentials.from_authorized_user_file('token.json', SCOPES) - # If there are no (valid) credentials available, let the user log in. - if not creds or not creds.valid: - if creds and creds.expired and creds.refresh_token: - creds.refresh(Request()) - else: - flow = InstalledAppFlow.from_client_secrets_file( - 'credentials.json', SCOPES) - creds = flow.run_local_server(port=0) - # Save the credentials for the next run - with open('token.json', 'w') as token: - token.write(creds.to_json()) - - try: + """Shows basic usage of the Vault API. + Prints the names and IDs of the first 10 matters in Vault. + """ + creds = None + # The file token.json stores the user's access and refresh tokens, and is + # created automatically when the authorization flow completes for the first + # time. + if os.path.exists("token.json"): + creds = Credentials.from_authorized_user_file("token.json", SCOPES) + # If there are no (valid) credentials available, let the user log in. + if not creds or not creds.valid: + if creds and creds.expired and creds.refresh_token: + creds.refresh(Request()) + else: + flow = InstalledAppFlow.from_client_secrets_file( + "credentials.json", SCOPES + ) + creds = flow.run_local_server(port=0) + # Save the credentials for the next run + with open("token.json", "w") as token: + token.write(creds.to_json()) - service = build('vault', 'v1', credentials=creds) + try: + service = build("vault", "v1", credentials=creds) - # Call the Vault API - results = service.matters().list(pageSize=10).execute() - matters = results.get('matters', []) + # Call the Vault API + results = service.matters().list(pageSize=10).execute() + matters = results.get("matters", []) - if not matters: - print('No matters found.') - return + if not matters: + print("No matters found.") + return - print('Matters:') - for matter in matters: - print(u'{} ({})'.format(matter.get('name'), matter.get('id'))) - except HttpError as err: - print(err) + print("Matters:") + for matter in matters: + print(f"{matter.get('name')} ({matter.get('id')})") + except HttpError as err: + print(err) -if __name__ == '__main__': - main() +if __name__ == "__main__": + main() # [END vault_quickstart]