如何在 spyne 中使用多个装饰器

How to use multiple decorators with spyne

我对 spyne 的多个装饰器有疑问。我想为 class 中的每个方法添加通用 try/except 装饰器。我的代码如下所示:

def try_except(fn):
       def wrapped(*args, **kwargs):
           try:
               return fn(*args, **kwargs)
           except Exception:
               do_sth()
   return wrapped

class A(ServiceBase):

@rpc(Unicode, Integer, _returns=[Boolean, Integer], _out_variable_names=["FooResult", "bar"])
@try_except
def Foo(self, foo, bar):
    do_sth()
    return True, 0

使用@try_except 我得到参数数量错误,我做错了什么?

我不推荐装饰器。不是因为它们不受支持,而是因为它们不是很强大并且还有神秘的行为。

对于异常处理,您可以在项目的 class 中覆盖 ApplicationServiceBasecall_wrapper 函数,并使用它代替普通的 Spyne classes。您应该让 try/except 块包围 super() 调用。

请参阅 API 文档 ServiceBase.call_wrapper and Application.call_wrapper

你不喜欢这样做?您可以将事件处理程序添加到您的服务 classes 或应用程序中。 events example 可以帮助您入门。

你还想用装饰器?参见 this FAQ entry。引用相关位:

from decorator import decorator

def _do_something(func, *args, **kw):
    print "before call"
    result = func(*args, **kw)
    print "after call"
    return result

def my_decor(f):
    return decorator(_do_something, f)

class SomeService(ServiceBase):
    @my_decor
    @srpc(Integer, _returns=Integer)
    def testf(first):
        return first

Note that the place of the decorator matters. Putting it before @srpc will make it run once, on service initialization. Putting it after will make it run every time the method is called, but not on initialization.

再次声明,不要使用装饰器!!

您已收到警告:)