Created
February 13, 2022 21:32
-
-
Save gsidhu/7dc127bd1a70e06e7c751ccd23798ecb to your computer and use it in GitHub Desktop.
Boiler plate code for uploading files to 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
# install dependencies listed here: https://developers.google.com/drive/api/v3/quickstart/python#step_1_install_the_google_client_library | |
from googleapiclient.discovery import build | |
from google.oauth2.service_account import Credentials | |
from googleapiclient.http import MediaFileUpload | |
# Location of the access token | |
# Get this from https://console.cloud.google.com/apis/api/drive.googleapis.com/ | |
ACCESS_TOKEN_LOCATION = "client-secret.json" | |
# Check the scope for your needs at https://developers.google.com/identity/protocols/oauth2/scopes#drive | |
SCOPES = ["https://www.googleapis.com/auth/drive"] # This scope is FULL access | |
# authorisation + initialisation | |
credentials = Credentials.from_service_account_file(ACCESS_TOKEN_LOCATION, scopes=SCOPES) | |
service = build('drive', 'v3', credentials=credentials) | |
file_metadata = { | |
'name': 'sample.png', # name of the file on Drive | |
'parents':['thY2Hl25HthY2Hl25H'] # the folder in which to upload; if not specified file is uploaded to root folder on Drive | |
} | |
# location + type of the file to be uploaded | |
media = MediaFileUpload('./greatphoto.png', mimetype='image/png') | |
# UPLOAD! | |
file = service.files().create(body=file_metadata, media_body=media, fields='id').execute() | |
# if an ID is returned, the upload was successful | |
print('File ID: %s' % file.get('id')) | |
## NOTE | |
## 1. Set fields to '*' in line 25 and then print(file) to see all the details about the file you've just uploaded | |
## 2. If you're trying to upload a file to a folder that is not in your Drive, make sure you share that folder with the email address listed in your client-secret.json first | |
## 3. You'll have to set up a project and enable the Drive API as a prerequisite. See: https://developers.google.com/drive/api/v3/quickstart/python#prerequisites |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment