Skip to content

Instantly share code, notes, and snippets.

@kramer65
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kramer65/b1c93b5cc1ce023d070a to your computer and use it in GitHub Desktop.
Save kramer65/b1c93b5cc1ce023d070a to your computer and use it in GitHub Desktop.
Flask caching endpoint for images stored MongoDB
@app.route('/doc/<docId>')
def getDoc(docId):
userDoc = UserDocument.objects(id=docId).first() # I use MongoEngine to query my mongodb instance
if not userDoc:
return abort(404)
desiredWidthStr = request.args.get('width')
desiredHeightStr = request.args.get('height')
if desiredWidthStr or desiredHeightStr:
try:
desiredWidth = int(desiredWidthStr) if desiredWidthStr else None
desiredHeight = int(desiredHeightStr) if desiredHeightStr else None
except ValueError as e:
print e
return abort(400, "A width and a height can only be integers.")
im = Image.open(userDoc.file_)
originalWidth, originalHeight = im.size
if desiredWidth and not desiredHeight:
desiredHeight = originalHeight / (originalWidth / desiredWidth) # Calculate height from width
elif not desiredWidth and desiredHeight:
desiredWidth = originalWidth / (originalHeight / desiredHeight) # Calculate width from height
else:
return abort(400, "Please provide either a 'width' OR a 'height', but never both.")
if desiredWidth < originalWidth and desiredHeight < originalHeight: # if this is false there's no need to resize and we just serve the original image.
thumbFilename = '/tmp/' + str(userDoc.id) + '_' + str(desiredWidth) + 'x' + str(desiredHeight) + '.' + im.format # Create a filename with the id and the size of the image.
if not os.path.isfile(thumbFilename): # Check if the resized file already exists in the cache
im.thumbnail((desiredWidth, desiredHeight)) # Resize the image
im.save(thumbFilename, im.format) # Save/cache the resized image in /tmp
thumbFile = open(thumbFilename, 'r') # Open the file from cache
return Response(thumbFile, mimetype=mimetypes.guess_type(thumbFilename)[0])
userDoc.file_.seek(0) # ensure we are reading the image from the start
return Response(userDoc.file_.read(), mimetype=userDoc.file_.content_type)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment