From bcc27f2761a7683cf1e0d3a3b677a0f653ebb2cb Mon Sep 17 00:00:00 2001 From: Wesley Chun Date: Wed, 13 Mar 2019 00:50:57 -0700 Subject: [PATCH 01/10] add Docs API Mail Merge Python sample --- docs/mail-merge/CONTRIBUTING.md | 36 +++++ docs/mail-merge/LICENSE | 201 ++++++++++++++++++++++++ docs/mail-merge/README.md | 79 ++++++++++ docs/mail-merge/docs_mail_merge.py | 142 +++++++++++++++++ docs/mail-merge/docs_mail_merge_test.py | 96 +++++++++++ 5 files changed, 554 insertions(+) create mode 100644 docs/mail-merge/CONTRIBUTING.md create mode 100644 docs/mail-merge/LICENSE create mode 100644 docs/mail-merge/README.md create mode 100644 docs/mail-merge/docs_mail_merge.py create mode 100644 docs/mail-merge/docs_mail_merge_test.py diff --git a/docs/mail-merge/CONTRIBUTING.md b/docs/mail-merge/CONTRIBUTING.md new file mode 100644 index 00000000..3e0558e0 --- /dev/null +++ b/docs/mail-merge/CONTRIBUTING.md @@ -0,0 +1,36 @@ +# How to become a contributor and submit your own code + +## Contributor License Agreements + +We'd love to accept your sample apps and patches! Before we can take them, we +have to jump a couple of legal hurdles. + +Please fill out either the individual or corporate Contributor License Agreement +(CLA). + + * If you are an individual writing original source code and you're sure you + own the intellectual property, then you'll need to sign an [individual CLA] + (https://developers.google.com/open-source/cla/individual). + * If you work for a company that wants to allow you to contribute your work, + then you'll need to sign a [corporate CLA] + (https://developers.google.com/open-source/cla/corporate). + +Follow either of the two links above to access the appropriate CLA and +instructions for how to sign and return it. Once we receive it, we'll be able to +accept your pull requests. + +## Contributing A Patch + +1. Submit an issue describing your proposed change to the repo in question. +1. The repo owner will respond to your issue promptly. +1. If your proposed change is accepted, and you haven't already done so, sign a + Contributor License Agreement (see details above). +1. Fork the desired repo, develop and test your code changes. +1. Ensure that your code adheres to the existing style in the sample to which + you are contributing. Refer to the + [Google Cloud Platform Samples Style Guide] + (https://github.com/GoogleCloudPlatform/Template/wiki/style.html) for the + recommended coding standards for this organization. +1. Ensure that your code has an appropriate set of unit tests which all pass. +1. Submit a pull request. + diff --git a/docs/mail-merge/LICENSE b/docs/mail-merge/LICENSE new file mode 100644 index 00000000..01de3bce --- /dev/null +++ b/docs/mail-merge/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2018 Google LLC + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + 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. diff --git a/docs/mail-merge/README.md b/docs/mail-merge/README.md new file mode 100644 index 00000000..6db0cec5 --- /dev/null +++ b/docs/mail-merge/README.md @@ -0,0 +1,79 @@ +# Mail Merge Sample (Python) for Google Docs (REST) API + +## Prerequisites + +- Access to the internet and a web browser +- A Google account (G Suite accounts may require administrator approval) +- Basic Python skills (2.x or 3.x) +- Google APIs project with the [Drive](https://developers.google.com/drive/), [Sheets](https://developers.google.com/sheets/), and [Docs](https://developers.google.com/docs/) APIs enabled + +## Description + +Before getting started, create a new project (or reuse an existing one) at with Google Drive and Docs APIs enabled. (See the videos listed below if you're new to Google APIs.) Then install the Google APIs Client Library for Python if you haven't already: `pip{,3} install -U google-api-python-client` + +This sample app requires you to [create a new Google Docs file](https://docs.google.com). Choose whatever template you wish to use, but we suggest using the Letter/Spearmint one to keep things simple. Replace the contact information in the Doc with template variables that we can merge with desired data. + +Here is a [sample Letter template](https://drive.google.com/open?id=1Rr7eKm3tvUgRKRoOYVSMF69IVAHIOPS72-l0CzsPmfM) to get an idea of what we mean: ![sample Letter template](https://user-images.githubusercontent.com/1102504/44741564-51ea2480-aab2-11e8-871c-a836626b2a0d.png "sample Letter template") + +In the document, the variable names used by the sample app are: + +### General + +* `{{DATE}}` — letter to be dated with this date +* `{{BODY}}` — letter content + +### Sender + +* `{{MY_NAME}}` — sender's name +* `{{MY_ADDRESS}}` — sender's address +* `{{MY_EMAIL}}` — sender's email +* `{{MY_PHONE}}` — sender's telephone number + +### Recipient + +* `{{TO_NAME}}` — recipient's name +* `{{TO_TITLE}}` — recipient's job title +* `{{TO_COMPANY}}` — recipient's organization +* `{{TO_ADDRESS}}` — recipient's address + +After you've templatized the Google Doc, be sure to grab its file ID — in your browser, look at the address bar, and extract the long alphanumeric string that makes up the Drive file ID from the URL: `https://docs.google.com/document/d//edit`. + +Replace `YOUR_TMPL_DOC_FILE_ID` in the `docs_mail_merge.py` source file with this file ID as the string value (in quotes) for the `DOCS_FILE_ID` variable. Run the sample app, accept the OAuth2 permissions requested, and when the script has completed, you should have a new mail-merged Google Doc named `Merged form letter` in your Google Drive folder! + +## Data source + +The application currently supports two different sources of data, plain text and Google Sheets. By default, the sample uses plain text via the `TARGET_TEXT` variable. A better option is to use a Google Sheet. Enable the API for your project in the developers console, and change the `source` variable at the bottom to `'sheets'`. Be sure you create a Sheet which looks like the below and set the `SHEETS_FILE_ID` variable to its file ID. + +![sample Sheets data source](https://user-images.githubusercontent.com/1102504/54064578-62e6c180-41ca-11e9-86f6-9d147ac17200.png "sample Sheets data source") + +## Testing + +The unit-test script is `docs_mail_merge_test.py`; these are the current tests available: + +1. Confirm OAuth2 credentials file was downloaded from the API project in the developers console as `credentials.json`. +1. Confirm those OAuth2 credentials can issue requests to Google APIs +1. Confirm project can connect to the Drive, Sheets, and Docs APIs +1. Confirm correct project setup & enabled-APIs by creating & deleting a temp Docs file. +1. Confirm correct project setup & enabled-APIs by copying an existing Docs file then deleting it. +1. Confirm application can retrieve data from plain text source. +1. Confirm application can retrieve data from Google Sheets source. + +## Reference + +- Google Drive API + - [API documentation](https://developers.google.com/drive) + - [Support channels](https://developers.google.com/drive/api/v3/support) +- Google Docs API + - [API documentation](https://developers.google.com/docs) + - [Python Quickstart](https://developers.google.com/docs/api/quickstart/python) + - [Support channels](https://developers.google.com/docs/api/support) +- Google Sheets API + - [API documentation](https://developers.google.com/sheets) + - [Support channels](https://developers.google.com/sheets/api/support) +- [Google APIs Client Libraries](https://developers.google.com/api-client-library) +- [G Suite developer overview & video](https://developers.google.com/gsuite) +- [G Suite (REST) APIs intro codelab](https://g.co/codelabs/gsuite-apis-intro) (~half-hour) +- Introductory API videos + - [New Google APIs project setup](https://goo.gl/RbyTFD) (6:54) + - [Common Python boilerplate code review](https://goo.gl/KMfbeK) (3:48) + - [REST APIs intro (Drive API)](https://goo.gl/ZIgf8k) (6:20) diff --git a/docs/mail-merge/docs_mail_merge.py b/docs/mail-merge/docs_mail_merge.py new file mode 100644 index 00000000..af8d746d --- /dev/null +++ b/docs/mail-merge/docs_mail_merge.py @@ -0,0 +1,142 @@ +# -*- coding: utf-8 -*- +# +# Copyright ©2018-2019 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at apache.org/licenses/LICENSE-2.0. +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# 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. + +""" +docs-mail-merge.py (2.x or 3.x) + +Google Docs (REST) API mail-merge sample app +""" +from __future__ import print_function +import time + +from googleapiclient import discovery +from httplib2 import Http +from oauth2client import file, client, tools + +# fill-in your template file ID +DOCS_FILE_ID = YOUR_TMPL_DOC_FILE_ID # Docs template +SHEETS_FILE_ID = YOUR_SHEET_DATA_FILE_ID # Sheets data source +CREDS_FILE = 'credentials.json' +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', +) +COLUMNS = ['to_name', 'to_title', 'to_company', 'to_address'] +OUTPUT = True # change to False to suppress output +SOURCE = 'text' # or 'sheets' to change data source + +def get_http_client(): + """Manage OAuth tokens in 'token.json' file given the downloaded + 'credentials.json' file along with requested OAuth2 scopes. + """ + store = file.Storage('token.json') + creds = store.get() + if not creds or creds.invalid: + flow = client.flow_from_clientsecrets(CREDS_FILE, SCOPES) + creds = tools.run_flow(flow, store) + return creds.authorize(Http()) + +# create service endpoints to the 3 APIs +HTTP = get_http_client() +DRIVE = discovery.build('drive', 'v3', http=HTTP) +DOCS = discovery.build('docs', 'v1', http=HTTP) +SHEETS = discovery.build('sheets', 'v4', http=HTTP) + +# plain text data source +TARGET_TEXT = [ + 'Ms. Lara Brown', 'Googler', 'Google NYC', '111 8th Ave\nNew York, NY 10011-5201', +] + +# fill-in your data to merge into document template variables +merge = { + 'my_name': 'Mr. Jeff Erson', + 'my_address': '76 9th Ave\nNew York, NY 10011-4962', + 'my_email': 'http://google.com', + 'my_phone': '+1-212-565-0000', + # - - - - - - - - - - - - - - - - - - - - - - - - - - + 'date': time.ctime(), + # - - - - - - - - - - - - - - - - - - - - - - - - - - + '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 Android phones.' +} + +def get_data(source='text', output=True): + """Gets mail merge data from chosen data source. + """ + if source not in {'sheets', 'text'}: + raise ValueError('ERROR: unsupported data type %r... must be "sheets" or "text"' % source) + func = eval('_get_%s_data' % source) + return dict(zip(COLUMNS, func(output=output))) + +def _get_text_data(output=False): + """Private function that returns data from plain text source. + """ + if output: + print(' - Using static text data') + return TARGET_TEXT + +def _get_sheets_data(service=SHEETS, output=False): + """Private function that returns data from Google Sheets source. + Note: this sample code gets all cells in 'Sheet1', the first + default Sheet in a spreadsheet. Use any desired data range + you need (in standard A1 notation). Sample returns only 1 row. + The 'output' flag toggles verbose output. + """ + if output: + print(' - Using data from Google Sheets') + return SHEETS.spreadsheets().values().get(spreadsheetId=SHEETS_FILE_ID, + range='Sheet1').execute().get('values')[0] # one row only + +def _copy_template(tmpl_id, source, service=DRIVE, output=False): + """Private function that copies the letter template document then + returns the new file ID. The 'output' flag toggles verbose output. + """ + body = {'name': 'Merged form letter (%s)' % source} + if output: + print(' - Copying template document as %r' % body['name']) + + # Call the Drive API to copy the template document. + return service.files().copy(body=body, fileId=tmpl_id, + fields='id').execute().get('id') + +def merge_template(tmpl_id=DOCS_FILE_ID, source='text', output=False): + """Merge the new letter template copy and return its file ID. + The 'output' flag toggles verbose output. + """ + # Copy the template and get the file ID of the new copy. + copy_id = _copy_template(tmpl_id, source, DRIVE, output) + + # Build the requests to make all substitutions in the mail merge. + if output: + print(' - Replacing placeholder variables') + reqs = [{'replaceAllText': { + 'containsText': { + 'text': '{{%s}}' % key.upper(), + 'matchCase': True, + }, + 'replaceText': value, + }} for key, value in (merge.iteritems() \ + if hasattr({}, 'iteritems') else merge.items())] + + # Use the Docs API to merge the data in the new copied document. + DOCS.documents().batchUpdate(body={'requests': reqs}, + documentId=copy_id, fields='').execute() + return copy_id + + +if __name__ == '__main__': + merge.update(get_data(SOURCE, OUTPUT)) + file_id = merge_template(source=SOURCE, output=OUTPUT) + if OUTPUT: + print(' - New merged letter: docs.google.com/document/d/%s/edit' % file_id) diff --git a/docs/mail-merge/docs_mail_merge_test.py b/docs/mail-merge/docs_mail_merge_test.py new file mode 100644 index 00000000..b70be0dc --- /dev/null +++ b/docs/mail-merge/docs_mail_merge_test.py @@ -0,0 +1,96 @@ +# Copyright 2018-2019 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at apache.org/licenses/LICENSE-2.0. +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# 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. + +""" +docs_mail_merge_test.py -- unit test for docs_mail_merge.py: + 1. test credentials file availability + 2. test whether project can authorize OAuth2 credentials + 3. test whether project can connect to all 3 APIs + 4. test creation (and deletion) of Google Docs file + 5. test copying (and deletion) of Google Docs file + 6. test getting plain text data + 7. test getting data from Google Sheets spreadsheet +""" + +import os +import unittest +from googleapiclient import discovery +from docs_mail_merge5 import (CREDS_FILE, get_data, get_http_client, + merge_template, _copy_template) + +class TestDocsMailMerge(unittest.TestCase): + def test_project(self): + self.assertTrue(project_test()) + def test_oauth2(self): + self.assertTrue(oauth2_test()) + def test_gapis(self): + self.assertTrue(gapis_test()) + def test_create_doc(self): + self.assertTrue(create_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_sheets_data(self): + self.assertTrue(bool(get_sheets_data_test())) + +def project_test(): + 'Tests whether project credentials file was downloaded from project.' + if os.path.exists(CREDS_FILE): + return True + raise IOError('''\ + ERROR: Must create a Google APIs project, enable both + the Drive and Docs REST APIs, create and download OAuth2 + client credentials as %r before unit test can run.''' % CREDS_FILE) + +def oauth2_test(): + 'Tests whether project credentials can be used to call Google APIs.' + discovery.build('oauth2', 'v2', http=get_http_client()).userinfo().get().execute() + return True + +def gapis_test(): + 'Tests whether project can connect to all 3 APIs used in the sample.' + HTTP = get_http_client() + discovery.build('drive', 'v3', http=HTTP) + discovery.build('docs', 'v1', http=HTTP) + discovery.build('sheets', 'v4', http=HTTP) + return True + +def create_doc_test(): + 'Tests whether project can create and delete a Google Docs file.' + DRIVE = discovery.build('drive', 'v3', http=get_http_client()) + 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', http=get_http_client()) + DOCS_FILE_ID = '1Rr7eKm3tvUgRKRoOYVSMF69IVAHIOPS72-l0CzsPmfM' + doc_id = _copy_template(DOCS_FILE_ID, 'text') + DRIVE.files().delete(fileId=doc_id, fields='').execute() + return True + +def get_text_data_test(): + 'Tests reading plain text data.' + return get_data(output=False) + +def get_sheets_data_test(): + 'Tests reading Google Sheets data.' + return get_data(source='sheets', output=False) + +if __name__ == '__main__': + unittest.main() From a5c509e9c2de7bb3f0ca4423f2b8676e22b10232 Mon Sep 17 00:00:00 2001 From: Wesley Chun Date: Wed, 13 Mar 2019 01:28:39 -0700 Subject: [PATCH 02/10] pylint & eval fixes --- docs/mail-merge/docs_mail_merge.py | 27 ++++++++++++++++--------- docs/mail-merge/docs_mail_merge_test.py | 5 +++-- 2 files changed, 20 insertions(+), 12 deletions(-) diff --git a/docs/mail-merge/docs_mail_merge.py b/docs/mail-merge/docs_mail_merge.py index af8d746d..e1f31f31 100644 --- a/docs/mail-merge/docs_mail_merge.py +++ b/docs/mail-merge/docs_mail_merge.py @@ -25,8 +25,8 @@ from oauth2client import file, client, tools # fill-in your template file ID -DOCS_FILE_ID = YOUR_TMPL_DOC_FILE_ID # Docs template -SHEETS_FILE_ID = YOUR_SHEET_DATA_FILE_ID # Sheets data source +DOCS_FILE_ID = 'YOUR_TMPL_DOC_FILE_ID' # Docs template +SHEETS_FILE_ID = 'YOUR_SHEET_DATA_FILE_ID' # Sheets data source CREDS_FILE = 'credentials.json' SCOPES = ( # iterable or space-delimited string 'https://www.googleapis.com/auth/drive', @@ -35,6 +35,7 @@ ) COLUMNS = ['to_name', 'to_title', 'to_company', 'to_address'] OUTPUT = True # change to False to suppress output +SOURCES = ('text', 'sheets') SOURCE = 'text' # or 'sheets' to change data source def get_http_client(): @@ -56,7 +57,8 @@ def get_http_client(): # plain text data source TARGET_TEXT = [ - 'Ms. Lara Brown', 'Googler', 'Google NYC', '111 8th Ave\nNew York, NY 10011-5201', + 'Ms. Lara Brown', 'Googler', 'Google NYC', + '111 8th Ave\nNew York, NY 10011-5201' ] # fill-in your data to merge into document template variables @@ -68,15 +70,17 @@ def get_http_client(): # - - - - - - - - - - - - - - - - - - - - - - - - - - 'date': time.ctime(), # - - - - - - - - - - - - - - - - - - - - - - - - - - - '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 Android phones.' + '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 Android phones.' } def get_data(source='text', output=True): """Gets mail merge data from chosen data source. """ if source not in {'sheets', 'text'}: - raise ValueError('ERROR: unsupported data type %r... must be "sheets" or "text"' % source) - func = eval('_get_%s_data' % source) + raise ValueError('ERROR: unsupported source %r; must be "sheets" or "text"' % source) + func = SAFE_DISPATCH[source] return dict(zip(COLUMNS, func(output=output))) def _get_text_data(output=False): @@ -98,6 +102,8 @@ def _get_sheets_data(service=SHEETS, output=False): return SHEETS.spreadsheets().values().get(spreadsheetId=SHEETS_FILE_ID, range='Sheet1').execute().get('values')[0] # one row only +SAFE_DISPATCH = {k: globals().get('_get_%s_data' % k) for k in SOURCES} + def _copy_template(tmpl_id, source, service=DRIVE, output=False): """Private function that copies the letter template document then returns the new file ID. The 'output' flag toggles verbose output. @@ -136,7 +142,8 @@ def merge_template(tmpl_id=DOCS_FILE_ID, source='text', output=False): if __name__ == '__main__': - merge.update(get_data(SOURCE, OUTPUT)) - file_id = merge_template(source=SOURCE, output=OUTPUT) - if OUTPUT: - print(' - New merged letter: docs.google.com/document/d/%s/edit' % file_id) + if SOURCE in SOURCES: + merge.update(get_data(SOURCE, OUTPUT)) + file_id = merge_template(source=SOURCE, output=OUTPUT) + if OUTPUT: + print(' - New merged letter: docs.google.com/document/d/%s/edit' % file_id) diff --git a/docs/mail-merge/docs_mail_merge_test.py b/docs/mail-merge/docs_mail_merge_test.py index b70be0dc..ca06f642 100644 --- a/docs/mail-merge/docs_mail_merge_test.py +++ b/docs/mail-merge/docs_mail_merge_test.py @@ -24,7 +24,7 @@ import os import unittest from googleapiclient import discovery -from docs_mail_merge5 import (CREDS_FILE, get_data, get_http_client, +from docs_mail_merge import (CREDS_FILE, get_data, get_http_client, merge_template, _copy_template) class TestDocsMailMerge(unittest.TestCase): @@ -54,7 +54,8 @@ def project_test(): def oauth2_test(): 'Tests whether project credentials can be used to call Google APIs.' - discovery.build('oauth2', 'v2', http=get_http_client()).userinfo().get().execute() + discovery.build('oauth2', 'v2', + http=get_http_client()).userinfo().get().execute() return True def gapis_test(): From 1e0734c61063637f11602339fff4b1d63c6b2e9f Mon Sep 17 00:00:00 2001 From: Wesley Chun Date: Wed, 13 Mar 2019 14:31:17 -0700 Subject: [PATCH 03/10] lint fixes --- docs/mail-merge/default.profraw | Bin 0 -> 2056 bytes docs/mail-merge/docs_mail_merge.py | 18 +++++++++--------- docs/mail-merge/docs_mail_merge_test.py | 9 +++++---- 3 files changed, 14 insertions(+), 13 deletions(-) create mode 100644 docs/mail-merge/default.profraw diff --git a/docs/mail-merge/default.profraw b/docs/mail-merge/default.profraw new file mode 100644 index 0000000000000000000000000000000000000000..49d265da31d9e052c5e1c144a90cce00e08634bf GIT binary patch literal 2056 zcmZoHO3N=Q$obF000E*%Jl2)hbS5qF(?cH`F>*(d$( zNW#T7==IGd;@eF&yr1FHT24)r(f zXB+Qt_fm z)4TR*MzM36EXjbXH$YPl3(t)lR;We{}QG$1;;+F3kKL zQ1uVWu$zCuPU=p5ll9&}70roDJh&JRK-DiOM^z6qUr^xgMc+>a&U*u*A2mI5YJ31y z&rpG?UKr{C8Q;SP4X&C8NRTLM#yl{cV+K<{1FAj%hk97JkJ6(d zFdRdGiAYZ^V?M)JacgSdX+LH|9@nYzs{}-)%NFZtba$;_eyy=&`pk?;7Mt!){87DZ z>B^9Z(&yDRe>U7bXY_QHJd@eB+k2IlhDD!m>SMQT70*~NbNa)o6XF{d8g1Wk!p`|% z`tJ65((KE!EYBtVh}h;Ky5|nJfMMgS@2wTGz4os<78zC?ea~!{-;sTP|JqNRi|c>C zGY*^)qhsv5!#mE_?(XyT@@K@E?<&1joZ59DWd7VIvkx9)k&y%Qb Xi&k%|OH+M;&D!u;bqsed&Qk*bkdHde literal 0 HcmV?d00001 diff --git a/docs/mail-merge/docs_mail_merge.py b/docs/mail-merge/docs_mail_merge.py index e1f31f31..b61100de 100644 --- a/docs/mail-merge/docs_mail_merge.py +++ b/docs/mail-merge/docs_mail_merge.py @@ -50,9 +50,9 @@ def get_http_client(): return creds.authorize(Http()) # create service endpoints to the 3 APIs -HTTP = get_http_client() -DRIVE = discovery.build('drive', 'v3', http=HTTP) -DOCS = discovery.build('docs', 'v1', http=HTTP) +HTTP = get_http_client() +DRIVE = discovery.build('drive', 'v3', http=HTTP) +DOCS = discovery.build('docs', 'v1', http=HTTP) SHEETS = discovery.build('sheets', 'v4', http=HTTP) # plain text data source @@ -79,7 +79,8 @@ def get_data(source='text', output=True): """Gets mail merge data from chosen data source. """ if source not in {'sheets', 'text'}: - raise ValueError('ERROR: unsupported source %r; must be "sheets" or "text"' % source) + raise ValueError('ERROR: unsupported source %r; choose %r' % ( + source, SOURCES)) func = SAFE_DISPATCH[source] return dict(zip(COLUMNS, func(output=output))) @@ -99,7 +100,7 @@ def _get_sheets_data(service=SHEETS, output=False): """ if output: print(' - Using data from Google Sheets') - return SHEETS.spreadsheets().values().get(spreadsheetId=SHEETS_FILE_ID, + return service.spreadsheets().values().get(spreadsheetId=SHEETS_FILE_ID, range='Sheet1').execute().get('values')[0] # one row only SAFE_DISPATCH = {k: globals().get('_get_%s_data' % k) for k in SOURCES} @@ -132,8 +133,7 @@ def merge_template(tmpl_id=DOCS_FILE_ID, source='text', output=False): 'matchCase': True, }, 'replaceText': value, - }} for key, value in (merge.iteritems() \ - if hasattr({}, 'iteritems') else merge.items())] + }} for key, value in (merge.iteritems() if hasattr({}, 'iteritems') else merge.items())] # Use the Docs API to merge the data in the new copied document. DOCS.documents().batchUpdate(body={'requests': reqs}, @@ -144,6 +144,6 @@ def merge_template(tmpl_id=DOCS_FILE_ID, source='text', output=False): if __name__ == '__main__': if SOURCE in SOURCES: merge.update(get_data(SOURCE, OUTPUT)) - file_id = merge_template(source=SOURCE, output=OUTPUT) + fid = merge_template(source=SOURCE, output=OUTPUT) if OUTPUT: - print(' - New merged letter: docs.google.com/document/d/%s/edit' % file_id) + print(' - Merged letter: docs.google.com/document/d/%s/edit' % fid) diff --git a/docs/mail-merge/docs_mail_merge_test.py b/docs/mail-merge/docs_mail_merge_test.py index ca06f642..5f503b5a 100644 --- a/docs/mail-merge/docs_mail_merge_test.py +++ b/docs/mail-merge/docs_mail_merge_test.py @@ -23,11 +23,12 @@ import os import unittest + from googleapiclient import discovery -from docs_mail_merge import (CREDS_FILE, get_data, get_http_client, - merge_template, _copy_template) +from docs_mail_merge import CREDS_FILE, get_data, get_http_client, _copy_template class TestDocsMailMerge(unittest.TestCase): + 'Unit tests for Mail Merge sample' def test_project(self): self.assertTrue(project_test()) def test_oauth2(self): @@ -61,8 +62,8 @@ def oauth2_test(): def gapis_test(): 'Tests whether project can connect to all 3 APIs used in the sample.' HTTP = get_http_client() - discovery.build('drive', 'v3', http=HTTP) - discovery.build('docs', 'v1', http=HTTP) + discovery.build('drive', 'v3', http=HTTP) + discovery.build('docs', 'v1', http=HTTP) discovery.build('sheets', 'v4', http=HTTP) return True From 2e4ad409d0ee2486b7ac5390a9085058d702a616 Mon Sep 17 00:00:00 2001 From: Wesley Chun Date: Wed, 13 Mar 2019 14:39:44 -0700 Subject: [PATCH 04/10] final(?) lint fixes --- docs/mail-merge/docs_mail_merge.py | 5 ++++- docs/mail-merge/docs_mail_merge_test.py | 3 ++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/mail-merge/docs_mail_merge.py b/docs/mail-merge/docs_mail_merge.py index b61100de..47893865 100644 --- a/docs/mail-merge/docs_mail_merge.py +++ b/docs/mail-merge/docs_mail_merge.py @@ -127,13 +127,16 @@ def merge_template(tmpl_id=DOCS_FILE_ID, source='text', output=False): # Build the requests to make all substitutions in the mail merge. if output: print(' - Replacing placeholder variables') + + # Get key-value pairs (prefer iterators) and merge template values + context = merge.iteritems() if hasattr({}, 'iteritems') else merge.items() reqs = [{'replaceAllText': { 'containsText': { 'text': '{{%s}}' % key.upper(), 'matchCase': True, }, 'replaceText': value, - }} for key, value in (merge.iteritems() if hasattr({}, 'iteritems') else merge.items())] + }} for key, value in context] # Use the Docs API to merge the data in the new copied document. DOCS.documents().batchUpdate(body={'requests': reqs}, diff --git a/docs/mail-merge/docs_mail_merge_test.py b/docs/mail-merge/docs_mail_merge_test.py index 5f503b5a..ac950068 100644 --- a/docs/mail-merge/docs_mail_merge_test.py +++ b/docs/mail-merge/docs_mail_merge_test.py @@ -25,7 +25,8 @@ import unittest from googleapiclient import discovery -from docs_mail_merge import CREDS_FILE, get_data, get_http_client, _copy_template +from docs_mail_merge import ( + CREDS_FILE, get_data, get_http_client, _copy_template) class TestDocsMailMerge(unittest.TestCase): 'Unit tests for Mail Merge sample' From d5b77f4876e57e645b0956cc46e8429a22b84214 Mon Sep 17 00:00:00 2001 From: Wesley Chun Date: Thu, 14 Mar 2019 22:38:25 -0700 Subject: [PATCH 05/10] PR fixes and code cleanup --- docs/mail-merge/CONTRIBUTING.md | 36 ------ docs/mail-merge/LICENSE | 201 ----------------------------- docs/mail-merge/README.md | 18 +-- docs/mail-merge/default.profraw | Bin 2056 -> 0 bytes docs/mail-merge/docs_mail_merge.py | 108 +++++++--------- 5 files changed, 53 insertions(+), 310 deletions(-) delete mode 100644 docs/mail-merge/CONTRIBUTING.md delete mode 100644 docs/mail-merge/LICENSE delete mode 100644 docs/mail-merge/default.profraw diff --git a/docs/mail-merge/CONTRIBUTING.md b/docs/mail-merge/CONTRIBUTING.md deleted file mode 100644 index 3e0558e0..00000000 --- a/docs/mail-merge/CONTRIBUTING.md +++ /dev/null @@ -1,36 +0,0 @@ -# How to become a contributor and submit your own code - -## Contributor License Agreements - -We'd love to accept your sample apps and patches! Before we can take them, we -have to jump a couple of legal hurdles. - -Please fill out either the individual or corporate Contributor License Agreement -(CLA). - - * If you are an individual writing original source code and you're sure you - own the intellectual property, then you'll need to sign an [individual CLA] - (https://developers.google.com/open-source/cla/individual). - * If you work for a company that wants to allow you to contribute your work, - then you'll need to sign a [corporate CLA] - (https://developers.google.com/open-source/cla/corporate). - -Follow either of the two links above to access the appropriate CLA and -instructions for how to sign and return it. Once we receive it, we'll be able to -accept your pull requests. - -## Contributing A Patch - -1. Submit an issue describing your proposed change to the repo in question. -1. The repo owner will respond to your issue promptly. -1. If your proposed change is accepted, and you haven't already done so, sign a - Contributor License Agreement (see details above). -1. Fork the desired repo, develop and test your code changes. -1. Ensure that your code adheres to the existing style in the sample to which - you are contributing. Refer to the - [Google Cloud Platform Samples Style Guide] - (https://github.com/GoogleCloudPlatform/Template/wiki/style.html) for the - recommended coding standards for this organization. -1. Ensure that your code has an appropriate set of unit tests which all pass. -1. Submit a pull request. - diff --git a/docs/mail-merge/LICENSE b/docs/mail-merge/LICENSE deleted file mode 100644 index 01de3bce..00000000 --- a/docs/mail-merge/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright 2018 Google LLC - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - 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. diff --git a/docs/mail-merge/README.md b/docs/mail-merge/README.md index 6db0cec5..89f8a862 100644 --- a/docs/mail-merge/README.md +++ b/docs/mail-merge/README.md @@ -11,9 +11,9 @@ Before getting started, create a new project (or reuse an existing one) at with Google Drive and Docs APIs enabled. (See the videos listed below if you're new to Google APIs.) Then install the Google APIs Client Library for Python if you haven't already: `pip{,3} install -U google-api-python-client` -This sample app requires you to [create a new Google Docs file](https://docs.google.com). Choose whatever template you wish to use, but we suggest using the Letter/Spearmint one to keep things simple. Replace the contact information in the Doc with template variables that we can merge with desired data. +This sample app requires you to [create a new Google Docs file](https://docs.google.com). Choose the template you wish to use, but we suggest using Letter/Spearmint to keep things simple. Replace the contact information in the Doc with template variables that we can merge with desired data. -Here is a [sample Letter template](https://drive.google.com/open?id=1Rr7eKm3tvUgRKRoOYVSMF69IVAHIOPS72-l0CzsPmfM) to get an idea of what we mean: ![sample Letter template](https://user-images.githubusercontent.com/1102504/44741564-51ea2480-aab2-11e8-871c-a836626b2a0d.png "sample Letter template") +Here is a [sample letter template](https://drive.google.com/open?id=1Rr7eKm3tvUgRKRoOYVSMF69IVAHIOPS72-l0CzsPmfM) to get an idea of what we mean: ![sample letter template](https://user-images.githubusercontent.com/1102504/44741564-51ea2480-aab2-11e8-871c-a836626b2a0d.png "sample letter template") In the document, the variable names used by the sample app are: @@ -48,15 +48,7 @@ The application currently supports two different sources of data, plain text and ## Testing -The unit-test script is `docs_mail_merge_test.py`; these are the current tests available: - -1. Confirm OAuth2 credentials file was downloaded from the API project in the developers console as `credentials.json`. -1. Confirm those OAuth2 credentials can issue requests to Google APIs -1. Confirm project can connect to the Drive, Sheets, and Docs APIs -1. Confirm correct project setup & enabled-APIs by creating & deleting a temp Docs file. -1. Confirm correct project setup & enabled-APIs by copying an existing Docs file then deleting it. -1. Confirm application can retrieve data from plain text source. -1. Confirm application can retrieve data from Google Sheets source. +The unit-test script is `docs_mail_merge_test.py`; see the file for a list of the available tests. ## Reference @@ -65,12 +57,12 @@ The unit-test script is `docs_mail_merge_test.py`; these are the current tests a - [Support channels](https://developers.google.com/drive/api/v3/support) - Google Docs API - [API documentation](https://developers.google.com/docs) - - [Python Quickstart](https://developers.google.com/docs/api/quickstart/python) + - [Python quickstart](https://developers.google.com/docs/api/quickstart/python) - [Support channels](https://developers.google.com/docs/api/support) - Google Sheets API - [API documentation](https://developers.google.com/sheets) - [Support channels](https://developers.google.com/sheets/api/support) -- [Google APIs Client Libraries](https://developers.google.com/api-client-library) +- [Google APIs client libraries](https://developers.google.com/api-client-library) - [G Suite developer overview & video](https://developers.google.com/gsuite) - [G Suite (REST) APIs intro codelab](https://g.co/codelabs/gsuite-apis-intro) (~half-hour) - Introductory API videos diff --git a/docs/mail-merge/default.profraw b/docs/mail-merge/default.profraw deleted file mode 100644 index 49d265da31d9e052c5e1c144a90cce00e08634bf..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2056 zcmZoHO3N=Q$obF000E*%Jl2)hbS5qF(?cH`F>*(d$( zNW#T7==IGd;@eF&yr1FHT24)r(f zXB+Qt_fm z)4TR*MzM36EXjbXH$YPl3(t)lR;We{}QG$1;;+F3kKL zQ1uVWu$zCuPU=p5ll9&}70roDJh&JRK-DiOM^z6qUr^xgMc+>a&U*u*A2mI5YJ31y z&rpG?UKr{C8Q;SP4X&C8NRTLM#yl{cV+K<{1FAj%hk97JkJ6(d zFdRdGiAYZ^V?M)JacgSdX+LH|9@nYzs{}-)%NFZtba$;_eyy=&`pk?;7Mt!){87DZ z>B^9Z(&yDRe>U7bXY_QHJd@eB+k2IlhDD!m>SMQT70*~NbNa)o6XF{d8g1Wk!p`|% z`tJ65((KE!EYBtVh}h;Ky5|nJfMMgS@2wTGz4os<78zC?ea~!{-;sTP|JqNRi|c>C zGY*^)qhsv5!#mE_?(XyT@@K@E?<&1joZ59DWd7VIvkx9)k&y%Qb Xi&k%|OH+M;&D!u;bqsed&Qk*bkdHde diff --git a/docs/mail-merge/docs_mail_merge.py b/docs/mail-merge/docs_mail_merge.py index 47893865..b61df397 100644 --- a/docs/mail-merge/docs_mail_merge.py +++ b/docs/mail-merge/docs_mail_merge.py @@ -24,43 +24,41 @@ from httplib2 import Http from oauth2client import file, client, tools -# fill-in your template file ID -DOCS_FILE_ID = 'YOUR_TMPL_DOC_FILE_ID' # Docs template -SHEETS_FILE_ID = 'YOUR_SHEET_DATA_FILE_ID' # Sheets data source -CREDS_FILE = 'credentials.json' +# Fill-in IDs of your Docs template & any Sheets data source +DOCS_FILE_ID = 'YOUR_TMPL_DOC_FILE_ID' +SHEETS_FILE_ID = 'YOUR_SHEET_DATA_FILE_ID' + +# authorization constants +CLIENT_ID_FILE = 'credentials.json' +TOKEN_STORE_FILE = 'token.json' 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', ) -COLUMNS = ['to_name', 'to_title', 'to_company', 'to_address'] -OUTPUT = True # change to False to suppress output + +# application constants SOURCES = ('text', 'sheets') -SOURCE = 'text' # or 'sheets' to change data source +SOURCE = 'text' # Choose one of the data SOURCES +COLUMNS = ['to_name', 'to_title', 'to_company', 'to_address'] def get_http_client(): - """Manage OAuth tokens in 'token.json' file given the downloaded - 'credentials.json' file along with requested OAuth2 scopes. + """Uses project credentials in CLIENT_ID_FILE along with requested OAuth2 + scopes for authorization, and caches API tokens in TOKEN_STORE_FILE. """ - store = file.Storage('token.json') + store = file.Storage(TOKEN_STORE_FILE) creds = store.get() if not creds or creds.invalid: - flow = client.flow_from_clientsecrets(CREDS_FILE, SCOPES) + flow = client.flow_from_clientsecrets(CLIENT_ID_FILE, SCOPES) creds = tools.run_flow(flow, store) return creds.authorize(Http()) -# create service endpoints to the 3 APIs +# service endpoints to Google APIs HTTP = get_http_client() DRIVE = discovery.build('drive', 'v3', http=HTTP) DOCS = discovery.build('docs', 'v1', http=HTTP) SHEETS = discovery.build('sheets', 'v4', http=HTTP) -# plain text data source -TARGET_TEXT = [ - 'Ms. Lara Brown', 'Googler', 'Google NYC', - '111 8th Ave\nNew York, NY 10011-5201' -] - # fill-in your data to merge into document template variables merge = { 'my_name': 'Mr. Jeff Erson', @@ -75,70 +73,61 @@ def get_http_client(): 'in his keynote that users love their new Android phones.' } -def get_data(source='text', output=True): +def get_data(source='text'): """Gets mail merge data from chosen data source. """ if source not in {'sheets', 'text'}: - raise ValueError('ERROR: unsupported source %r; choose %r' % ( + raise ValueError('ERROR: unsupported source %r; choose from %r' % ( source, SOURCES)) func = SAFE_DISPATCH[source] - return dict(zip(COLUMNS, func(output=output))) + return dict(zip(COLUMNS, func())) -def _get_text_data(output=False): - """Private function that returns data from plain text source. +def _get_text_data(): + """(private) Returns plain text data. """ - if output: - print(' - Using static text data') - return TARGET_TEXT - -def _get_sheets_data(service=SHEETS, output=False): - """Private function that returns data from Google Sheets source. - Note: this sample code gets all cells in 'Sheet1', the first - default Sheet in a spreadsheet. Use any desired data range - you need (in standard A1 notation). Sample returns only 1 row. - The 'output' flag toggles verbose output. + return [ + 'Ms. Lara Brown', 'Googler', 'Google NYC', + '111 8th Ave\nNew York, NY 10011-5201' + ] + +def _get_sheets_data(service=SHEETS): + """(private) Returns data from Google Sheets source. NOTE: this sample + code gets all cells in 'Sheet1', the first default Sheet in a + spreadsheet. Use any desired data range (in standard A1 notation). + This sample app is coded to return only the 2nd row (the data). """ - if output: - print(' - Using data from Google Sheets') return service.spreadsheets().values().get(spreadsheetId=SHEETS_FILE_ID, - range='Sheet1').execute().get('values')[0] # one row only + range='Sheet1!2:2').execute().get('values')[0] # 2nd row only +# data source dispatch table [better alternative to using eval()] SAFE_DISPATCH = {k: globals().get('_get_%s_data' % k) for k in SOURCES} -def _copy_template(tmpl_id, source, service=DRIVE, output=False): - """Private function that copies the letter template document then - returns the new file ID. The 'output' flag toggles verbose output. +def _copy_template(tmpl_id, source, service=DRIVE): + """(private) Copies letter template document using Drive API then + returns file ID of (new) copy. """ body = {'name': 'Merged form letter (%s)' % source} - if output: - print(' - Copying template document as %r' % body['name']) - - # Call the Drive API to copy the template document. return service.files().copy(body=body, fileId=tmpl_id, fields='id').execute().get('id') -def merge_template(tmpl_id=DOCS_FILE_ID, source='text', output=False): - """Merge the new letter template copy and return its file ID. - The 'output' flag toggles verbose output. +def merge_template(tmpl_id=DOCS_FILE_ID, source='text'): + """Copies template document and merges data into newly-minted copy then + returns its file ID. """ - # Copy the template and get the file ID of the new copy. - copy_id = _copy_template(tmpl_id, source, DRIVE, output) - - # Build the requests to make all substitutions in the mail merge. - if output: - print(' - Replacing placeholder variables') - - # Get key-value pairs (prefer iterators) and merge template values + # copy template and set context data struct for merging template values + copy_id = _copy_template(tmpl_id, source, DRIVE) context = merge.iteritems() if hasattr({}, 'iteritems') else merge.items() + + # "search & replace" API requests for mail merge substitutions reqs = [{'replaceAllText': { 'containsText': { - 'text': '{{%s}}' % key.upper(), + 'text': '{{%s}}' % key.upper(), # {{VARS}} are uppercase 'matchCase': True, }, 'replaceText': value, }} for key, value in context] - # Use the Docs API to merge the data in the new copied document. + # send requests to Docs API to do actual merge DOCS.documents().batchUpdate(body={'requests': reqs}, documentId=copy_id, fields='').execute() return copy_id @@ -146,7 +135,6 @@ def merge_template(tmpl_id=DOCS_FILE_ID, source='text', output=False): if __name__ == '__main__': if SOURCE in SOURCES: - merge.update(get_data(SOURCE, OUTPUT)) - fid = merge_template(source=SOURCE, output=OUTPUT) - if OUTPUT: - print(' - Merged letter: docs.google.com/document/d/%s/edit' % fid) + merge.update(get_data(SOURCE)) + fid = merge_template(source=SOURCE) + print('Merged letter: docs.google.com/document/d/%s/edit' % fid) From 4ec846e14e674915d7af587dfd6b8f1f027586f1 Mon Sep 17 00:00:00 2001 From: Wesley Chun Date: Thu, 14 Mar 2019 22:59:00 -0700 Subject: [PATCH 06/10] more cleanup & fixed brokenness from last commit --- docs/mail-merge/docs_mail_merge.py | 21 +++++++++--------- docs/mail-merge/docs_mail_merge_test.py | 29 ++++++++++--------------- 2 files changed, 22 insertions(+), 28 deletions(-) diff --git a/docs/mail-merge/docs_mail_merge.py b/docs/mail-merge/docs_mail_merge.py index b61df397..03c343b0 100644 --- a/docs/mail-merge/docs_mail_merge.py +++ b/docs/mail-merge/docs_mail_merge.py @@ -41,6 +41,10 @@ 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\nNew York, NY 10011-5201' +] def get_http_client(): """Uses project credentials in CLIENT_ID_FILE along with requested OAuth2 @@ -73,7 +77,7 @@ def get_http_client(): 'in his keynote that users love their new Android phones.' } -def get_data(source='text'): +def get_data(source): """Gets mail merge data from chosen data source. """ if source not in {'sheets', 'text'}: @@ -83,12 +87,9 @@ def get_data(source='text'): return dict(zip(COLUMNS, func())) def _get_text_data(): - """(private) Returns plain text data. + """(private) Returns plain text data; can alter to read from CSV file. """ - return [ - 'Ms. Lara Brown', 'Googler', 'Google NYC', - '111 8th Ave\nNew York, NY 10011-5201' - ] + return TEXT_SOURCE_DATA def _get_sheets_data(service=SHEETS): """(private) Returns data from Google Sheets source. NOTE: this sample @@ -102,7 +103,7 @@ def _get_sheets_data(service=SHEETS): # data source dispatch table [better alternative to using eval()] SAFE_DISPATCH = {k: globals().get('_get_%s_data' % k) for k in SOURCES} -def _copy_template(tmpl_id, source, service=DRIVE): +def _copy_template(tmpl_id, source, service): """(private) Copies letter template document using Drive API then returns file ID of (new) copy. """ @@ -110,12 +111,12 @@ def _copy_template(tmpl_id, source, service=DRIVE): return service.files().copy(body=body, fileId=tmpl_id, fields='id').execute().get('id') -def merge_template(tmpl_id=DOCS_FILE_ID, source='text'): +def merge_template(tmpl_id, source, service): """Copies template document and merges data into newly-minted copy then returns its file ID. """ # copy template and set context data struct for merging template values - copy_id = _copy_template(tmpl_id, source, DRIVE) + 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 @@ -136,5 +137,5 @@ def merge_template(tmpl_id=DOCS_FILE_ID, source='text'): if __name__ == '__main__': if SOURCE in SOURCES: merge.update(get_data(SOURCE)) - fid = merge_template(source=SOURCE) + fid = merge_template(DOCS_FILE_ID, SOURCE, DRIVE) print('Merged letter: docs.google.com/document/d/%s/edit' % fid) diff --git a/docs/mail-merge/docs_mail_merge_test.py b/docs/mail-merge/docs_mail_merge_test.py index ac950068..cd32c1e8 100644 --- a/docs/mail-merge/docs_mail_merge_test.py +++ b/docs/mail-merge/docs_mail_merge_test.py @@ -13,20 +13,19 @@ """ docs_mail_merge_test.py -- unit test for docs_mail_merge.py: 1. test credentials file availability - 2. test whether project can authorize OAuth2 credentials - 3. test whether project can connect to all 3 APIs - 4. test creation (and deletion) of Google Docs file - 5. test copying (and deletion) of Google Docs file - 6. test getting plain text data - 7. test getting data from Google Sheets spreadsheet + 2. test whether project can connect to all 3 APIs + 3. test creation (and deletion) of Google Docs file + 4. test copying (and deletion) of Google Docs file + 5. test getting plain text data + 6. test getting data from Google Sheets spreadsheet """ import os import unittest from googleapiclient import discovery -from docs_mail_merge import ( - CREDS_FILE, get_data, get_http_client, _copy_template) +from docs_mail_merge6 import (CLIENT_ID_FILE, get_data, get_http_client, + merge_template, _copy_template) class TestDocsMailMerge(unittest.TestCase): 'Unit tests for Mail Merge sample' @@ -47,18 +46,12 @@ def test_get_sheets_data(self): def project_test(): 'Tests whether project credentials file was downloaded from project.' - if os.path.exists(CREDS_FILE): + if os.path.exists(CLIENT_ID_FILE): return True raise IOError('''\ ERROR: Must create a Google APIs project, enable both the Drive and Docs REST APIs, create and download OAuth2 - client credentials as %r before unit test can run.''' % CREDS_FILE) - -def oauth2_test(): - 'Tests whether project credentials can be used to call Google APIs.' - discovery.build('oauth2', 'v2', - http=get_http_client()).userinfo().get().execute() - return True + client credentials as %r before unit test can run.''' % CLIENT_ID_FILE) def gapis_test(): 'Tests whether project can connect to all 3 APIs used in the sample.' @@ -89,11 +82,11 @@ def copy_doc_test(): def get_text_data_test(): 'Tests reading plain text data.' - return get_data(output=False) + return get_data() def get_sheets_data_test(): 'Tests reading Google Sheets data.' - return get_data(source='sheets', output=False) + return get_data(source='sheets') if __name__ == '__main__': unittest.main() From 19586852789bed00249e62f4dc3bce55c23cbf38 Mon Sep 17 00:00:00 2001 From: Wesley Chun Date: Thu, 14 Mar 2019 23:04:27 -0700 Subject: [PATCH 07/10] unit test fixes --- docs/mail-merge/docs_mail_merge_test.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/docs/mail-merge/docs_mail_merge_test.py b/docs/mail-merge/docs_mail_merge_test.py index cd32c1e8..3021d1ed 100644 --- a/docs/mail-merge/docs_mail_merge_test.py +++ b/docs/mail-merge/docs_mail_merge_test.py @@ -25,14 +25,12 @@ from googleapiclient import discovery from docs_mail_merge6 import (CLIENT_ID_FILE, get_data, get_http_client, - merge_template, _copy_template) + _copy_template) class TestDocsMailMerge(unittest.TestCase): 'Unit tests for Mail Merge sample' def test_project(self): self.assertTrue(project_test()) - def test_oauth2(self): - self.assertTrue(oauth2_test()) def test_gapis(self): self.assertTrue(gapis_test()) def test_create_doc(self): From 4692d004e0de1f6a491c245da12dade5c0738f1e Mon Sep 17 00:00:00 2001 From: Wesley Chun Date: Thu, 14 Mar 2019 23:14:20 -0700 Subject: [PATCH 08/10] README missing one more reference to Sheets API --- docs/mail-merge/.README.md.swp | Bin 0 -> 20480 bytes docs/mail-merge/README.md | 4 ++-- 2 files changed, 2 insertions(+), 2 deletions(-) create mode 100644 docs/mail-merge/.README.md.swp diff --git a/docs/mail-merge/.README.md.swp b/docs/mail-merge/.README.md.swp new file mode 100644 index 0000000000000000000000000000000000000000..3606cacc4ac012f455230abb6b276e6795bb6fca GIT binary patch literal 20480 zcmeHN%Woq|8SmL$@!kb7a6_nO21tz3cI-HhnOzon;%s6jo@8w&%#cNKxw~xlq}|=q z)oo8^Gz%vVaNz)Z0cp{K1VZ8n2=)(v3m`ag;Iv3wxB$zFBmBOq_9HVvnOzR6K^5sI z$L{K{zWUYosK?h?+^^NyT7J>O-$yL#)vMol>G$@>&wX#lvPMEW^z&JN)XpAorxS)p zQ5=@?amWXGCyb+fFARIW!2bgXd6^m(`n^JQobZ_hJo{=s3GHFkl!k3>XFs1BL;^fMLKeU>JB87~r^M|0_2CuhRw|_y6Pl|F1u6S-%2)2K*HG zI#2;V33Q&ZEDkh)7lAiFWLf_Je)~bo`VH{?4_MY~KnLK!9?$|V0OtS;ck5i0bd06fh}MYxCs2~eb58=F7O@T6&x^p8(4miWtD+X1D^s&|6c+>0R9LZ1HSc54jP4(UJy2~WH*cr;l#%VwLZl7cmr za0WqRnQvD;Rc&#aa=WT3gWXO&=SU_zPR>$pB5C?cR@(8-2TU?&hFir~R%!JG<5A>$ zjv|dYX&i$=|CnV2OO}j6=6c<(pa)EbY3vBe!Y*@p!WUTNb1z_txRWp*xF^ZXv#ZC< z6KyJ$(16}Et*>!8?ENy z3$^Wy!&-IPh$SKO63M!r_2}(SZ)!ajtmIjRbwrYgn1vBpJo7MFA#uz2iFwGgjevMm z1d^k4!J2RmoozW|Qt&rc zfWtV*0h8DZdT=d26>J{jZl_@)WKP)xHE5&1Q`{@h8mTst%!Ls(U>uGkB0c{*l{D#> z7(({IlM?1ASuAd+LMFo1Rx~2wlnzep;jKPYLirjB)l?HQ5!nw@-^G(5*-0QqY+AfF zi7kj+EZ_s!O}kE2Z7%6PU=RaeXp=3^GF^>52G$i9qiNe0L#( z6w4+D9W1~MwdKN~dok~1u|-ej8(;m_q?=A0j--een2#DgmN^4=-B?J;Ivfuu93ec$ z9F9i4_#q~M`w^T9=_>Y|@uVbuyguMZh>dBanr6ypHq?#D!60F;v3-TLC%N(gFMw^R zG+1y8&s7_>{f)8tJg%gbGN(z->pwx(_tps8?#+V|6CY1)0~R%>!&qTAiQ*vS#(2 zG@2^gRLW$UUfroqIMWtNp)~==y4z}{H5o6XP<&JMC?V->Vxh?!7JZZsQfu{aAp@425V zHsV!rZLpLK_j-+Mjd17YezX3<%H`UAWvjNc+gvT#{^I&wxjX3AbCe!>$mEEyo+~&- z#St0(NU#CY{1tZLOhquD*!BjzClLA(<K;6*@k0+fqmuKt!Fht5Gzs};3PM0H3B801aj%buBl4RP$xD(7O1@Uba z@e0jIa0Fc}&d~Zu2nro|40SyUu87=OQlT!0C<;VgKtWS4`m&@#aaG$}Hv5wW7^Mz9 zOAh5m3c9+bDrxf-LGK`Q1<*{04zzmVH;02h?m?w~d1xg%Z zoudR{oq}|X`6M5JtB5#IVaUZYV#TJoLoqAz9bz-Hx~hSxZ;SYZF=5 zrw3N*q-1Em!IOjWZhg8dmbCfC zh)GMIcV?vH=&q3cDhoYHyL>tXk+ymP{k`1he%HnYK}@|)WKYh8SU40h4V!%ioAhV3 z8q*FY?M~bn>5jBOeGRNA&_^yf8ls~dPn>zeL8mqP9b3P1oKyS%9o*gj9H9IEaee>4 zvG3GnA7zPXj zh5^HXVZbn87%&XHdkkb-)VEvvnq3Q@R{ctQLRC;pUm;U!cX;mOFs~t(FjlQ}pZwOTw?4ULY#SttGyu`+}ISPe!ksqpN9xPToq~}zz z_$uF5f}E{HDb`4Bhnx^fk-$h_*Yg?~|9f};0vt&lEUP(>(N5#)5+ z|LEmH%jLzD^787My;2e@P7&oo<)Xu>T with Google Drive and Docs APIs enabled. (See the videos listed below if you're new to Google APIs.) Then install the Google APIs Client Library for Python if you haven't already: `pip{,3} install -U google-api-python-client` +Before getting started, create a new project (or reuse an existing one) at with Google Drive, Sheets, and Docs APIs enabled. (See the videos listed below if you're new to Google APIs.) Then install the Google APIs Client Library for Python if you haven't already: `pip{,3} install -U google-api-python-client` This sample app requires you to [create a new Google Docs file](https://docs.google.com). Choose the template you wish to use, but we suggest using Letter/Spearmint to keep things simple. Replace the contact information in the Doc with template variables that we can merge with desired data. @@ -42,7 +42,7 @@ Replace `YOUR_TMPL_DOC_FILE_ID` in the `docs_mail_merge.py` source file with thi ## Data source -The application currently supports two different sources of data, plain text and Google Sheets. By default, the sample uses plain text via the `TARGET_TEXT` variable. A better option is to use a Google Sheet. Enable the API for your project in the developers console, and change the `source` variable at the bottom to `'sheets'`. Be sure you create a Sheet which looks like the below and set the `SHEETS_FILE_ID` variable to its file ID. +The application currently supports two different sources of data, plain text and Google Sheets. By default, the sample uses plain text via the `TARGET_TEXT` variable. A better option is to use a Google Sheet. Enable the API for your project in the developers console, and change the `source` variable at the bottom to `'sheets'`. Be sure you create a Sheet structured like the one below. Here is one [example Sheet](https://docs.google.com/spreadsheets/d/1vaoqPYGL1cJvkogV36nu3AKQ5rUacXj9TV-zqTvXuMU/edit) you can model yours on. Ensure you then set the `SHEETS_FILE_ID` variable to the file ID of your Google Sheet. ![sample Sheets data source](https://user-images.githubusercontent.com/1102504/54064578-62e6c180-41ca-11e9-86f6-9d147ac17200.png "sample Sheets data source") From 21f1c0cdea8dade6dc2eec2026cdaeaad0899445 Mon Sep 17 00:00:00 2001 From: Wesley Chun Date: Thu, 14 Mar 2019 23:17:43 -0700 Subject: [PATCH 09/10] oops --- docs/mail-merge/.README.md.swp | Bin 20480 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 docs/mail-merge/.README.md.swp diff --git a/docs/mail-merge/.README.md.swp b/docs/mail-merge/.README.md.swp deleted file mode 100644 index 3606cacc4ac012f455230abb6b276e6795bb6fca..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 20480 zcmeHN%Woq|8SmL$@!kb7a6_nO21tz3cI-HhnOzon;%s6jo@8w&%#cNKxw~xlq}|=q z)oo8^Gz%vVaNz)Z0cp{K1VZ8n2=)(v3m`ag;Iv3wxB$zFBmBOq_9HVvnOzR6K^5sI z$L{K{zWUYosK?h?+^^NyT7J>O-$yL#)vMol>G$@>&wX#lvPMEW^z&JN)XpAorxS)p zQ5=@?amWXGCyb+fFARIW!2bgXd6^m(`n^JQobZ_hJo{=s3GHFkl!k3>XFs1BL;^fMLKeU>JB87~r^M|0_2CuhRw|_y6Pl|F1u6S-%2)2K*HG zI#2;V33Q&ZEDkh)7lAiFWLf_Je)~bo`VH{?4_MY~KnLK!9?$|V0OtS;ck5i0bd06fh}MYxCs2~eb58=F7O@T6&x^p8(4miWtD+X1D^s&|6c+>0R9LZ1HSc54jP4(UJy2~WH*cr;l#%VwLZl7cmr za0WqRnQvD;Rc&#aa=WT3gWXO&=SU_zPR>$pB5C?cR@(8-2TU?&hFir~R%!JG<5A>$ zjv|dYX&i$=|CnV2OO}j6=6c<(pa)EbY3vBe!Y*@p!WUTNb1z_txRWp*xF^ZXv#ZC< z6KyJ$(16}Et*>!8?ENy z3$^Wy!&-IPh$SKO63M!r_2}(SZ)!ajtmIjRbwrYgn1vBpJo7MFA#uz2iFwGgjevMm z1d^k4!J2RmoozW|Qt&rc zfWtV*0h8DZdT=d26>J{jZl_@)WKP)xHE5&1Q`{@h8mTst%!Ls(U>uGkB0c{*l{D#> z7(({IlM?1ASuAd+LMFo1Rx~2wlnzep;jKPYLirjB)l?HQ5!nw@-^G(5*-0QqY+AfF zi7kj+EZ_s!O}kE2Z7%6PU=RaeXp=3^GF^>52G$i9qiNe0L#( z6w4+D9W1~MwdKN~dok~1u|-ej8(;m_q?=A0j--een2#DgmN^4=-B?J;Ivfuu93ec$ z9F9i4_#q~M`w^T9=_>Y|@uVbuyguMZh>dBanr6ypHq?#D!60F;v3-TLC%N(gFMw^R zG+1y8&s7_>{f)8tJg%gbGN(z->pwx(_tps8?#+V|6CY1)0~R%>!&qTAiQ*vS#(2 zG@2^gRLW$UUfroqIMWtNp)~==y4z}{H5o6XP<&JMC?V->Vxh?!7JZZsQfu{aAp@425V zHsV!rZLpLK_j-+Mjd17YezX3<%H`UAWvjNc+gvT#{^I&wxjX3AbCe!>$mEEyo+~&- z#St0(NU#CY{1tZLOhquD*!BjzClLA(<K;6*@k0+fqmuKt!Fht5Gzs};3PM0H3B801aj%buBl4RP$xD(7O1@Uba z@e0jIa0Fc}&d~Zu2nro|40SyUu87=OQlT!0C<;VgKtWS4`m&@#aaG$}Hv5wW7^Mz9 zOAh5m3c9+bDrxf-LGK`Q1<*{04zzmVH;02h?m?w~d1xg%Z zoudR{oq}|X`6M5JtB5#IVaUZYV#TJoLoqAz9bz-Hx~hSxZ;SYZF=5 zrw3N*q-1Em!IOjWZhg8dmbCfC zh)GMIcV?vH=&q3cDhoYHyL>tXk+ymP{k`1he%HnYK}@|)WKYh8SU40h4V!%ioAhV3 z8q*FY?M~bn>5jBOeGRNA&_^yf8ls~dPn>zeL8mqP9b3P1oKyS%9o*gj9H9IEaee>4 zvG3GnA7zPXj zh5^HXVZbn87%&XHdkkb-)VEvvnq3Q@R{ctQLRC;pUm;U!cX;mOFs~t(FjlQ}pZwOTw?4ULY#SttGyu`+}ISPe!ksqpN9xPToq~}zz z_$uF5f}E{HDb`4Bhnx^fk-$h_*Yg?~|9f};0vt&lEUP(>(N5#)5+ z|LEmH%jLzD^787My;2e@P7&oo<)Xu>T Date: Fri, 15 Mar 2019 00:33:18 -0700 Subject: [PATCH 10/10] added Docs API video to README --- docs/mail-merge/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/mail-merge/README.md b/docs/mail-merge/README.md index f7bc7f4e..78d7a636 100644 --- a/docs/mail-merge/README.md +++ b/docs/mail-merge/README.md @@ -42,7 +42,7 @@ Replace `YOUR_TMPL_DOC_FILE_ID` in the `docs_mail_merge.py` source file with thi ## Data source -The application currently supports two different sources of data, plain text and Google Sheets. By default, the sample uses plain text via the `TARGET_TEXT` variable. A better option is to use a Google Sheet. Enable the API for your project in the developers console, and change the `source` variable at the bottom to `'sheets'`. Be sure you create a Sheet structured like the one below. Here is one [example Sheet](https://docs.google.com/spreadsheets/d/1vaoqPYGL1cJvkogV36nu3AKQ5rUacXj9TV-zqTvXuMU/edit) you can model yours on. Ensure you then set the `SHEETS_FILE_ID` variable to the file ID of your Google Sheet. +The application currently supports two different sources of data, plain text and Google Sheets. By default, the sample uses plain text via the `TARGET_TEXT` variable. A better option is to use a Google Sheet. Enable the API for your project in the developers console, and change the `source` variable at the bottom to `'sheets'`. Be sure you create a Sheet structured like the one below. Here is one [example Sheet](https://docs.google.com/spreadsheets/d/1vaoqPYGL1cJvkogV36nu3AKQ5rUacXj9TV-zqTvXuMU/edit) you can model yours with. Ensure you then set the `SHEETS_FILE_ID` variable to the file ID of your Google Sheet. ![sample Sheets data source](https://user-images.githubusercontent.com/1102504/54064578-62e6c180-41ca-11e9-86f6-9d147ac17200.png "sample Sheets data source") @@ -69,3 +69,4 @@ The unit-test script is `docs_mail_merge_test.py`; see the file for a list of th - [New Google APIs project setup](https://goo.gl/RbyTFD) (6:54) - [Common Python boilerplate code review](https://goo.gl/KMfbeK) (3:48) - [REST APIs intro (Drive API)](https://goo.gl/ZIgf8k) (6:20) + - [Introducing the Docs API](https://youtu.be/jeU-tWKeb6g) (2:57)