Skip to content

Commit

Permalink
super code cleanup, got rid of most horrible catch all exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
jinpark committed Aug 18, 2015
1 parent 516fdb8 commit ff3af3e
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 47 deletions.
76 changes: 33 additions & 43 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from flask import Flask, send_file, request, abort, jsonify, send_from_directory, make_response, redirect, current_app
from StringIO import StringIO
from wand.image import Image, GRAVITY_TYPES
from wand.exceptions import MissingDelegateError
from urlparse import urlparse
from tempfile import NamedTemporaryFile
from shutil import copyfileobj
Expand All @@ -18,6 +19,11 @@
app.logger.setLevel(logging.INFO)
app.logger.info('jinageresizer startup')

@app.errorhandler(400)
def custom400(error):
response = jsonify({'message': error.description})
return response, 400

def nocache(view):
"""
no cache decorator. used for health check
Expand Down Expand Up @@ -53,35 +59,28 @@ def convert(url):
filename, file_ext = os.path.splitext(os.path.basename(urlparse(url).path))
if 'image' not in r.headers['content-type']:
app.logger.error(url + " is not an image.")
abort(400)
abort(400, url + " is not an image.")
except:
app.logger.exception("Error while getting url: " + url)
abort(400)
abort(400, "Error while getting url: " + url)
try:
with Image(file=StringIO(r.content)) as img:
if query_string.get('type') in ['jpeg', 'jpg', 'png', 'pjeg']:
img.format = query_string.get('type')

img = resize(img, query_string.get('rwidth'), query_string.get('rheight'))

if 'cwidth' and 'cheight' in query_string.keys():
if 'gravity' in query_string.keys() and query_string['gravity'].lower() in GRAVITY_TYPES:
img.crop(width=int(query_string['cwidth']), height=int(query_string['cheight']), gravity=query_string['gravity'])
else:
img.crop(width=int(query_string['cwidth']), height=int(query_string['cheight']))
img = crop(img, query_string.get('cwidth'), query_string.get('cheight'), query_string.get('gravity'))

temp_file = NamedTemporaryFile(mode='w+b',suffix=img.format)
try:
img.save(file=temp_file)
temp_file.seek(0,0)
response = send_file(temp_file, mimetype=img.mimetype)
return response
finally:
# temp_file.close()
print 'cat'
except:
app.logger.exception("Error while getting image for wand")
abort(500)
img.save(file=temp_file)
temp_file.seek(0,0)
response = send_file(temp_file, mimetype=img.mimetype)
return response
except MissingDelegateError:
abort(400, 'Image is unusable')




def resize(img, width=None, height=None):
Expand All @@ -90,15 +89,15 @@ def resize(img, width=None, height=None):
if width:
try:
width = int(width)
except:
except ValueError:
app.logger.exception("rwidth is invalid: " + width)
return bad_request(bad_var_name='width')
abort(400, "rwidth is invalid: " + width)
if height:
try:
height = int(height)
except:
except ValueError:
app.logger.exception("rheight is invalid: " + height)
return bad_request(bad_var_name='rheight')
abort(400, "rheight is invalid: " + height)
if width and height:
img.resize(width, height)
if width and not height:
Expand All @@ -108,33 +107,24 @@ def resize(img, width=None, height=None):

return img


# on hold until I can figure out gravity
# def crop(img, width, height):
# """
# Crops image based on left, top, bottom, right pixel sizes.
# Default gravity is center. Options are center, north, north_east, ...
# View http://docs.wand-py.org/en/latest/wand/image.html#wand.image.BaseImage.crop
# for more details
# """
# img.transform("{}x{}".format(width,height))
def crop(img, width=None, height=None, gravity='north_west'):
if not width and not height:
return img
if width and height:
try:
img.crop(width=int(width), height=int(height), gravity=gravity)
except ValueError:
app.logger.exception("cheight: {0} or cwidth: {1} is invalid.".format(height, width))
abort(400, "cheight: {0} or cwidth: {1} is invalid.".format(height, width))
if (width and not height) or (not width and height): # xor!
abort(400, "cheight or cwidth is missing. Both are required for cropping.")
return img


@app.route('/health/')
@nocache
def health_check():
return jsonify({'health': 'ok', 'commit_hash': os.environ.get('COMMIT_HASH')})


@app.errorhandler(400)
def bad_request(bad_var_name="", error=None):
message = {
'status': 400,
'message': 'Bad request: {0} is not valid'.format(bad_var_name),
}
resp = jsonify(message)
resp.status_code = 400
return resp

if __name__ == '__main__':
app.run()
4 changes: 0 additions & 4 deletions tests/test_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,6 @@ def test_not_an_image(self):
rv = self.app.get('/http://notanimage.com/g/50/200/?rwidth=100')
self.assertEqual(rv.status, "400 BAD REQUEST")

def test_bad_image(self):
rv = self.app.get('/http://badimage.com/g/50/200/?rwidth=100')
self.assertEqual(rv.status, "500 INTERNAL SERVER ERROR")

def test_bad_width(self):
rv = self.app.get('/http://placekitten.com/g/50/200/?rwidth=cat')
self.assertEqual(rv.status, "400 BAD REQUEST")
Expand Down

0 comments on commit ff3af3e

Please sign in to comment.