Java中的AOP可以用JDK的动态代理和cglib来实现,将需要拦截的方法前后可以额外添加些功能。
Python中有许多方法去实现AOP,现在先介绍第一种比较简单的:
1)利用with...as...
Python的with...as...子句是用于控制执行流程的语句,结构是with expression as variable,这里的expression里定义拦截的方法前后需要执行的逻辑,分别定义“__enter__”和“__exit__”方法,“__enter__”方法定义拦截方法执行前的逻辑,“__exit__”方法定义拦截方法执行后的逻辑,with...as...子句的主体是拦截的方法执行的逻辑,variable变量是用来接收“__enter__”方法返回的值,下面来看个示例:
class AOP: def __enter__(self): print("before action enter") return 1 def __exit__(self, *args): print("after action enter") return 0 def Myfunction(): print ('Myfunction() called and processed ') return 111
def Myfunction1(): print ('Myfunction1() called and processed') return 222
def MyMain(): with AOP() as AOPValue: print ('AOPValue is %s'%AOPValue) Myfunction() Myfunction1() if __name__ == '__main__': MyMain()
最后输出的结果是:
before action enter AOPValue is 1 Myfunction() called and processed Myfunction1() called and processed after action enter
PS:with子句中的variable接收的是__enter__方法的返回值。这是with子句的基本用法
2)利用contextlib实现AOP
Python核心库中的contextlib中的contextmanager来实现AOP就非常简单了,contextmanager是一个装饰器,具体用法如下示例:
from contextlib import contextmanager
#define inteceptors
@contextmanager def AOPfunc(name): print ("before:some actions done") yield print ("after:some actions done ")
#normal service flow def BusinessProcess1(): print ('BusinessProcess1()') return 111
def BusinessProcess2(): print ('BusinessProcess2()') return 111
def BusinessProcess3(): print ('BusinessProcess3()') return 111
#main flow def MyMain(): with AOPfunc("aop"): BusinessProcess1() BusinessProcess2() with AOPfunc("aop"): BusinessProcess3()
if __name__ == '__main__': MyMain()
运行结果是:
before:some actions done BusinessProcess1() BusinessProcess2() after:some actions done before:some actions done BusinessProcess3() after:some actions done