Last active
August 15, 2023 17:40
-
-
Save dewitt4/3fdb31c176fae4ceb516ff4efaf4b632 to your computer and use it in GitHub Desktop.
Python function that uses the Google Drive API to read documents from Google Drive
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
import os | |
import pickle | |
from googleapiclient.discovery import build | |
from googleapiclient.http import MediaIoBaseDownload | |
from google_auth_oauthlib.flow import InstalledAppFlow | |
from google.auth.transport.requests import Request | |
# If modifying these SCOPES, delete the token.pickle file. | |
SCOPES = ['https://www.googleapis.com/auth/drive.readonly'] | |
def authenticate_google_drive(): | |
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(port=0) | |
# Save the credentials for the next run | |
with open('token.pickle', 'wb') as token: | |
pickle.dump(creds, token) | |
return creds | |
def read_google_doc(document_id): | |
creds = authenticate_google_drive() | |
service = build('drive', 'v3', credentials=creds) | |
try: | |
request = service.files().export_media(fileId=document_id, | |
mimeType='application/pdf') | |
fh = open(f'{document_id}.pdf', 'wb') | |
downloader = MediaIoBaseDownload(fh, request) | |
done = False | |
while done is False: | |
status, done = downloader.next_chunk() | |
print(f'Download {int(status.progress() * 100)}%') | |
fh.close() | |
print(f'Document downloaded as {document_id}.pdf') | |
except Exception as e: | |
print(f'An error occurred: {e}') | |
if __name__ == '__main__': | |
document_id = 'YOUR_DOCUMENT_ID' | |
read_google_doc(document_id) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment