Flask Login @login_required Not Working
Solution 1:
My problem was that the @flask_login.login_required
decorator was above the @app.route('<path>')
decorator, so I just replaced them and it worked
From this:
@flask_login.login_required
@app.route('/')
def index():
return render_template("index.html")
to this:
@app.route('/')
@flask_login.login_required
def index():
return render_template("index.html")
Solution 2:
Just spent the last 2 hours trying to fix this and realized that it was because off the configuration that the login_required was not working
On my local development environment, I had set
app.config['TESTING'] = True
From the flask-login documentation
If the application configuration variable LOGIN_DISABLED or TESTING is set to True, the login_required decorator will be ignored
set it back to this and got it working
app.config['TESTING'] = False
Solution 3:
Is the username field a primary key? Assuming that you are using sql alchemy, the get() method aways look for the primary key and does not accept expressions, see http://docs.sqlalchemy.org/en/rel_1_0/orm/query.html#sqlalchemy.orm.query.Query.get
Try again with user = models.User.filter_by(username=response['username'])
...
Solution 4:
Just check if the user is logged in. There might be a cookie that the user is logged in.
I tested if it was all working by just setting the user as logged in that added a
cookie.
I just added this and got it working
@app.before_first_request
def init_app():
logout_user()
and it worked perfectly fine
Solution 5:
If you are using flask-login, you need to make sure that you have a function that can be used by the library to load a user based on the ID. Something of this type:
@login_manager.user_loader
def load_user(user_id):
return models.User.get(models.User.id == user_id)
Please read this section of the docs for how to do it.
Post a Comment for "Flask Login @login_required Not Working"