Google Drive Python API; upload a media object which is NOT a file

Viewed 2545

I'm able to upload a file to Google Drive using the python API as provided in this example by using the MediaUpload class.

But I need to upload a file which is dynamically created and I don't want to save it and open again.

There is no such implementation already existing. This guide says I need to create a subclass of MediaUpload and must fully implement the MediaUpload interface.

I went through the code and it's really confusing. If anyone had already implemented it or could help me with this, please share the code.

Thank you

2 Answers

For those looking for a way to upload a file not through a url, but using formdata or any media object/string which is in bytes, here is the sample code.

The following case is, I am sending a docx file from my frontend application using formdata & receiving it on the backend. Now this file, I want to upload to google drive.

The tech stack I'm using is Angular 8 for frontend & Tornado Python for backend.

Backend Python Code:

import io
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseUpload
from gdrive_config import credentials # Import your credentials object created using a service account 
# Refer this link for more info - https://github.com/googleapis/google-api-python-client/blob/master/docs/oauth-server.md

drive_service = build("drive", "v3", credentials=credentials, cache_discovery=False)

file = self.request.files
file_info = file["my_docx_file"][0] # Here "my_docx_file" is the key name you have set in form data

def upload_file(file_info):
    file_name = file_info["filename"]

    file_metadata = {
        "name": file_name,
        "mimeType": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", # Mimetype for docx
    }

    media = MediaIoBaseUpload(io.BytesIO(file_info["body"]), # **Pass your bytes object/string here
                              mimetype="application/vnd.google-apps.document", # I'm converting docx to native google docs
                              resumable=True)

    file = drive_service.files().create(body=file_metadata,
                                        media_body=media,
                                        fields="id, name").execute()

    print("Uploaded File '{}' with ID: {}".format(file.get("name"), file.get("id")))

Reference links:

Oauth flow for service accounts - https://github.com/googleapis/google-api-python-client/blob/master/docs/oauth-server.md

Google drive python client docs - https://developers.google.com/resources/api-libraries/documentation/drive/v3/python/latest/drive_v3.files.html

Google drive upload file guide - https://developers.google.com/drive/api/v3/manage-uploads

Related