flask-login can not be used in Blueprint object?

user2331095 picture user2331095 · Apr 29, 2013 · Viewed 7.1k times · Source

I have a question regarding flask-login and blueprint.

admin.py

admin = Blueprint('admin', __name__)
login_manager = LoginManager()
login_manager.setup_app(admin)

@login_manager.user_loader
def load_user(userid):
    return User.query.get(int(userid))

@admin.route('/login', methods=["GET", "POST"])
def login():
    login_form = LoginForm()
    if request.method == 'POST':
    #####user validation####
        login_user(user)
        return redirect('/')
    return render_template('admin/login.html', login_form=login_form)

run.py

app = Flask(__name__)
app.config.from_object(blog_config)
app.register_blueprint(admin)
if __name__ == "__main__":
    app.run(debug=True)

But when I post a form, and use login_user(user), an error occurred.

AttributeError: 'Flask' object has no attribute 'login_manager'

Then I try to use flask-login in run.py, It works fine.

run.py

login_manager = LoginManager()
login_manager.setup_app(admin)

@login_manager.user_loader
def load_user(userid):
    return User.query.get(int(userid))

So, What I want to ask is,flask-login can not be used in Blueprint object? THX!

Answer

Viruzzz-kun picture Viruzzz-kun · Nov 24, 2013

It is also possible to LoginManager.setup_app() on Blueprint's registration:

admin = Blueprint('admin', __name__)
login_manager = LoginManager()

@admin.record_once
def on_load(state):
    login_manager.init_app(state.app)

on_load will be run when the Blueprint is first registered to the app.