gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:27:46 25 4
gpt4 key购买 nike

我对 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 我得到参数数量错误,我做错了什么?

最佳答案

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

对于异常处理,您可以在项目的类中覆盖 ApplicationServiceBasecall_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.

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

您已被警告:)

关于python - 如何在 spyne 中使用多个装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38198523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com