def requires_auth(f):
@wraps(f)
def decorated(*args,**kwargs):
auth = request.authorization #认证
if not auth or not check_auth(auth.username, auth.password): # 如果没有认证,或者用户名、密码不正确
authenticate() #执行认证函数
returnf(*args,**kwargs)return decorated
日志
日志是装饰器运用的另一个亮点。就是在执行函数的时候将这个过程记录在日志:
from functools import wraps
def logit(func):
@wraps(func)
def with_logging(*args,**kwargs):print(func.__name__ +" was called")returnfunc(*args,**kwargs)return with_logging
@logit
def addition_func(x):"""Do some math."""return x + x
result =addition_func(4)
带参数的装饰器类
程序示例:
"""
"""
我的第四个装饰器
version:1.0
writer:假书生@
date:2020.02.09"""
from functools import wraps
def Logi(files ='log.txt'): #传入日志参数
def Outer(func):
@wraps(func)
def Inner(*args,**kwargs):
str = func.__name__ +"is called" #写入日志文件的内容
with open (files,'a') as file: #打开日志文件
file.write(str+'\n') #在日志文件中写入内容
returnfunc(*args,**kwargs)return Inner
return Outer
@Logi()
def Hello():print("Hello,world,")Hello()