Created
July 3, 2018 11:32
-
-
Save ruanbekker/75d98a0d5cab5d6a562c70b4be5ba86d to your computer and use it in GitHub Desktop.
Flask Cache S3 Objects with Redis
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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