Forum in maintenance, we will back soon 🙂
Python Flask, Flask-Login, decorator login_required, and a new script for a logout_required decorator
One of the coding items you'll need to code is authentication and controlling access to your route endpoints. For instance if you have a route to the endpoint /profile you don't want unauthenticated users accessing that endpoint. So to control that you import the login_required decorator function from the flask_login package to use like so.
from flask import Flask, render_template from flask_login import login_required app = Flask(__name__) @app.route('/profile') @login_required def profile(): return render_template('profile.html')
So now if your /profile endpoint is accessed anonymously the user is redirected to the login page.
Unfortunately flask_login doesn't provide the opposite decorator to control the /login and /register endpoints. I've created the following with the help of ChatGPT.
import flask as fl import flask_login as flLogin import functools as ft def logout_required(f): @ft.wraps(f) def decorated_function(*args, **kwargs): if flLogin.current_user.is_authenticated: # Redirect to the home page or another appropriate page return fl.redirect(fl.url_for('index')) return f(*args, **kwargs) return decorated_function
and to use it
@app.route('/login') @logout_required def login(): return render_template('index.html') @app.route('/register') @logout_required def register(): return render_template('register.html')
NOTE: The examples are incomplete and are given only as a sample for use of the decorators.
POLL: Is this something you think you could use?
Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack
Thanks for sharing, I was just creating some custom decorators today for my API project, but am using FastAPI and not Flask.
@admin looking forward to seeing your API project.
Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack