Upload file to google drive using Python

Today we will see how to upload files to Google Drive using Python. We will use the Google Drive API to do this. So go to Google Developer Console And create a new project. It may take 5 to 10 seconds, sometimes a few minutes, or you can just click on enable from the google drive quick start documentation

Upload file to google drive using Python

Then you’ll get your client id and client secret. Download Client Configurations JSON file:

client id and client secret

Now you need to install google API client. You can install the library in whichever editor you’re using. For example, we will use PyCharm, so we will install the library in Pycharm Terminal, or you can directly install it in Windows CMD, or Linux Terminal

pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

After installing the library. Make a quickstart.py file, and paste the following code. If it shows an error then copy the URL from the console and manually open it in your browser.

Then click allow, if you use multiple Google Account, then it will ask you to choose the account from which you created the API.

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request


SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']

def main():
    creds = None

    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)    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.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('drive', 'v3', credentials=creds)

    # Call the Drive v3 API
    results = service.files().list(
        pageSize=10, fields="nextPageToken, files(id, name)").execute()
    items = results.get('files', [])

    if not items:
        print('No files found.')
    else:
        print('Files:')
        for item in items:
            print(u'{0} ({1})'.format(item['name'], item['id']))

if __name__ == '__main__':
    main()

After following every step, you’ll get this following screen:

pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

And in the terminal, it will show you all the files, including the trash files.

pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

Now you’re Google Drive API is successfully authenticated.

Uploading Files to Google Drive Using Python

Now there are three types of upload requests:

  • Simple Upload to upload small files(<= 5MB)

  • MultiPart Upload to the quick transfer of a small file (<=5MB) and metadata describing the file, all in a single request.
  • Resumable Upload for large files. These are a good choice for most applications as it works for small files at the cost of one additional HTTP request per upload.

This is an example of how to upload an image to Google Drive

file_metadata = {'name': 'photo.jpg'}
media = MediaFileUpload('files/photo.jpg',
                        mimetype='image/jpeg')
file = drive_service.files().create(body=file_metadata,
                                    media_body=media,
                                    fields='id').execute()
print 'File ID: %s' % file.get('id')

Now you need to send the upload request:

POST https://www.googleapis.com/upload/drive/v3/files?uploadType=media HTTP/1.1
Content-Type: image/jpeg
Content-Length: [NUMBER_OF_BYTES_IN_FILE]
Authorization: Bearer [YOUR_AUTH_TOKEN]

[JPEG_DATA]

If the request succeeds, the server returns the HTTP 200 OK status code along with the file’s metadata:

HTTP/1.1 200
Content-Type: application/json

{
  "name": "Untitled"
}

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *