Updating Thumbnail of File on Google Drive using Python

Gists

This sample script is for updating thumbnail of file on Google Drive using Python.

This sample supposes that quickstart is used and default quickstart works fine. In order to use this sample, please carry out as follows.

  • Replace main() of the default quickstart to this sample.

Script :

import base64 # This is used for this sample.

def main():
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('drive', 'v3', http=http)

    with open("./sample.png", "rb") as f:
        res = service.files().update(
            fileId="### file ID ###",
            body={
                "contentHints": {
                    "thumbnail": {
                        "image": base64.urlsafe_b64encode(f.read()).decode('utf8'),
                        "mimeType": "image/png",
                    }
                }
            },
        ).execute()
        print(res)

contentHints.thumbnail.image is URL-safe Base64-encoded image. So an image data that you want to use as new thumbnail has to be converted to URL-safe Base64-encoded data. For this, it uses base64.urlsafe_b64encode() at Python.

There are some limitations for updating thumbnail. Please confirm the detail information at https://developers.google.com/drive/v3/web/file#uploading_thumbnails.

Result :

Note :

I used zip file as a sample. Zip file doesn’t have the thumbnail on Google Drive. When it confirms using drive.files.get, hasThumbnail is false. So this can be used. Although I used this script to Google Docs and images, the updated image was not reflected to them. This may touch to the limitations. When the thumbnail is given to the zip file, hasThumbnail becomes true. In my environment, at the first update, the update had sometimes been failed. But at that time, the second update had worked fine. I don’t know about the reason. I’m sorry.

 Share!