【问题标题】:Why does inserting a function inside a route differ from inserting the code inside the function in Flask?为什么在路由中插入函数与在 Flask 中的函数中插入代码不同?
【发布时间】:2023-02-23 00:50:50
【问题描述】:

我正在尝试制作一个带有登录系统的网络应用程序。我想让它使用户无法访问某些页面,除非他们已登录。

我想要的是,当您在未登录的情况下单击转到另一个页面时,您将被重定向到登录页面,并在其上收到一条消息。

这是有效的:

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

但这并不像我想要的那样工作。它而是重定向到主页,然后闪烁消息。我该如何解决?

【问题讨论】:

    标签: python flask flask-login


    【解决方案1】:

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

    在您的第一段代码中,您正确地处理了这个问题。你把 redirect(...) 的结果返回给 flask。在您的第二段代码中,您采用require_login 返回的重定向并在home 中忽略它。

    你可能会尝试这样的事情:

    value = require_login()
    if value:
         return value
    

    【讨论】:

      【解决方案2】:

      你需要返回函数

      return require_login()
      

      但是请注意,在那之后您将无法拥有代码。您应该为此创建一个装饰器。网上有例子只是谷歌“flask authorized decorator”

      你的优势是你可以将授权逻辑移出视图,你可以轻松地装饰你的视图并且不在每个视图/路由中都有这些东西

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-04-24
        • 1970-01-01
        • 1970-01-01
        • 2016-11-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多