I want to have a dynamic navigation menu that shows \"Login\" if the user is not currently logged on, and \"Logout\" if the user is logged in.
I\'m using code simila
Flask-Login will make your life easier. It provided a current_user
to point to the current user, and the user object has an is_authenticated
property:
from flask_login import current_user
...
@nav.navigation()
def top_nav():
...
if current_user.is_authenticated:
items.append(View("Logout", ".logout"))
else:
items.append(View("Login", ".login"))
The code to initialize Flask-Login will like this:
from flask import Flask
from flask_login import LoginManager, UserMixin
app = Flask(__name__)
login_manager = LoginManager(app)
# The user model
class User(db.Model, UserMixin):
...
@login_manager.user_loader
def load_user(user_id):
return User.get(user_id)
Check the documentation for more detail.