Skip to content

Instantly share code, notes, and snippets.

@amgaweda
Created April 5, 2014 01:39
Show Gist options
  • Save amgaweda/9986374 to your computer and use it in GitHub Desktop.
Save amgaweda/9986374 to your computer and use it in GitHub Desktop.
Adding S3 to your Flask application
# Place inside views.py
from flask import render_template, flash, redirect, session, url_for, request, g, abort
@app.route('/upload', methods = ['GET', 'POST'])
def upload():
if request.method == 'POST' and 'file' in request.files:
f = request.files['file']
if f and allowed_file(f.filename):
filename = f.filename
try:
img = push_to_s3(photo=f, filename=filename)
if img:
g.filename = get_from_s3(key=img)
else:
raise Exception("Failed to Upload Image to S3 - %s" % str(img))
except Exception, e:
print "ERROR - views/upload - %s" % str(e)
return render_template('new-image.html', filename=g.filename, hide_button=True)
elif request.method == "GET":
return render_template('upload.html')
else:
pass
return redirect('/')
# Place wherever, I chose models.py
from boto.s3.connection import S3Connection
from boto.s3.key import Key
def push_to_s3(**kwargs):
try:
conn = S3Connection(app.config["S3_KEY"], app.config["S3_SECRET"])
buckets = [bucket.name for bucket in conn.get_all_buckets()]
# Check if bucket currently exists
# If not, create bucket
if app.config["S3_BUCKET"] in buckets:
bucket = conn.get_bucket(app.config["S3_BUCKET"])
else:
bucket = conn.create_bucket(app.config["S3_BUCKET"])
k = Key(bucket)
k.key = app.config["S3_UPLOAD_DIR"] + kwargs.get("filename") # for example, 'images/bob/resized_image1.png'
k.set_contents_from_file(kwargs.get("photo"))
k.make_public()
return k
except Exception, e:
print "ERROR - models/push_to_s3 - %s" % str(e)
abort(500)
def get_from_s3(**kwargs):
try:
conn = S3Connection(app.config["S3_KEY"], app.config["S3_SECRET"])
bucket = conn.get_bucket(app.config["S3_BUCKET"])
if kwargs.get("key"):
filename = kwargs.get("key").name
elif kwargs.get("filename"):
filename = kwargs.get("filename")
else:
raise Exception('Invalid kwarg')
key = bucket.get_key(filename)
# Generate a URL for key that exists for 1 hour
# http://objects.dreamhost.com/my-bucket-name/secret_plans.txt?Signature=XXXXXXXXXXXXXXXXXXXXXXXXXXX&Expires=1316027075&AWSAccessKeyId=XXXXXXXXXXXXXXXXXXX
#image_url = key.generate_url(3600, query_auth=True, force_http=True) #URL is available for 1 hour
image_url = key.generate_url(expires_in=None, query_auth=False) #URL is available forever
return image_url
except Exception, e:
print "ERROR - models/get_from_s3 - %s" % str(e)
abort(500)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment