Skip to content

Instantly share code, notes, and snippets.

@ruanbekker
Created July 3, 2018 11:32
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 ruanbekker/75d98a0d5cab5d6a562c70b4be5ba86d to your computer and use it in GitHub Desktop.
Save ruanbekker/75d98a0d5cab5d6a562c70b4be5ba86d to your computer and use it in GitHub Desktop.
Flask Cache S3 Objects with Redis
from StringIO import StringIO
from flask import send_file, Flask
import requests
import redis
app = Flask(__name__)
redis_server = redis.StrictRedis(host='localhost', port=6379)
@app.route('/img/<server>/<hash_string>')
def image(server, hash_string):
"""Handle image, use redis to cache image."""
image_url = 'https://objects-us-east-1.dream.io/foobar/assets/images/aws-logo.png?AWSAccessKeyId=somekey&Expires=5436864673&Signature=somesignature'
cached = redis_server.get(image_url)
if cached:
buffer_image = StringIO(cached)
buffer_image.seek(0)
else:
r = requests.get(image_url)
buffer_image = StringIO(r.content)
buffer_image.seek(0)
redis_server.setex(image_url, (60*60*24*7),
buffer_image.getvalue())
return send_file(buffer_image, mimetype='image/jpeg')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80)
# thanks:
# https://stackoverflow.com/questions/30240370/python-flask-image-proxy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment