Skip to content

Instantly share code, notes, and snippets.

@gsidhu
Created February 13, 2022 21:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gsidhu/7dc127bd1a70e06e7c751ccd23798ecb to your computer and use it in GitHub Desktop.
Save gsidhu/7dc127bd1a70e06e7c751ccd23798ecb to your computer and use it in GitHub Desktop.
Boiler plate code for uploading files to Google Drive
# 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