《Python进阶》读书笔记(2)

9.装饰器

既将函数传参给装饰器函数,在函数执行的上下文作某些通用操作。

记得要用@wraps复制函数名称(__name__),等等属性

使用举例:

from functools import wraps

def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            #若未登录,返回401
            authenticate()
        return f(*args, **kwargs)
    return decorated

继续阅读“《Python进阶》读书笔记(2)”