Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Last active Jul 28, 2021
Embed
What would you like to do?
Simple Script of Resumable Upload with Google Drive API for Python

Simple Script of Resumable Upload with Google Drive API for Python

This is a simple sample script for achieving the resumable upload to Google Drive using Python. In order to achieve the resumable upload, at first, it is required to retrieve the location, which is the endpoint of upload. The location is included in the response headers. After the location was retrieved, the file can be uploaded to the location URL.

In this sample, a PNG file is uploaded with the resumable upload using a single chunk.

Sample script

Before you use this, please set the variables.

import json
import os
import requests

access_token = '###'  ## Please set the access token.
filename = './sample.png'

filesize = os.path.getsize(filename)

# 1. Retrieve session for resumable upload.
headers = {"Authorization": "Bearer "+access_token, "Content-Type": "application/json"}
params = {
    "name": "sample.png",
    "mimeType": "image/png"
}
r = requests.post(
    "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",
    headers=headers,
    data=json.dumps(params)
)
location = r.headers['Location']

# 2. Upload the file.
headers = {"Content-Range": "bytes 0-" + str(filesize - 1) + "/" + str(filesize)}
r = requests.put(
    location,
    headers=headers,
    data=open(filename, 'rb')
)
print(r.text)

Reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment