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

标签 python web-services wcf python-decorators spyne

我对 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/

相关文章:

python - 如何在 jupyter notebook 中触发保存命令?

python - 如何向 Python REST 请求添加基本身份验证?

c# - 返回大字节数组的 Web 服务

python - 在 Tkinter 文本小部件中粘贴

python - IBM 沃森对话 : How to programmatically turn messages to counterexamples?

来自 .net 客户端的 java web 服务

xml - Web 服务上的 X509Certificate2 验证

wcf - 在 IIS 上托管 WCF 服务(找不到资源)

python - 在 python 中导航文本文件搜索

web-services - 使用 Netbeans 平台使用 Web 服务