Created
October 5, 2016 21:44
-
-
Save bsmithyman/944c84fc38c52985e0e1762c993767d9 to your computer and use it in GitHub Desktop.
Generate a resumable upload URL for Google Cloud Storage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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