我在许多 Spyne 示例中看到所有方法都没有典型self
参数;没有使用self
参数的 Spyne 示例,也没有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 + "!"