pythonflaskflask-uploads

Flask-Uploads : how to use with application factory


I am trying to implement Flask-Uploads in my project. However, I am having trouble because I am using an application factory function and cannot access the UploadSets from other files in the app!

FILE: app/__init__.py

from flask_uploads import UploadSet, configure_uploads, IMAGES

def create_app(object_name):
    ...
    images = UploadSet('images', IMAGES)
    configure_uploads(app, images)

FILE: app/controllers/editions.py

from flask_uploads import UploadNotAllowed

# this is one of my route files, registered in a blueprint
editions = Blueprint('editions', __name__)

...
    # inside one of the routes
    poster = request.files.get('poster')
    try:
        filename = images.save(poster)
    except UploadNotAllowed:
        flash('The upload was not allowed.', category='warning')
    else:
        # add to db...

Of course this won't work because images is not defined. But how to I import it from the app?

I tried:

import app
app.images.save(...)

from flask import current_app
current_app.images.save(...)

from app import images

None works. Any ideas???

PS: everything else in my app is working fine except this.


Solution

  • I figured it out right after I posted here. It is simple, but can't find it explained nowhere:

    On your controller/view file, where the routes are:

    from flask_upload import UploadSet, IMAGES
    
    my_upload_set = UploadSet('my_upload_set', IMAGES)
    
    # (...) routes where you can use:
        image = request.files.get('image') # or whatever your form field name is
        try:
            filename = my_upload_set.save(image)
        except UploadNotAllowed:
            flash('The upload was not allowed.', category='warning')
        else:
            #  add to db
    

    On your app/__init__.py file:

    from app.controllers.my_view import my_upload_set
    from flask_uploads import configure_uploads
    
    def create_app(object):
        (...)
        configure_uploads(app, my_upload_set)
    

    This should work like a charm! Any questions let me know...