Skip to content

Commit

Permalink
enhance code
Browse files Browse the repository at this point in the history
  • Loading branch information
albertcht committed Jun 29, 2019
1 parent 4dd85f1 commit c55b8e7
Showing 1 changed file with 35 additions and 3 deletions.
38 changes: 35 additions & 3 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,50 @@

from flask import Flask
from flask import request
from flask import make_response

from google.appengine.ext import blobstore
from google.appengine.api import images

JSON_MIME_TYPE = 'application/json'

app = Flask(__name__)

@app.route('/image-url', methods=['GET'])
def image_url():
bucket = request.args.get('bucket')
image = request.args.get('image')

filename = (bucket + "/" + image)
servingImage = images.get_serving_url(None, filename='/gs/' + filename)
if not all([bucket, image]):
error = json.dumps({'error': 'Missing `bucket` or `image` parameter.'})
return json_response(error, 422)

filepath = (bucket + "/" + image)

try:
servingImage = images.get_serving_url(None, filename='/gs/' + filepath)
except images.AccessDeniedError:
error = json.dumps({'error': 'Ensure the GAE service account has access to the object in Google Cloud Storage.'})
return json_response(error, 401)
except images.ObjectNotFoundError:
error = json.dumps({'error': 'The object was not found.'})
return json_response(error, 404)
except images.TransformationError:
# A TransformationError may happen in several scenarios - if
# the file is simply too large for the images service to
# handle, if the image service doesn't have access to the file,
# or if the file was already uploaded to the image service by
# another App Engine app. For the latter case, we can try to
# work around that by copying the file and re-uploading it to
# the image service.
error = json.dumps({'error': 'There was a problem transforming the image. Ensure the GAE service account has access to the object in Google Cloud Storage.'})
return json_response(error, 400)

return json_response(json.dumps({'image_url': servingImage}))

def json_response(data='', status=200, headers=None):
headers = headers or {}
if 'Content-Type' not in headers:
headers['Content-Type'] = JSON_MIME_TYPE

return(servingImage)
return make_response(data, status, headers)

0 comments on commit c55b8e7

Please sign in to comment.