在实际开发中,我们有时候会用到自己定义装饰器并运用到函数视图或者类视图,比如:我们想要进入个人中心页面,首先要验证是否登录,否则就进不去,下面来模拟这个场景
定义一个装饰器
from functools import wraps
...
def login_required(func):
@wraps(func) <---------保持原来函数的特性
def wrapper(*args, **kwargs ):
# /setting/?username=heboan
username = request.args.get(‘username‘)
if username and username == ‘heboan‘:
return func(*args, **kwargs)
else:
return ‘请先登录‘
函数视图运用自定义装饰器
@app.route(‘/lprofile/‘)
@login_required 《-----------------这个必须放在@app,route装饰器下面
def profile():
return render_template(‘profile.html‘)
类视图运用自定义装饰器
class ProfileView(views.View):
decorators = [login_required]
def dispatch_request(self):
return render_template(‘profile.html‘)
app.add_url_rule(‘/profile/‘, view_func=ProfileView.as_view(‘profile‘))