Search code examples
pythondrive

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


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


Solution

  • Answering my own question

    What I wanted to do was to get a file from a url and upload to drive.

    Used MediaIoBaseUpload class instead of MediaUpload class.

    response = urllib2.urlopen(url)
    fh = BytesIO(response.read())
    media_body = MediaIoBaseUpload(fh, mimetype='image/jpeg',
                  chunksize=1024*1024, resumable=True)
    body = {
            'title': 'pic.jpg'
        }
    drive_service.files().insert(body=body, media_body=media_body).execute()