Skip to main content
 首页 » 编程设计

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

2025年04月02日12yxwkf

我对 spyne 的多个装饰器有疑问。我想为类中的每个方法添加通用的 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 我得到参数数量错误,我做错了什么?

请您参考如下方法:

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

对于异常处理,您可以在项目的类中覆盖 Application 或 ServiceBase 的 call_wrapper 函数,并使用它代替 stock斯派恩类(class)。你应该让你的 try/except block 包围 super() 调用。

请参阅 ServiceBase.call_wrapper 的 API 文档和 Application.call_wrapper .

你不喜欢这样做?您可以将事件处理程序添加到您的服务类或应用程序中。 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.

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

您已被警告:)