Why does inserting a function inside a route differ from inserting the code inside the function in Flask?

Question:

I am trying to make a web app with a login system. I want to make it so that a user can’t access certain pages unless they are logged in.

What I want is that when you click to go to another page while not logged in, you get redirected to the login page and on it you get a message flash.

This is what works:

@app.route("/home", methods=['GET', 'POST'])
def home():
    #some form
    if not current_user.is_authenticated:
        flash('You need to be logged in to access this page.', 'info')
        return redirect(url_for('login'))
    #rest of the code

But I would need to add all of this to other routes as well. So I created the function and added it to the routes instead:

@app.route("/home", methods=['GET', 'POST'])
def home():
    #some form
    require_login()
    #rest of the code

def require_login():
    if not current_user.is_authenticated:
        flash('You need to be logged in to access this page.', 'info')
        return redirect(url_for('login'))

But this does not work as I want it to. It instead redirects to the home page and then flashes the message. How do I fix this?

Asked By: Roamex

||

Answers:

You need to return the function

return require_login()

But be aware, after that u cant have code. You should create an decorator for this. There are examples online just Google "flask authorized decorator"

Your Advantage of this that u can move the auth Logic out of the Views and you can easily decorate your Views and dont have this Stuff in each View/route

Answered By: Christoph

The problem is that the redirect(...) doesn’t itself do the redirect. It returns a value to Flask telling flask that it needs to do the redirect.

In your first piece of code, you handle this correctly. You take the result of redirect(...) and return it to flask. In your second piece of code, you take the redirection returned by require_login and ignore it in home.

You might try something like:

value = require_login()
if value:
     return value
Answered By: Frank Yellin
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.