Skip to content

Instantly share code, notes, and snippets.

@georgewhewell
Created October 3, 2013 13:04
Show Gist options
  • Save georgewhewell/6809486 to your computer and use it in GitHub Desktop.
Save georgewhewell/6809486 to your computer and use it in GitHub Desktop.
cloud storages
from google.appengine.ext import blobstore
from google.appengine.api import images
from django.conf import settings
from django.core.files.storage import Storage
import mimetypes
import cloudstorage
import os
class CloudStorage(Storage):
def __init__(self, **kwargs):
self.BUCKET_NAME = settings.GS_BUCKET_NAME
def delete(self, filename):
assert(filename)
try:
cloudstorage.delete(os.path.join(self.BUCKET_NAME, filename))
except cloudstorage.NotFoundError:
pass
def exists(self, filename):
try:
cloudstorage.stat(os.path.join(self.BUCKET_NAME, filename))
return True
except cloudstorage.NotFoundError:
return False
def _open(self, filename, mode):
return cloudstorage.open(os.path.join(self.BUCKET_NAME, filename), 'r')
def _save(self, filename, content):
with cloudstorage.open(os.path.join(self.BUCKET_NAME, filename),
'w',
content_type=mimetypes.guess_type(filename)[0],
options={'x-goog-acl': 'public-read'}) as handle:
handle.write(content.read())
return os.path.join(self.BUCKET_NAME, filename)
def url(self, filename):
key = blobstore.create_gs_key('/gs' + filename)
return images.get_serving_url(key)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment