请求之前烧瓶 - 添加特定路线的异常 [英] flask before request - add exception for specific route

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

问题描述

在我的before_request()函数中,我想重定向用户/登录,如果他们还没有登录。是否有一个特殊的变量,会给我目前的网址,将作为下面的例子吗? ():

$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
efore $ #但是我想要的东西像它一样
if(not'logged_in'in session)and(current_url!='/ login'):
return redirect(url_for('login'))

我需要检查当前的网址是否为'/ login',因为如果我没有进入服务器一个无限循环。

谢谢!

解决方案

您可以查看的请求对象上的属性,有记录的此处, code> request.path 可能是你想要的。我可以建议 request.endpoint ,所以你会被覆盖,如果你决定将您的视图路由到另一个网址或多个URL

  @ app.before_request $ b $ def before_request():
如果'logged_in'不在session中并且request.endpoint!='login':
返回重定向(url_for('login'))


in my before_request() function, 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'))

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

thanks!

解决方案

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天全站免登陆