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 @   wellplayed  阅读(32)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示