为什么在路由中插入函数与在Flask中在函数中插入代码不同



我正在尝试制作一个带有登录系统的web应用程序。我想让用户在登录之前无法访问某些页面。

我想要的是,当你在没有登录的情况下点击转到另一个页面时,你会被重定向到登录页面,并在上面看到一条消息。

这就是工作原理:

@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

但我也需要将所有这些添加到其他路线中。所以我创建了这个函数,并将其添加到路由中:

@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'))

但这并没有像我希望的那样工作。相反,它重定向到主页,然后闪烁消息。我该如何解决这个问题?

问题是redirect(...)本身不进行重定向。它向烧瓶返回一个值,告诉烧瓶它需要进行重定向。

在您的第一段代码中,您可以正确地处理此问题。取redirect(...)的结果并将其返回烧瓶。在第二段代码中,采用require_login返回的重定向,并在home中忽略它。

你可以试试这样的东西:

value = require_login()
if value:
return value

您需要返回函数

return require_login()

但要注意,在那之后你就不能有代码了。您应该为此创建一个装饰器。网上有一些例子,只有谷歌";烧瓶授权装饰师";

你的优势是,你可以将auth逻辑从视图中移出,你可以很容易地装饰你的视图,而不是在每个视图/路线中都有这个东西

最新更新