我有以下内容:
from spyne.service import ServiceBase
from spyne.util import xml
from spyne.model import complex, primitive
class ComplexModel(complex.ComplexModelBase):
__namespace__ = 'http://xml.candyshop.com/ns/candies/'
__metaclass__ = complex.ComplexModelMeta
class CandyModel(ComplexModel):
__type_name__ = 'candy'
flavor = complex.XmlAttribute(primitive.Unicode)
class BagModel(ComplexModel):
__type_name__ = 'bag'
candies = complex.Array(CandyModel)
class CandyShop(ServiceBase):
__tns__ = 'http://xml.candyshop.com/ns/shop/'
@rpc(_returns=primitive.AnyXml)
def get_my_bag(ctx):
bag = BagModel()
bag.candies = [CandyModel(flavor='choco')]
return xml.get_object_as_xml(
bag,
cls=BagModel,
root_tag_name='bag',
)
@classmethod
def dispatch(cls):
from django.views.decorators.csrf import csrf_exempt
from spyne.application import Application
from spyne.server.django import DjangoApplication
application = Application([cls],
tns=cls.__tns__,
in_protocol=Soap11(validator='lxml'),
out_protocol=Soap11(cleanup_namespaces=True)
)
return csrf_exempt(DjangoApplication(application))
shop_service = CandyShop.dispatch()
结果get_my_bag
如下:
<tns:get_my_bagResult xmlns:tns="http://xml.candyshop.com/ns/shop/">
<ns0:bag xmlns:ns0="http://xml.candyshop.com/ns/candies/">
<ns0:candies>
<ns1:candy xmlns:ns1="None" flavor="choco"/>
</ns0:candies>
</ns0:bag>
</tns:get_my_bagResult>
但我想要以下:
<tns:get_my_bagResult xmlns:tns="http://xml.candyshop.com/ns/shop/">
<ns0:bag xmlns:ns0="http://xml.candyshop.com/ns/candies/">
<ns0:candies>
<ns0:specialCandy flavor="choco"/>
</ns0:candies>
</ns0:bag>
</tns:get_my_bagResult>
那么,如何在不定义新子类的情况下自定义数组内容的类型名称呢?我试过了
complex.Array(CandyModel.customize(type_name='specialCandy'))
但这不起作用。使用静态alias
方法给出了一个空的<ns0:candies/>
,也许我仍然把CandyModel
实例放到candies
列表中,但这是我的目标。
其次,为什么存在xmlns:ns1="None"
以及如何解决它ns0
?
顺便提一句。有没有办法自定义命名空间前缀?
编辑
class Candies(complex.Array):
__namespace__ = 'http://xml.candyshop.com/ns/candies/'
和
candies = Candies(CandyModel)
解决了命名空间的问题,但它是一种解决方法而不是解决方案。我更喜欢内联自定义或一些带有我的命名空间的 mixin ComplexModel
。