请求前烧瓶 - 为特定路线添加例外 [英] flask before request - add exception for specific route

查看:15
本文介绍了请求前烧瓶 - 为特定路线添加例外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

before_request() 函数(如下)中,如果用户尚未登录,我想将用户重定向到 /login.是否有一个特殊的变量会给我提供如下示例所示的当前 URL 吗?

In the before_request() function (below), I want to redirect the user to /login if they are not yet logged in. Is there a special variable that will give me the current URL that will work as the below example does?

@app.before_request
def before_request():
    # the variable current_url does not exist
    # but i want something that works like it
    if (not 'logged_in' in session) and (current_url != '/login'):
        return redirect(url_for('login'))

我需要检查当前 URL 是否为 /login,因为如果我不这样做,服务器将进入无限循环.

I need to check that the current URL is /login, because if I don't the server goes into an infinite loop.

推荐答案

您可以检查请求对象上的几个属性,记录在 这里request.path 可能就是你想要的.我可以建议 request.endpoint,因此如果您决定将视图路由到另一个 url 或多个 url,您将被覆盖

There are a couple of properties on the request object you can check, documented here, request.path is probably what you want. Can I suggest request.endpoint though, so you'll be covered should you decide to route your view to another url, or multiple urls

@app.before_request
def before_request():
    if 'logged_in' not in session and request.endpoint != 'login':
        return redirect(url_for('login'))

这篇关于请求前烧瓶 - 为特定路线添加例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆