Scenarios decorator
- Additional features
- Data cleanup or add:
- Parameter type validation function similar to the previous request interceptor @require_ints
- After the data format conversion function returns the dictionary to JSON / YAML similar response tamper
- Provide additional data as a function of mock.patch
- Registration function
- Register a task in the task center
- A registration function with the signal processor
Decorators to achieve under different scenarios
Functions Registry
- Simple Registry
funcs = []
def register(func):
funcs.append(func)
return func
@register
def a():
return 3
@register
def b():
return 5
# 访问结果
result = [func() for func in funcs]
- Registry isolation (using different instances of the class)
class Registry(object):
def __init__(self):
self._funcs = []
def register(self, func):
self._funcs.append(func)
def run_all(self):
return [func() for func in self._funcs]
r1 = Registry()
r2 = Registry()
@r1.register
def a():
return 3
@r2.register
def b():
return 5
@r1.register
@r2.register
Code is executed when the package
- Type checking
from functools import wraps
def require_ints(func):
@wraps(func) # 将func的信息复制给inner
def inner(*args, **kwargs):
for arg list(args) + list(kwargs.values()):
if not isinstance(arg, int:
raise TypeError("{} 只接受int类型参数".format(func.__name__)
return func(*args, **kwargs)
return inner
- User Authentication
from functools import wraps
class User(object):
def __init__(self, username, email):
self.username = username
self.email = email
class AnonymousUser(object):
def __init__(self):
self.username = self.email = None
def __nonzero__(self): # 将对象转换为bool类型时调用
return False
def requires_user(func):
@wraps(func)
def inner(user, *args, **kwargs): # 由于第一个参数无法支持self, 该装饰器不支持装饰类
if user and isinstance(user, User):
return func(use, *args, **kwargs)
else:
raise ValueError("非合法用户")
return inner
- Output Format
import json
from functools import wraps
def json_output(func): # 将原本func返回的字典格式转为返回json字符串格式
@wrap(func)
def inner(*args, **kwargs):
return json.dumps(func(*args, **kwargs))
return inner
- Exception trap
import json
from functools import wraps
class Error1(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
def json_output(func):
@wrap(func)
def inner(*args, **kwargs):
try:
result = func(*args, **kwargs)
except Error1 as ex:
result = {"status": "error", "msg": str(ex)}
return json.dumps(result)
return inner
# 使用方法
@json_ouput
def error():
raise Error1("该条异常会被捕获并按JSON格式输出")
- Log Management
import time
import logging
from functools import wraps
def logged(func):
@wraps(func)
def inner(*args, **kwargs): # *args可以装饰函数也可以装饰类
start = time.time()
result = func(*args, **kwargs)
exec_time = time.time() - start
logger = logging.getLoger("func.logged")
logger.warning("{} 调用时间:{:.2} 执行时间:{:.2}s 结果:{}".format(func.__name__, start, exec_time, result)
Decorator with parameters
Decorator with parameters corresponding to a decorator return function, @deco(a=1)
the call @
before the first execution will deco(a=1)
get a real decorator, decorator with parameters deco(a=1)
executed immediately when the module is introduced
Decoration
- (When not expanded by subclasses super method, such as a plurality of classes need to add this functionality) increase the sorting class
import time
from functools import wraps
def sortable_by_created(cls):
original_init = cls.__init__
@wrap(original_init)
def new_init(self, *args, **kwargs):
original_init(*args, **kwargs)
self._created = time.time()
cls.__init__ = new_init
cls.__lt__ = lambda self, other: self._created < other._created
cls.__gt__ = lambda self, other: self._created > other._created
return cls
Also define a SortableByCreated () class, subclass and its superclass using multiple inheritance SortableByCreated
Type Conversion
There may be decorated after the function becomes an instance of a class, this time for compatibility function calls should be provided for the class returned by __call__
the method
class Task(object):
def __call__(self, *args, **kwargs):
return self.run(*args, **kwargs)
def run(self, *args, **kwargs):
raise NotImplementedError("子类未实现该接口")
def task(func):
class SubTask(Task):
def run(self, *args, **kwargs):
func(*args, **kwargs)
return SubTask()
Chapter II context manager
definition
- Packaging arbitrary code
- Ensure consistency of execution
grammar
- with statement
- __enter__ method and __exit__
class ContextManager(object):
def __init__(self):
self.entered = False
def __enter__(self):
self.entered = True
return self
def __exit__(self, exc_type, exc_instance, traceback):
self.entered = False
Scenarios
Resource Cleanup
import pymysql
class DBConnection(object):
def __init__(self, *args, **kwargs):
self.args,self.kwargs = args, kwargs
def __enter__(self):
self.conn = pymysql.connect(*args, **kwargs)
return self.conn.cursor()
def __exit__(self, exc_type, exc_instance, trackback):
self.conn.close()
Exception handling (to avoid repetition)
- Abnormal propagation (in the __exit__ return False)
- Abnormal termination (__exit__ in return True)
class BubleExceptions(object):
def __enter__(self):
return self
def __exit__(self, exc_type, exc_instance, trackback):
if exc_instance:
print("出现异常: {}".format(exc_instance)
return False # return True终止异常
- Deal with specific exceptions
class HandleValueError(object):
def __enter__(self):
return self
def __exit__(self, exc_type, exc_instance, trackback):
if not exc_type: return True
if issubclass(exc_type, ValueError):
print("处理ValueError: {}".format(exc_instance)
return False
if issubclass...
Statement toif exec_type == ValueError
ValueType not process a subclass
It may also be determined whether or terminated in accordance with the propagation property abnormality
Simpler syntax
import contextlib
@contextlib.contextmanager
def acceptable_error_codes(*codes):
try:
yield
except ShellException as exc_instance:
if exc_instance.code not in codes:
raise
pass