Skip to content

Instantly share code, notes, and snippets.

@bsmithyman
Created October 5, 2016 21:44
Show Gist options
  • Save bsmithyman/944c84fc38c52985e0e1762c993767d9 to your computer and use it in GitHub Desktop.
Save bsmithyman/944c84fc38c52985e0e1762c993767d9 to your computer and use it in GitHub Desktop.
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