python装饰器应用场景

# -*- coding:utf-8 -*-
# 学习装饰器的一些常用场景

from functools import wraps

def decorator_name(f):
@wraps(f)
def decorated(*arg, **kwargs):
if not can_run:
return('Function will not run')
return f(*arg, **kwargs)
return decorated

@decorator_name
def func():
return('Function is running')

#can_run = True

#print(func())

can_run = False
print(func())
# 小结:@wraps接受一个函数来进行装饰,并加入了复制函数名称、注释文档、参数列表等功能。
# 这可以让我们在装饰器里面访问在装饰之前的函数的属性
"""
装饰器使用场景-授权(Authorization)
"""
# 装饰器能有助于检查某个人是否被授权去使用一个web应用的端点(endpoint)。它们被大量使用于
# Flask和Django web框架中。这里是一个例子来使用基于装饰器的授权
from functools import wraps

def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = requests.authorization
if not auth or not check_auth(auth.username, auth.password):
authenticate()
return f(*args, **kwargs)
return decorated

"""
装饰器使用场景-日志(Logging)
"""
# 日志是装饰器运用的另一个亮点,这是个例子

from functools import wraps

def logit(func):
@wraps(func)
def with_logging(*args, **kwargs):
print(func.__name__ + "was called")
return func(*args, **kwargs)
return with_logging
@logit
def addition_func(x):
"""Do some math"""
return x + x

result = addition_func(4)
print(result)

"""
带参数的装饰器-在函数中嵌入装饰器
"""
from functools import wraps

def logit1(logfile='out.log'):
def logging_decorator(func):
@wraps(func)
def wrapped_function(*args, **kwargs):
log_string = func.__name__ + " was called"
print(log_string)
# 打开logfile,并写入内容
with open(logfile, 'a') as opened_file:
# 现在将日志打印到指定的logfile
opened_file.write(log_string + '\n')
return func(*args, **kwargs)
return wrapped_function
return logging_decorator
@logit1(logfile='fun2.log')
def myfun1():
pass
myfun1()

"""
装饰器类
"""
from functools import wraps

class logit2(object):
def __init__(self, logfile='out.log'):
self.logfile = logfile

def __call__(self, func):
@wraps(func)
def wrapped_function(*args, **kwargs):
log_string = func.__name__ + " was called"
print(log_string)
# 打开logfile,并写入内容
with open(self.logfile, 'a') as opened_file:
# 现在将日志打印到指定的logfile
opened_file.write(log_string + '\n')
# 现在,发送一个通知
self.notify()
return func(*args, **kwargs)
return wrapped_function

def notify(self):
print('logit只打日志,不做别的')
pass

@logit2()
def myfunc2():
print('调用通知')

print('------')
myfunc2()

# 现在,我们给logit创建子类,来添加email的功能
class email_logit(logit2):
"""
一个logit的实现版本,可以在函数调用时发送email给管理员
"""
def __init__(self, email='mecexia@tencent.com', *args, **kwargs):
self.email = email
super(email_logit, self).__init__(*args, **kwargs)

def notify(self):
# 发送一封email到self.email
# 这里就不做实现了
pass





posted @ 2021-10-26 15:30  ReluStarry  阅读(363)  评论(0编辑  收藏  举报