正如前面的一些评论所建议的,我尝试了元类方法,它非常有效。在
附件是一个简单的例子来演示如何拦截grpc调用。
您可以通过向元类提供一个可以应用于每个函数的decorator列表来扩展它。在
另外,对于应用包装器的方法,最好是更具选择性。一个好的选择是列出自动生成的基类的方法,并且只包装这些方法。在from types import FunctionType
from functools import wraps
def wrapper(method):
@wraps(method)
def wrapped(*args, **kwargs):
# do stuff here
return method(*args, **kwargs)
return wrapped
class ServicerMiddlewareClass(type):
def __new__(meta, classname, bases, class_dict):
new_class_dict = {}
for attribute_name, attribute in class_dict.items():
if isinstance(attribute, FunctionType):
# replace it with a wrapped version
attribute = wrapper(attribute)
new_class_dict[attribute_name] = attribute
return type.__new__(meta, classname, bases, new_class_dict)
# In order to use
class MyGrpcService(grpc.MyGrpcServicer, metaclass=ServicerMiddlewareClass):
...