Skip to content

Instantly share code, notes, and snippets.

@TheGarkine
Last active April 11, 2022 16:56
Show Gist options
  • Select an option

  • Save TheGarkine/6dcb1b25b96870dc7bf0eb10f35f151e to your computer and use it in GitHub Desktop.

Select an option

Save TheGarkine/6dcb1b25b96870dc7bf0eb10f35f151e to your computer and use it in GitHub Desktop.
A minimal working example that uploads a given file to Google Drive
import magic
from googleapiclient.discovery import build, Resource
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient.http import MediaFileUpload
FOLDER_ID = "<your google drive folder id>"
FILE_NAME = "CV.pdf" # How you want your file to be named in Google Drive
FILE_LOCATION = "./CV.pdf"
# Use your JSON token to create the Google Drive Service with it
credentials = ServiceAccountCredentials.from_json_keyfile_name("token.json")
service = build('drive', 'v3', credentials=credentials)
# Find all files that exist in the folder
execution = service.files().list(q=f"'{FOLDER_ID}' in parents", fields="files(id, name)").execute()
files = execution.get('files', [])
# Collect all the file information needed
mime = magic.Magic(mime=True).from_file(FILE_LOCATION)
file_metadata = {'name': FILE_NAME, 'parents' : [FOLDER_ID]}
media = MediaFileUpload(FILE_LOCATION, mimetype=mime)
# Get the files that are named the same way as the suggested FILE_NAME
exist = [f for f in files if f["name"] == FILE_NAME]
if exist:
# Overwrite it if it exists
file_id = exist[0]["id"]
file = service.files().update(fileId=file_id, media_body=media, fields='id').execute()
else:
# Create a new one if it doesn't exist
file = service.files().create(body=file_metadata, media_body=media,fields='id').execute()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment