Jie Jenn - 03-uploadFiles

3. Google Drive API in Python | Upload Files

Part 1 Docs

01

Go to google drive and go to the folders section

02

Go to the documentation for the create method.
https://developers.google.com/drive/api/reference/rest/v3/files/create We use this to upload files

Part 2 - Script Create new Folder and upload file

02

Create a new folder random files with the script in 02-createFolders

Use the mime type found at
https://developers.google.com/drive/api/guides/mime-types

application/vnd.google-apps.folder
from googleServiceCreate import create_service
CLIENT_SECRET = 'credentials.json'
API_NAME = 'drive'
API_VERSION = 'v3'
SCOPES = ['https://www.googleapis.com/auth/drive']

service = create_service(CLIENT_SECRET,API_NAME,API_VERSION,SCOPES)

national_parks = ['Yellowstone','Rocky Moutains','Yosemite']

file_metadata = {
'name': 'random files',
'mimeType': 'application/vnd.google-apps.folder'
}

service.files().create(body=file_metadata).execute()

02

Click on the folder and get the 'id' of the folder from the URL.

1JWqwvybul0ZlvgcYkP53FxozYJUq9JYp

03

The example files are an excel file and jpeg, use the folder id in the previous step, and get the 'mimeType' for excel files and jpeg from,
https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types

Insert the folder id, names of files and mime types into variables,

from googleServiceCreate import create_service
CLIENT_SECRET = 'credentials.json'
API_NAME = 'drive'
API_VERSION = 'v3'
SCOPES = ['https://www.googleapis.com/auth/drive']

service = create_service(CLIENT_SECRET,API_NAME,API_VERSION,SCOPES)

folder_id = '1JWqwvybul0ZlvgcYkP53FxozYJUq9JYp'
file_names = ['Untitled spreadsheet.xlsx', 'Automn_landscape.jpg']
mime_types = ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','image/jpeg']

04

Create a loop and add the names to a dict's name 'key', and the folder_id to 'parents'

05

Import the class MediaFileUpload from the googleapiclient.http library

Add the path to the files as the first argument to a MediaFileUpload class, format with file_name and mimeType with mime type.

Make sure to use the zip() function in loop

from googleapiclient.http import MediaFileUpload
from googleServiceCreate import create_service
CLIENT_SECRET = 'credentials.json'
API_NAME = 'drive'
API_VERSION = 'v3'
SCOPES = ['https://www.googleapis.com/auth/drive']

service = create_service(CLIENT_SECRET,API_NAME,API_VERSION,SCOPES)

folder_id = '1JWqwvybul0ZlvgcYkP53FxozYJUq9JYp'
file_names = ['Untitled spreadsheet.xlsx', 'Automn_landscape.jpg']
mime_types = ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','image/jpeg']

for file_name,mime_type in zip(file_names,mime_types):
    file_metadata = {
        'name': file_name,
        'parents': [folder_id]
    }
    media = MediaFileUpload('./exFiles/{0}'.format(file_name),mimetype=mime_type)
    service.files().create(
        body=file_metadata,
        media_body=media,
        fields='id'
    ).execute()

06

The files should now appear in the folder

Part 3 - Both Scripts

01

Full Codes

from googleapiclient.http import MediaFileUpload
from googleServiceCreate import create_service
CLIENT_SECRET = 'credentials.json'
API_NAME = 'drive'
API_VERSION = 'v3'
SCOPES = ['https://www.googleapis.com/auth/drive']

service = create_service(CLIENT_SECRET,API_NAME,API_VERSION,SCOPES)

folder_id = '1JWqwvybul0ZlvgcYkP53FxozYJUq9JYp'
file_names = ['Untitled spreadsheet.xlsx', 'Automn_landscape.jpg']
mime_types = ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','image/jpeg']

for file_name,mime_type in zip(file_names,mime_types):
    file_metadata = {
        'name': file_name,
        'parents': [folder_id]
    }
    media = MediaFileUpload('./exFiles/{0}'.format(file_name),mimetype=mime_type)
    service.files().create(
        body=file_metadata,
        media_body=media,
        fields='id'
    ).execute()

                                
                                    
import os.path

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

def create_service(client_secret,api_name,api_version,*scopes):
    CLIENT_SECRET = client_secret
    API_NAME = api_name
    API_VERSION = api_version
    SCOPES = [scope for scope in scopes[0]]

    creds = None
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json',SCOPES)
    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('credentials.json',SCOPES)
            creds = flow.run_local_server(port=0)
        with open ('token.json','w') as token:
            token.write(creds.to_json())
    try:
        service = build(API_NAME,API_VERSION,credentials=creds)
        return service
    except HttpError as e:
        print('error', e)