0

我还没有找到一种方法来描述可重复原始类型的 xml 属性;到目前为止我最好的猜测:

class Contact(ComplexModel):
    "contact person and communication channel"
    contactName = primitive.Unicode(min_len=1, max_len=70, nillable=False)
    channel = primitive.Unicode(max_occurs='unbounded')
    channelCode = XmlAttribute(Enum('TELEPHONE', 'TELEFAX', 'EMAIL', 'WEBSITE', type_name='channelCode'), attribute_of='channel')

这会产生一个看起来正确的 wsdl(至少对我而言):

<xs:complexType name="Contact">
    <xs:sequence>
        <xs:element name="channel" minOccurs="0" maxOccurs="unbounded" nillable="true">
            <xs:complexType>
                <xs:simpleContent>
                    <xs:extension base="xs:string">
                        <xs:attribute name="channelCode" type="tns:channelCode"/>
                    </xs:extension>
                </xs:simpleContent>
            </xs:complexType>
        </xs:element>
        <xs:element name="contactName" type="tns:Contact_contactNameType" minOccurs="0"/>
    </xs:sequence>
</xs:complexType>

但我不知道如何使用 Contact 类!

>>> c = Contact()
>>> c.contactName = 'xxx'
>>> c.channel = [ '1', '2' ]
>>> # c.channelCode = ???
4

1 回答 1

2

你快到了 :) 你只需要将 channelCode 的类型声明放到一个单独的变量中。

ChannelCodeType = Enum('TELEPHONE', 'TELEFAX', 'EMAIL', 'WEBSITE',
                                               type_name='channelCode')

class Contact(ComplexModel):
    "contact person and communication channel"
    contactName = primitive.Unicode(min_len=1, max_len=70, nillable=False)
    channel = primitive.Unicode(max_occurs='unbounded')
    channelCode = XmlAttribute(ChannelCodeType, attribute_of='channel')

现在你可以做正确的分配:

>>> c = Contact()
>>> c.contactName = 'xxx'
>>> c.channel = [ '1', '2' ]
>>> c.channelCode = [ChannelCodeType.TELEPHONE, ChannelCodeType.FAX]

要不就:

>>> Contact(
...     contactName='xxx',
...     channel=[ '1', '2' ],
...     channelCode=[ChannelCodeType.TELEPHONE, ChannelCodeType.FAX]
... )

此外,虽然我不在“测试是文档的一部分”阵营中,但我认为放置相关测试的链接是合适的,因为这与您的用例直接相关。

https://github.com/arskom/spyne/blob/1d5ecf26da1d29b68d92451ebf33e5db3f8833dc/spyne/test/protocol/test_xml.py#L141

最后一点:attribute_of从 2.11 起将被弃用。它不会在 2.x 系列中被删除,但会在 3.x 中消失。XmlData 将替换它,这既更容易实现,也更快。详细信息将在 2.11 文档中。

于 2014-01-14T20:13:10.857 回答