Flask-login cannot be used in blueprint object?

I have a question related to flash login and plan.

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 submit the form and use login_user (user), an error has 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, the login checkbox cannot be used in the Blueprint object? thanks!

+8
flask blueprint flask-login
source share
2 answers

That's why he called setup_app

Just move the initialization to your run.py and pass the application as parameter And the login itself may remain inside the admin plan

+3
source share

You can also log in to LogManager.setup_app () when registering Blueprint:

 admin = Blueprint('admin', __name__) login_manager = LoginManager() @admin.record_once def on_load(state): login_manager.init_app(state.app) 

on_load will be launched when Blueprint is first registered in the application.

+26
source share

All Articles