在实际开发中,我们有时候会用到自己定义装饰器并应用到函数视图或者类视图里面:
比如:我们要想进入个人中心页面,首先要验证你是否登录,否则进不去,下面我们来模拟这个场景

定义一个装饰器

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 '请先登录'
    return wrapper

函数视图应用自定义装饰器

@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'))

 

相关文章:

  • 2021-10-24
  • 2021-11-26
  • 2022-02-11
  • 2021-10-14
  • 2021-06-02
  • 2021-12-14
  • 2022-12-23
  • 2021-09-29
猜你喜欢
  • 2022-02-16
  • 2021-12-03
  • 2021-10-17
  • 2021-09-05
  • 2022-12-23
  • 2022-12-23
  • 2021-06-22
相关资源
相似解决方案