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):
...
grpcpython目前不支持服务器端全局错误处理程序。拦截器不会在
intercept_service
函数内执行服务器处理程序,因此无法尝试/except。在另外,我发现grpcpython服务器拦截器实现与他们最初在L13-Python-Interceptors.md#server-interceptors上提出的实现不同。如果实现坚持最初的设计,我们可以使用拦截器作为全局错误处理程序,并使用
handler
和request
/request_iterator
。在请向https://github.com/grpc/grpc/issues提交功能请求问题。在
正如前面的一些评论所建议的,我尝试了元类方法,它非常有效。在
附件是一个简单的例子来演示如何拦截grpc调用。 您可以通过向元类提供一个可以应用于每个函数的decorator列表来扩展它。在
另外,对于应用包装器的方法,最好是更具选择性。一个好的选择是列出自动生成的基类的方法,并且只包装这些方法。在
相关问题 更多 >
编程相关推荐