1
votes

I have a blueprint where I have an upload form. I am attempting to save the files, but I cannot figure out how to reference the correct directory. When I use app.instance_path, it gives the error message:

NameError: name 'app' is not defined

How can I declare the correct folder location to store the file from within a Flask Blueprint?

Here is my init.py file:

# External libraries
from flask import Flask


# Import the resources
from . import students

def create_app(configfile=None):
    app = Flask(__name__)

    app.register_blueprint(students.bp)

    return app

Here is my students.py blueprint file:

import os

from flask import (
    Blueprint, flash, g, redirect, render_template, request, session, url_for
)

from werkzeug.utils import secure_filename

from SIMPLE.forms import ImportStudentsForm

bp = Blueprint('students', __name__, url_prefix='/students')

@bp.route('/import', methods=('GET', 'POST'))
def import_students():
    # Load the register form
    form = ImportStudentsForm(request.form)

    if form.validate_on_submit():

        f = request.files['file']
        filename = secure_filename(f.filename)
        f.save(os.path.join(
            app.instance_path, 'uploads',  filename
        ))

        # Flash success
        flash('Sucessfully registered.', 'success')

    return render_template('students/batch_import_students.html', form=form)

Any guidance would be much appreciated. Thanks.

2

2 Answers

0
votes

You get the error because you have not imported app in students.py. You could import it (and run the risk of circular imports) but a more elegant way is to get the app instance through flask.current_app.

Add from flask import current_app to the top of students.py and replace app.instance_path with current_app.instance_path.

0
votes

Try this ::

from flask import current_app

AND

f.save(os.path.join(current_app.instance_path, 'uploads',  filename))

You are using application factory. So there is no 'app' object here. Whatever app flask is currently using can be fetched with current_app and then you can work with it.

Also, if the instance_path doesn't work, try current_app.root_path