mickzer
mickzer

Reputation: 6358

Redirect in before_request()

I'm aware that the before_request() function is executed before the function attached to the route is executed.

My code checks if the user is logged in in the before_request() function, and if they're not it redirects to the index page. However, the redirect isn't working. Here's my code:

@app.before_request
def before_request():
if(
    (
        request.endpoint != 'index' or
        request.endpoint != 'home' or
        request.endpoint != ''
    )
    and 'logged_in' not in session
):
    print("NOT LOGGED IN")
    redirect(url_for('index'))

This prints "NOT LOGGED IN" in the terminal, but doesn't redirect. How do I redirect correctly?

Upvotes: 0

Views: 3516

Answers (1)

davidism
davidism

Reputation: 127330

You need to return the redirect, not just create it.

return redirect(url_for('index'))

Consider using Flask-Login rather than doing this yourself.

Upvotes: 6

Related Questions