Flask使用装饰器注意点

一 装饰器,需要放在路由装饰器下面

'''
在执行视图函数之前,做判断--》
路由的装饰器是控制路由匹配的--》
需要先执行,所以登录认证装饰器,需要放在下面
'''

二 需要直接指定路由别名

原因

'''
直接添加会报错————每个路由,都会有个别名,如果不写,默认以函数名作为别名

如果视图函数加了装饰器—————函数名就变成了 inner
而所有视图函数都叫inner,导致路由别名冲突了
'''

书写方式

@app.route('/',endpoint='index')
@auth
def index():
    return render_template('index.html', users=USERS)

登录装饰器案例

def auth(func):
    def inner(*args, **kwargs):
        if session.get('name'):
            # 在执行真正被装饰的函数之前,就要认证完
            res = func(*args, **kwargs)
            return res
        else:
            # 重定向到 登录页面
            return redirect('/login')

    return inner

@app.route('/',endpoint='index')
@auth
def index():
    return render_template('index.html', users=USERS)
posted @ 2024-02-28 16:03  wellplayed  阅读(45)  评论(0)    收藏  举报