我在许多 Spyne 示例中看到,所有方法都没有典型的 self
参数;没有使用 self
参数或 cls
的 Spyne 示例。他们使用 ctx
参数,但 ctx
既不引用实例也不引用类(我需要维护一些状态)。
可以用吗?还是这些类没有实例化,而是作为静态类使用?
我正在尝试做类似的事情:
# -*- coding: utf-8 -*-
from __future__ import (
absolute_import,
unicode_literals,
print_function,
division
)
from spyne.decorator import rpc
from spyne.service import ServiceBase
from spyne.model.primitive import String
class RadianteRPC(ServiceBase):
def __init__(self, name):
self._name = name
@rpc(_returns=String)
def whoami(self):
"""
Dummy test method.
"""
return "Hello I am " + self._name + "!"
这段代码的问题在于,RadianteRPC
似乎从未被 Spyne 实例化为对象,而是作为静态类使用。
解决方案 1: 就目前而言,Spyne 不会实例化任何对象。然后,如果我们需要存储一些状态,我们可以通过类属性来实现。
因为我们不能在我们的方法中访问cls
参数,我们需要通过类名来引用类,所以我们可以这样做:
class RadianteRPC(ServiceBase):
_name = "Example"
@rpc(_returns=String)
def whoami(ctx): # ctx is the 'context' parameter used by Spyne
"""
Dummy test method.
"""
return "Hello I am " + RadianteRPC._name + "!"
解决方案 2(在 Spyne 邮件列表中找到):
在很多情况下,我们可能无法直接引用类名,所以我们有另一种选择:通过ctx参数查找类。
class RadianteRPC(ServiceBase):
_name = "Example"
@rpc(_returns=String)
def whoami(ctx): # ctx is the 'context' parameter used by Spyne
"""
Dummy test method.
"""
return "Hello I am " + ctx.descriptor.service_class._name + "!"
最佳答案
我做的是继承Application类,然后通过ctx.app访问application对象。
from spyne.protocol.soap.soap11 import Soap11
from spyne.server.wsgi import WsgiApplication
from spyne import Application, rpc, ServiceBase, Unicode, Boolean
class MyApplication(Application):
def __init__(self, *args, **kargs):
Application.__init__(self, *args, **kargs)
assert not hasattr(self, 'session')
self.session = 1
def increment_session(self):
self.session += 1
def get_session(self):
return self.session
class Service(ServiceBase):
@rpc(_returns=Integer)
def increment_session(ctx):
s = ctx.app.get_session()
self.increment_session()
return s
application = MyApplication([MatlabAdapterService],
'spyne.soap',
in_protocol=Soap11(validator='lxml'),
out_protocol=Soap11())
wsgi_application = WsgiApplication(application)
...
我想应该有一种“更干净”的方法——不需要应用程序类的子类——通过子类化上下文,但这应该允许你动态地工作。
回到您的问题,您还有机会访问您的服务,因为这是在 Application.services 属性中定义的。
关于python - 如何在 Spyne 服务器方法中使用 'self' 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25306106/