Skip to content

Instantly share code, notes, and snippets.

Created December 15, 2012 19:52
Show Gist options
  • Save anonymous/4298659 to your computer and use it in GitHub Desktop.
Save anonymous/4298659 to your computer and use it in GitHub Desktop.
500 error Cloudinary upload code.
from flask import abort, request
from flask.views import MethodView
from flask.ext.login import login_required, current_user
from wtforms.fields import FileField
from wtforms import Form
from wtforms.validators import ValidationError
from werkzeug import secure_filename
import logging
import requests
import hashlib
import time
def _signature(keys, api_key):
to_sign = "&".join(sorted([(k+"="+ str(v)) for k, v in keys.items() if v]))
return hashlib.sha1(to_sign + api_key).hexdigest()
class Cloudinary(object):
def __init__(self, app):
self.config = app.config['CLOUDINARY_URL'].split(':')[2].split('@')
self.address = 'http://api.cloudinary.com/v1_1/' + self.config[1] + '/image/upload'
self.api_key = self.config[0]
def upload_image(self, image, user):
cloudinary_logging.info('User %s is uploading profile picture', user.get_id())
keys = {'timestamp': int(time.time()), 'public_id': user.get_id()}
keys['signature'] = _signature(keys, self.api_key)
keys['api_key'] = self.api_key
files = {'file': image.stream}
response = requests.post(self.address, files=files, data=keys)
response.raise_for_status()
return response.json
class FileUploadField(FileField):
'''Specialization copied from Flask-WTF'''
@property
def file(self):
return request.files.get(self.name, None)
class ImageForm(Form):
image = FileUploadField(u'image', validators = [ImageOnly()])
class ImageUploadView(MethodView):
methods = ['POST']
@login_required
def post(self):
upload_logging.info('User %s attempting to upload an image', current_user.get_id())
form = ImageForm(request.form)
try:
if form.validate():
json_result = cloudinary.upload_image(form.image.file, current_user)
return str(json_result) + "OMG PONIES, finish me"
else:
upload_logging.warn('Uploaded image for user %s did not validate.', current_user.get_id())
return abort(401)
except:
upload_logging.exception('Failed to upload profile image for user %s', current_user.get_id())
return abort(401)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment