简体   繁体   English

重定向至before_request()

[英]Redirect in before_request()

I'm aware that the before_request() function is executed before the function attached to the route is executed. 我知道在执行附加到路由的函数之前先执行了before_request()函数。

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. 我的代码检查用户是否登录到before_request()函数,如果不是,则重定向到索引页面。 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. 这会在终端中显示“ NO LOGGED IN”,但不会重定向。 How do I redirect correctly? 如何正确重定向?

You need to return the redirect, not just create it. 您需要返回重定向,而不仅仅是创建重定向。

return redirect(url_for('index'))

Consider using Flask-Login rather than doing this yourself. 考虑使用Flask-Login,而不要自己做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM