Flask how to redirect @login_required to specific route?

Viewed 329

I am building a small web application as a project and i am using the decorator @login_required at the moment it redirects to an unexisting route /login how can i manually set the route?

This is my code:

@auth.route('/logout', methods=['POST'])
@login_required
def logout():
    session.pop("user", None)
    return redirect(url_for('index'))
2 Answers

You didn't mention which library you were using, so I'm assuming it's a package that contains Flask Login. You can alter the login view by changing the config value for the login_manager.login_view as seen here

Use flask-login to handle user sessions.

(venv)$ pip3 install flask-login && pip3 freeze > requirements.txt

Add this package to your application instance. This is either the __init__.py file or the file that has:

from flask import Flask

app = Flask(__name__)

if __name__ == '__main__':
    app.run(host='0.0.0.0')
    

This is how you add it:

# __init__.py

from flask import Flask
from flask_login import LoginManager

app = Flask(__name__)

login = LoginManager(app)
login.login_view = 'login'

from app import routes

I have passed the login view function to the login object. This function is the one that handles user logins.

from app import app
from flask_login import login_required


@app.route('/')
@app.route('/index')
@login_required
def index():
    return render_template('index.html')


@app.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = LoginForm()
    if form.validate_on_submit():
        # Your code
    return render_template('login.html', form=form)

I have passed the login_required decorator to the index() view function. Every time a user want to access the index page, they will be redirected to the login page for authentication, which is rendered by the login view function. After a successful login, only then will this person access the index page.

Feel free to pass the login_required decorator to any other function that can be anonymously accessed. I have seen that you are using blueprints. My example does not make use of blueprints, though it should be fairly easy for you to update the code to use your blueprints.

Related