Created
March 31, 2016 06:47
-
-
Save davidwtbuxton/7f81b427f953a5f9c0db31ad8bba6439 to your computer and use it in GitHub Desktop.
Serving Google Cloud Storage files from App Engine without having to read them
This file contains hidden or 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 mimetypes | |
from django.http import HttpResponse | |
from google.appengine.api import app_identity | |
from google.appengine.ext import blobstore | |
def serve_cloud_storage_file(request, object_name): | |
"""Serve a file from cloud storage by setting a header on the response. | |
The blobstore will serve it for you. | |
""" | |
# The default bucket, or use a custom bucket. | |
bucket = app_identity.get_default_gcs_bucket_name() | |
# object_name is a path like '/foo/bar/myfile.json' inside the bucket. Must | |
# start with a slash. | |
key = '/{bucket}{object_name}'.format(bucket=bucket, object_name=object_name) | |
blob_key = blobstore.create_gs_key('/gs' + key) | |
content_type, encoding = mimetypes.guess_type(object_name) | |
if not content_type: | |
content_type='application/octet-stream' | |
# Setting the special header on the response means App Engine will return | |
# the data from cloud storage for you, without your app having to read it | |
# directly. | |
response = HttpResponse(content_type=content_type) | |
response[blobstore.BLOB_KEY_HEADER] = str(blob_key) | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment