Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generate a resumable upload URL for Google Cloud Storage
import json
import os
from oauth2client.service_account import ServiceAccountCredentials
import httplib2
GCP_CREDENTIALS_FILE = os.getenv('GCP_CREDENTIALS_FILE', 'client-secret.json')
GCS_UPLOAD_URL_PATTERN = 'https://www.googleapis.com/upload/storage'+ \
'/v1/b/{bucket}/o?uploadType=resumable'
def get_upload_url(bucket, filename, content_length, content_type='application/octet-stream'):
"""Generate a resumable upload URL for Google Cloud Storage"""
credentials = ServiceAccountCredentials.from_json_keyfile_name(
'client-secret.json',
('https://www.googleapis.com/auth/devstorage.read_write',),
)
http = httplib2.Http()
credentials.authorize(http)
url = GCS_UPLOAD_URL_PATTERN.format(bucket=bucket)
body = json.dumps({
'name': filename,
}).encode('UTF-8')
headers = {
'X-Upload-Content-Type': content_type,
'X-Upload-Content-Length': content_length,
'Content-Type': 'application/json; charset=UTF-8',
'Content-Length': len(body),
}
resp_headers, resp_body = http.request(url, method='POST', headers=headers, body=body)
return resp_headers['location']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment