Spyne。设置阵列固定数量项

时间:2013-07-22 06:44:20

标签: spyne

我使用数组属性在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.我的代码有什么问题,或者我需要设置数组的数组?

感谢。

1 个答案:

答案 0 :(得分:0)

两个选项:

  1. 您可以定义构造函数并以常规方式设置默认值。即。

    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)