我在许多Spyne示例中看到,所有方法都没有典型的self参数;没有Spyne使用self参数的例子,也没有cls。它们使用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 + "!"发布于 2015-03-02 18:13:35
我所做的是子类应用程序类,然后通过ctx.app访问应用程序对象。
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类进行子类化--通过对上下文进行子类化,但是这应该允许您动态地工作。
为了回到您的问题,您还可以访问您的服务,因为这是在Application.services属性中定义的。
https://stackoverflow.com/questions/25306106
复制相似问题