Skip to content

Instantly share code, notes, and snippets.

@lost-theory
Forked from anonymous/Flask Image Upload
Created December 15, 2012 22:06

Revisions

  1. lost-theory revised this gist Dec 15, 2012. 1 changed file with 1 addition and 3 deletions.
    4 changes: 1 addition & 3 deletions cloudinary.py
    Original file line number Diff line number Diff line change
    @@ -1,6 +1,4 @@
    from flask import abort, request, Flask

    import hashlib
    from flask import request, Flask

    from cloudinary import uploader #pip install git+https://github.com/cloudinary/pycloudinary/

  2. lost-theory renamed this gist Dec 15, 2012. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  3. lost-theory revised this gist Dec 15, 2012. 1 changed file with 39 additions and 61 deletions.
    100 changes: 39 additions & 61 deletions Flask Image Upload
    Original file line number Diff line number Diff line change
    @@ -1,67 +1,45 @@
    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
    from flask import abort, request, Flask

    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()
    from cloudinary import uploader #pip install git+https://github.com/cloudinary/pycloudinary/

    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)
    config = app.config['CLOUDINARY_URL'].split('://')[1]
    config = config.replace("@", ":")
    self.api_key, self.api_secret, self.name = config.split(":")

    def upload_image(self, image):
    keys = {'public_id': 1001}
    res = uploader.call_api(
    "upload",
    uploader.build_upload_params(**keys),
    api_key=self.api_key,
    api_secret=self.api_secret,
    cloud_name=self.name,
    file=image.stream,
    )
    return res

    ###############################################################################

    app = Flask(__name__)
    app.config['DEBUG'] = True
    app.config['CLOUDINARY_URL'] = "cloudinary://347452728366389:30n0mSGxiSYZw7q3dZ_3hjorJ5M@ummwut" #XXX: feel free to use this URL, upload whatever you like ;)
    cloudinary = Cloudinary(app)

    ###############################################################################

    @app.route("/", methods=['GET', 'POST'])
    def test():
    if request.method == "POST":
    json_result = cloudinary.upload_image(request.files['image'])
    return str(json_result)

    return '<html><body><form action="" method=post enctype=multipart/form-data><input type=file name=image /><input type=submit /></form></body></html>'

    ###############################################################################

    if __name__ == "__main__":
    app.run(use_debugger=True, use_reloader=True)
  4. @invalid-email-address Anonymous created this gist Dec 15, 2012.
    67 changes: 67 additions & 0 deletions Flask Image Upload
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,67 @@
    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)