Skip to content

Instantly share code, notes, and snippets.

@nelldnine
Created August 11, 2019 11:19
Show Gist options
  • Save nelldnine/e3fdcc363f575ef515275f55781b8bc6 to your computer and use it in GitHub Desktop.
Save nelldnine/e3fdcc363f575ef515275f55781b8bc6 to your computer and use it in GitHub Desktop.
import logging
import random, string
import cloudstorage as gcs
from google.appengine.ext import blobstore
from google.appengine.api import images
from settings import BUCKET_NAME
def random_string(n=8):
return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(n))
def upload(f):
if not f:
return None
filename = '/{}/{}/{}'.format(BUCKET_NAME, random_string(), f.filename)
gcs_options = {'x-goog-acl': 'public-read'}
gcs_file = gcs.open(filename, 'w', options=gcs_options)
gcs_file.write(f.read())
gcs_file.close()
url = 'https://storage.googleapis.com' + filename
try:
blob_key = blobstore.create_gs_key("/gs" + filename)
url = images.get_serving_url(blob_key)
except Exception as e:
logging.debug('File is not an image')
logging.exception(e)
return url
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment