10、Flask实战第10天:视图使用装饰器

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

定义一个装饰器

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

猜你喜欢

转载自www.cnblogs.com/sellsa/p/9248726.html
今日推荐