0

我在 spyne 中使用数组属性创建模型,我需要修复数组中的数字项。即我的模型看起来像:

class MyModel(ComplexModel):
__namespace__ = 'myns'

string_field = String(**{'min_occurs': 1, 'max_occurs': 1, 'nillable': False})
array_field = Array(Integer(**{'max_occurs': 16, 'min_occurs': 16, 'nillable': False}), 
                 **{'min_occurs': 1, 'max_occurs': 1, 'nillable': False})

因此,这意味着我需要具有字符串属性的对象和具有 16 个整数项的数组,但是此代码直接指向 xml,例如:

<myns:MyModel>
    <!--Optional:-->
    <myns:string_field>?</myns:string_field>
    <myns:array_field>
        <!--Zero or more repetitions:-->
        <myns:integer>?</myns:integer>
    </myns:array_field>
</myns:MyModel>

myns:array_field 中只有一个整数项,而不是 16。我的代码有什么问题,或者我需要设置多少个数组项?

谢谢。

4

1 回答 1

0

两种选择:

  1. 您可以按照通常的方式定义构造函数并设置默认值。IE

    class MyModel(ComplexModel):
        __namespace__ = 'myns'
    
        string_field = String(min_occurs=1, nillable=False)
        array_field = Array(Integer(max_occurs=16, min_occurs=16, nillable=False),
                     min_occurs=1, max_occurs=1, nillable=False)
    
        def __init__(self):
            self.array_field = [0] * 16
    
  2. 您可以为数组定义一个默认值。这是一个完整的工作脚本:

    from lxml import etree
    from spyne.model.complex import ComplexModel, Array
    from spyne.model.primitive import String, Integer
    
    class MyModel(ComplexModel):
        __namespace__ = 'myns'
    
        s = String(min_occurs=1, nillable=False)
        a = Array(Integer(max_occurs=16, min_occurs=16, nillable=False),
             min_occurs=1, max_occurs=1, nillable=False, default=[0]*16)
    
    from spyne.util.xml import get_object_as_xml
    
    print etree.tostring(get_object_as_xml(MyModel(s='some_string'), MyModel), pretty_print=True)
    
于 2013-07-22T10:58:29.197 回答