Last active
December 1, 2023 09:55
-
-
Save mattroz/e3cf49ce41da355ba245ddd7f33e681d to your computer and use it in GitHub Desktop.
Instructions for creating a doc and inserting some text
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import print_function | |
import pickle | |
import os.path | |
from googleapiclient.discovery import build | |
from google_auth_oauthlib.flow import InstalledAppFlow | |
from google.auth.transport.requests import Request | |
# If modifying these scopes, delete the file token.pickle. | |
SCOPES = ['https://www.googleapis.com/auth/drive.file'] | |
def main(): | |
"""Shows basic usage of the Docs API. | |
Prints the title of a sample document. | |
""" | |
creds = None | |
# The file token.pickle 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.pickle'): | |
with open('token.pickle', 'rb') as token: | |
creds = pickle.load(token) | |
# 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() | |
# Save the credentials for the next run | |
with open('token.pickle', 'wb') as token: | |
pickle.dump(creds, token) | |
service = build('docs', 'v1', credentials=creds) | |
title = 'My Document' | |
body = { | |
'title': title | |
} | |
doc = service.documents().create(body=body).execute() | |
title = doc.get('title') | |
_id = doc.get('documentId') | |
print(f'Created document with title: {title}, id: {_id}') | |
# Text insertion | |
text = "Some sample text. VERY HUGE CHARACTERS. CamelCaseSentence." | |
requests = [ | |
{ | |
'insertText': { | |
'location': { | |
'index': 1, | |
}, | |
'text': text | |
} | |
} | |
] | |
result = service.documents().batchUpdate(documentId=_id, body={'requests': requests}).execute() | |
if __name__ == '__main__': | |
main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import print_function | |
import pickle | |
import os.path | |
from googleapiclient.discovery import build | |
from google_auth_oauthlib.flow import InstalledAppFlow | |
from google.auth.transport.requests import Request | |
# If modifying these scopes, delete the file token.pickle. | |
SCOPES = ['https://www.googleapis.com/auth/drive.file'] | |
def main(): | |
"""Shows basic usage of the Docs API. | |
Prints the title of a sample document. | |
""" | |
creds = None | |
# The file token.pickle 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.pickle'): | |
with open('token.pickle', 'rb') as token: | |
creds = pickle.load(token) | |
# 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() | |
# Save the credentials for the next run | |
with open('token.pickle', 'wb') as token: | |
pickle.dump(creds, token) | |
docs_service = build('docs', 'v1', credentials=creds) | |
drive_service = build('drive', 'v3', credentials=creds) | |
doc_meta = create_document(title='SampleDocument', service=docs_service) | |
grant_permissions_to_file(file_id=doc_meta['documentId'], service=drive_service, role='writer') | |
def create_document(title, service): | |
body = { | |
'title': title | |
} | |
doc = service.documents().create(body=body).execute() | |
title = doc.get('title') | |
_id = doc.get('documentId') | |
print(f'Created document with title: {title}, id: {_id}') | |
# Text insertion | |
text = "Some sample text. VERY HUGE CHARACTERS. CamelCaseSentence." | |
requests = [ | |
{ | |
'insertText': { | |
'location': { | |
'index': 1, | |
}, | |
'text': text | |
} | |
} | |
] | |
result = service.documents().batchUpdate(documentId=_id, body={'requests': requests}).execute() | |
return {'documentId' : _id, 'title' : title} | |
def grant_permissions_to_file(file_id, service, role): | |
def callback(request_id, response, exception): | |
if exception: | |
# Handle error | |
print(exception) | |
else: | |
print("Permission Id: %s" % response.get('id')) | |
batch = service.new_batch_http_request(callback=callback) | |
user_permission = { | |
'type': 'anyone', | |
'role': role, | |
} | |
batch.add(service.permissions().create( | |
fileId=file_id, | |
body=user_permission, | |
fields='id', | |
)) | |
domain_permission = { | |
'type': 'domain', | |
'role': 'reader', | |
'domain': 'example.com' | |
} | |
batch.add(drive_service.permissions().create( | |
fileId=file_id, | |
body=domain_permission, | |
fields='id', | |
)) | |
batch.execute() | |
print(f"Granted \"{role}\" permission to file {file_id}'n") | |
if __name__ == '__main__': | |
main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1. Go to https://developers.google.com/docs/api/quickstart/python and download credentials.json by clicking on "DOWNLOAD CLIENT CONFIGURATION" | |
2. Put credentials.json in your working directory | |
3. Do `pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib` | |
4. See the code above. | |
Useful link on editing, inserting and deleting text: https://developers.google.com/docs/api/how-tos/move-text |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Lifesaver. Incredible effort. I'm so blessed to find this. Thank you so much