Skip to content

Instantly share code, notes, and snippets.

@hornc
Last active July 1, 2021 00:01
Show Gist options
  • Save hornc/6adacb31af7129a0ffadaf6f96a5dad1 to your computer and use it in GitHub Desktop.
Save hornc/6adacb31af7129a0ffadaf6f96a5dad1 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
# Based on Google Drive v3 API Quickstart example
# https://developers.google.com/drive/api/v3/quickstart/python
import os.path
import io
import sys
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/drive.readonly']
TYPE_FOLDER = 'application/vnd.google-apps.folder'
def get_service():
"""Login and return service."""
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.
path = os.path.dirname(__file__) + '/'
if os.path.exists(path + 'token.json'):
creds = Credentials.from_authorized_user_file(path + '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(
path + 'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open(path + 'token.json', 'w') as token:
token.write(creds.to_json())
service = build('drive', 'v3', credentials=creds)
return service
def main():
"""
Downloads a single file, or all files in the specified Google Drive folder.
"""
file_id = sys.argv[1]
service = get_service()
# Query specified file id:
metadata = service.files().get(fileId=file_id).execute()
filename = metadata.get('name')
print('METADATA:', metadata)
print('FILENAME:', filename)
files = [metadata]
if metadata.get('mimeType') == TYPE_FOLDER:
print('FOLDER FOUND!')
results = service.files().list(
q="'%s' in parents" % file_id,
spaces='drive',
fields='nextPageToken, files(id, name, mimeType)').execute()
print('RESULTS:', results)
files = results.get('files')
print('LEN:', len(files))
# DL one or more files
for f in files:
file_id = f.get('id')
filename = f.get('name')
print('Downloading %s' % filename)
request = service.files().get_media(fileId=file_id)
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
print("Download %d%%." % int(status.progress() * 100))
with open(filename, 'wb') as f:
f.write(fh.getbuffer())
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment