Last active
August 15, 2021 10:38
-
-
Save mcbhenwood/e9cabf690f5f23d38e936f5bb385f33a to your computer and use it in GitHub Desktop.
Example code for uploading a file to Google Drive via Google Drive API
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
#!/usr/bin/env python3 | |
# | |
# POC to call Google Drive API as a headless process | |
# -------------------------------------------------- | |
from googleapiclient.discovery import build | |
from googleapiclient.http import MediaFileUpload | |
from google.oauth2 import service_account | |
SCOPES = ['https://www.googleapis.com/auth/drive'] | |
SERVICE_ACCOUNT_FILE = 'keyfile.json' # Downloaded from GCP Service Account detail page | |
SHARED_FOLDER_NAME = 'Top-Level Folder Name - Unique - Supplied by business' | |
def get_credentials(): | |
return service_account.Credentials.from_service_account_file( | |
SERVICE_ACCOUNT_FILE, scopes=SCOPES) | |
def get_drive_service(scoped_creds): | |
return build('drive', 'v3', credentials=scoped_creds) | |
def get_shared_folder_id(): | |
file_list = drive_service.files().list(q=f"name = '{SHARED_FOLDER_NAME}'", | |
fields='files(name, id)').execute() | |
files = file_list['files'] | |
assert len(files) == 1 | |
return files[0]['id'] | |
def do_upload(target_folder_id, local_file_name): | |
# Here you will want to determine the actual folder location & filename for the upload | |
file_metadata = { | |
'name': local_file_name, | |
'parents': [target_folder_id], | |
} | |
media = MediaFileUpload(local_file_name, mimetype='image/jpeg') | |
file = drive_service.files().create(body=file_metadata, | |
media_body=media, | |
fields='id').execute() | |
print('File ID: %s' % file.get('id')) | |
if __name__ == '__main__': | |
scoped_creds = get_credentials() | |
drive_service = get_drive_service(scoped_creds) | |
shared_folder_id = get_shared_folder_id() | |
do_upload(shared_folder_id, 'charliecat.jpg') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment