Example #1
0
    def test_class_array(self):
        peeps = []
        names = ['bob', 'jim', 'peabody', 'mumblesleeves']
        dob = datetime.datetime(1979, 1, 1, tzinfo=pytz.utc)
        for name in names:
            a = Person()
            a.name = name
            a.birthdate = dob
            a.age = 27
            peeps.append(a)

        type = Array(Person)
        type.resolve_namespace(type, __name__)

        element = etree.Element('test')

        XmlDocument().to_parent_element(type, peeps, ns_test, element)
        element = element[0]

        self.assertEquals(4, len(element.getchildren()))

        peeps2 = XmlDocument().from_element(type, element)
        for i in range(0, 4):
            self.assertEquals(peeps2[i].name, names[i])
            self.assertEquals(peeps2[i].birthdate, dob)
Example #2
0
    def process_simple_type_list(self, s, name=None):
        item_type = s.list.item_type
        if item_type is None:
            self.debug1(
                "skipping simple type: %s because its list itemType "
                "could not be found", name)
            return

        base = self.get_type(item_type)
        if base is None:
            self.pending_simple_types[self.get_name(item_type)].add((s, name))
            self.debug1(
                "pending  simple type list: %s "
                "because of unseen base %s", name, item_type)

            return

        self.debug1("adding   simple type list: %s", name)
        retval = Array(base,
                       serialize_as='sd-list')  # FIXME: to be implemented
        retval.__type_name__ = name
        retval.__namespace__ = self.tns

        assert not retval.get_type_name() is retval.Empty
        return retval
Example #3
0
        class SomeClass(TableModel):
            __tablename__ = 'some_class'

            id = Integer32(primary_key=True)

            children = Array(
                SomeChildClass,
                store_as=table(
                    multi='children',
                    lazy='joined',
                    left='parent_id',
                    right='child_id',
                    fk_left_ondelete='cascade',
                    fk_right_ondelete='cascade',
                ),
            )

            other_children = Array(
                SomeOtherChildClass,
                store_as=table(
                    multi='children',
                    lazy='joined',
                    left='parent_id',
                    right='other_child_id',
                    fk_left_ondelete='cascade',
                    fk_right_ondelete='cascade',
                ),
            )
Example #4
0
    def test_class_nested_array(self):
        peeps = []
        names = ['bob', 'jim', 'peabody', 'mumblesleves']

        for name in names:
            a = Person()
            a.name = name
            a.birthdate = datetime.datetime(1979, 1, 1)
            a.age = 27
            a.addresses = []

            for i in range(0, 25):
                addr = Address()
                addr.street = '555 downtown'
                addr.city = 'funkytown'
                a.addresses.append(addr)
            peeps.append(a)

        type = Array(Person)
        type.resolve_namespace(type, __name__)
        element = etree.Element('test')
        XmlDocument().to_parent(None, type, peeps, element, ns_test)
        element = element[0]

        self.assertEquals(4, len(element.getchildren()))

        peeps2 = XmlDocument().from_element(None, type, element)
        for peep in peeps2:
            self.assertEquals(27, peep.age)
            self.assertEquals(25, len(peep.addresses))
            self.assertEquals('funkytown', peep.addresses[18].city)
Example #5
0
    def test_class_array(self):
        peeps = []
        names = ['bob', 'jim', 'peabody', 'mumblesleeves']
        dob = datetime.datetime(1979, 1, 1, tzinfo=pytz.utc)
        for name in names:
            a = Person()
            a.name = name
            a.birthdate = dob
            a.age = 27
            peeps.append(a)

        type = Array(Person)
        type.resolve_namespace(type, __name__)

        element = etree.Element('test')

        XmlDocument().to_parent(None, type, peeps, element, ns_test)
        element = element[0]

        self.assertEquals(4, len(element.getchildren()))

        peeps2 = XmlDocument().from_element(None, type, element)
        for i in range(0, 4):
            self.assertEquals(peeps2[i].name, names[i])
            self.assertEquals(peeps2[i].birthdate, dob)
Example #6
0
    def test_class_nested_array(self):
        peeps = []
        names = ['bob', 'jim', 'peabody', 'mumblesleves']

        for name in names:
            a = Person()
            a.name = name
            a.birthdate = datetime.datetime(1979, 1, 1)
            a.age = 27
            a.addresses = []

            for i in range(0, 25):
                addr = Address()
                addr.street = '555 downtown'
                addr.city = 'funkytown'
                a.addresses.append(addr)
            peeps.append(a)

        type = Array(Person)
        type.resolve_namespace(type, __name__)
        element = etree.Element('test')
        XmlDocument().to_parent_element(type, peeps, ns_test, element)
        element = element[0]

        self.assertEquals(4, len(element.getchildren()))

        peeps2 = XmlDocument().from_element(type, element)
        for peep in peeps2:
            self.assertEquals(27, peep.age)
            self.assertEquals(25, len(peep.addresses))
            self.assertEquals('funkytown', peep.addresses[18].city)
Example #7
0
 def test_array_customization(self):
     CC = Array(Unicode).customize(
         serializer_attrs=dict(min_len=5),
         punks='roll',
     )
     assert CC.Attributes.punks == 'roll'
     assert CC._type_info[0].Attributes.min_len == 5
Example #8
0
        class SomeClass(TableModel):
            __tablename__ = 'some_class'
            __table_args__ = {"sqlite_autoincrement": True}

            id = Integer32(primary_key=True)
            others = Array(SomeOtherClass,
                           store_as=table(multi=True, backref='some_classes'))
Example #9
0
        class SomeClass(TableModel):
            __tablename__ = 'some_class'
            __table_args__ = {"sqlite_autoincrement": True}

            id = Integer32(primary_key=True)
            others = Array(SomeOtherClass, store_as='json')
            f = Unicode(32, default='uuu')
Example #10
0
    def test_self_referential_array_workaround(self):
        from spyne.util.dictdoc import get_object_as_dict

        class Category(ComplexModel):
            id = Integer(min_occurs=1, max_occurs=1, nillable=False)

        Category._type_info['children'] = Array(Category)

        parent = Category()
        parent.children = [Category(id=0), Category(id=1)]

        d = get_object_as_dict(parent, Category)
        pprint(d)
        assert d['children'][0]['id'] == 0
        assert d['children'][1]['id'] == 1

        class SoapService(ServiceBase):
            @rpc(_returns=Category)
            def view_categories(ctx):
                pass

        Application([SoapService],
                    'service.soap',
                    in_protocol=ProtocolBase(),
                    out_protocol=ProtocolBase())
Example #11
0
    def test_array_customization_complex(self):
        class C(ComplexModel):
            u = Unicode

        CC = Array(C).customize(punks='roll',
                                serializer_attrs=dict(bidik=True))
        assert CC.Attributes.punks == 'roll'
        assert CC._type_info[0].Attributes.bidik == True
Example #12
0
 def test_wrapped_array(self):
     parent = etree.Element('parent')
     val = ['a', 'b']
     cls = Array(Unicode, namespace='tns')
     XmlDocument().to_parent(None, cls, val, parent, 'tns')
     print(etree.tostring(parent, pretty_print=True))
     xpath = parent.xpath('//x:stringArray/x:string/text()',
                                                     namespaces={'x': 'tns'})
     assert xpath == val
        class Service(Service):
            @rpc(String(max_occurs='unbounded'),
                 _returns=Array(KeyValuePair),
                 _in_variable_names={'keys': 'key'})
            def get_values(ctx, keys):
                session = self.Session()

                return session.query(KeyValuePair).filter(
                    sql.and_(KeyValuePair.key.in_(keys))).order_by(
                        KeyValuePair.key)
Example #14
0
class User(TableModel):
    __tablename__ = 'user'
    __namespace__ = 'spyne.examples.sql_crud'
    __table_args__ = {"sqlite_autoincrement": True}

    id = UnsignedInteger32(primary_key=True)
    name = Unicode(256)
    first_name = Unicode(256)
    last_name = Unicode(256)
    permissions = Array(Permission, store_as='table')
Example #15
0
File: parser.py Project: hozn/spyne
    def process_simple_type_list(self, s, name=None):
        item_type = s.list.item_type
        if item_type is None:
            self.debug1("skipping simple type: %s because its list itemType "
                        "could not be found", name)
            return

        base = self.get_type(item_type)
        if base is None:
            self.pending_simple_types[self.get_name(item_type)].add((s, name))
            self.debug1("pending  simple type list: %s "
                                   "because of unseen base %s", name, item_type)

            return

        self.debug1("adding   simple type list: %s", name)
        retval = Array(base, serialize_as='sd-list')  # FIXME: to be implemented
        retval.__type_name__ = name
        retval.__namespace__ = self.tns

        assert not retval.get_type_name() is retval.Empty
        return retval
Example #16
0
    def test_append_field_array(self):
        class C(TableModel):
            __tablename__ = "c"
            id = Integer32(pk=True)

        class D(TableModel):
            __tablename__ = "d"
            id = Integer32(pk=True)

        C.append_field('d', Array(D).store_as('table'))
        assert C.Attributes.sqla_mapper.get_property('d').argument is D
        print(repr(D.Attributes.sqla_table))
        assert isinstance(D.Attributes.sqla_table.c['c_id'].type, sqlalchemy.Integer)
Example #17
0
        class Bar(TableModel):
            __tablename__ = 'bar'
            __table_args__ = {"sqlite_autoincrement": True}
            __mapper_args__ = {
                'polymorphic_on': 'type',
                'polymorphic_identity': 'bar',
                'with_polymorphic': '*',
            }

            id = Integer32(primary_key=True)
            s = Unicode(64)
            type = Unicode(6)
            foos = Array(Foo).store_as('table')
Example #18
0
    def test_append_field_array_many(self):
        class C(TableModel):
            __tablename__ = "c"
            id = Integer32(pk=True)

        class D(TableModel):
            __tablename__ = "d"
            id = Integer32(pk=True)

        C.append_field('d', Array(D).store_as(table(multi='c_d')))
        assert C.Attributes.sqla_mapper.get_property('d').argument is D
        rel_table = C.Attributes.sqla_metadata.tables['c_d']
        assert 'c_id' in rel_table.c
        assert 'd_id' in rel_table.c
Example #19
0
 class SomeService(ServiceBase):
     @rpc(_body_style='bare', _returns=Array(String))
     def some_call(ctx):
         return ['abc', 'def']
Example #20
0
 class SomeService(ServiceBase):
     @rpc(Array(t))
     def some_call(ctx, arg):
         pass
Example #21
0
 class D(TableModel):
     __tablename__ = "d"
     id = Integer32(pk=True)
     c = Array(C).store_as('table')
Example #22
0
 class D(TableModel):
     __tablename__ = "dd"
     id = Integer32(pk=True)
     c = Array(C).customize(store_as=table(right='dd_id'))
Example #23
0
        class SomeClass(TableModel):
            __tablename__ = 'some_class'

            id = Integer32(primary_key=True)
            children = Array(SomeChildClass).store_as('table')
            mirror = SomeChildClass.store_as('table')
Example #24
0
 class SomeClass1(TableModel):
     __tablename__ = "%s_%d" % (fn, 1)
     _type_info = [
         ('i', Integer32(pk=True)),
         ('a', Array(SomeClass, store_as='json')),
     ]
Example #25
0
 class Service1(ServiceBase):
     @rpc(SomethingElse, _returns=Array(KeyValuePair))
     def some_call(ctx, sth):
         pass
Example #26
0
 class SomeClass(SomeOtherClass):
     __mapper_args__ = {'polymorphic_identity': 2}
     numbers = Array(Integer32).store_as(xml(no_ns=True, root_tag='a'))
Example #27
0
 class SomeClass(SomeOtherClass):
     numbers = Array(Integer32).store_as(xml(no_ns=True, root_tag='a'))
Example #28
0
        class SomeClass(TableModel):
            __tablename__ = 'some_class'
            __table_args__ = {"sqlite_autoincrement": True}

            id = Integer32(primary_key=True)
            others = Array(SomeOtherClass, store_as=xml(no_ns=True))
Example #29
0
 class Service2(ServiceBase):
     @rpc(BetterSomething, _returns=Array(KeyValuePair))
     def some_other_call(ctx, sth):
         pass
Example #30
0
 class DataRequest(ComplexModel):
     status = Array(RequestStatus)
Example #31
0
 class SomeService(ServiceBase):
     @rpc(Array(Unicode), Iterable(Unicode))
     def some_call(ctx, a, b):
         pass
Example #32
0
        class SomeClass(TableModel):
            __tablename__ = 'some_class'

            id = Integer32(primary_key=True)
            values = Array(Unicode).store_as('table')
Example #33
0
def log_repr(obj, cls=None, given_len=None, parent=None, from_array=False, tags=None):
    """Use this function if you want to serialize a ComplexModelBase instance to
    logs. It will:

        * Limit size of the String types
        * Limit size of Array types
        * Not try to iterate on iterators, push data, etc.
    """

    if tags is None:
        tags = set()

    if obj is None:
        return 'None'

    if cls is None:
        cls = obj.__class__

    if cls in (list, tuple):
        cls = Array(Any)

    if cls is dict:
        cls = AnyDict

    if cls in NATIVE_MAP:
        cls = NATIVE_MAP[cls]

    if hasattr(obj, '__class__') and issubclass(obj.__class__, cls):
        cls = obj.__class__

    if hasattr(cls, 'Attributes') and not cls.Attributes.logged:
        return "%s(...)" % cls.get_type_name()

    if issubclass(cls, File) and isinstance(obj, File.Value):
        cls = obj.__class__

    if cls.Attributes.logged == 'len':
        l = '?'
        try:
            if isinstance(obj, (list, tuple)):
                l = str(sum([len(o) for o in obj]))
            else:
                l = str(len(obj))
        except TypeError:
            if given_len is not None:
                l = str(given_len)

        return "<len=%s>" % l

    if (issubclass(cls, Array) or cls.Attributes.max_occurs > 1) and not \
                                                                     from_array:
        if id(obj) in tags:
            return "%s(...)" % obj.__class__.__name__
        tags.add(id(obj))

        retval = []
        subcls = cls
        if issubclass(cls, Array):
            subcls, = cls._type_info.values()

        if isinstance(obj, PushBase):
            retval = '[<PushData>]'

        else:
            for i, o in enumerate(obj):
                if i >= MAX_ARRAY_ELEMENT_NUM:
                    retval.append("(...)")
                    break

                retval.append(log_repr(o, subcls, from_array=True, tags=tags))

            retval = "[%s]" % (', '.join(retval))

    elif issubclass(cls, ComplexModelBase):
        if id(obj) in tags:
            return "%s(...)" % obj.__class__.__name__
        tags.add(id(obj))

        retval = []
        i = 0

        for k, t in cls.get_flat_type_info(cls).items():
            if i >= MAX_FIELD_NUM:
                retval.append("(...)")
                break

            if not t.Attributes.logged:
                continue

            try:
                v = getattr(obj, k, None)
            except (AttributeError, KeyError):
                v = None

            # HACK!: sometimes non-db attributes restored from database don't
            # get properly reinitialized.
            if isclass(v) and issubclass(v, ModelBase):
                continue

            polymap = t.Attributes.polymap
            if polymap is not None:
                t = polymap.get(v.__class__, t)

            if v is not None:
                retval.append("%s=%s" % (k, log_repr(v, t, parent=k, tags=tags)))
                i += 1

        return "%s(%s)" % (cls.get_type_name(), ', '.join(retval))

    elif issubclass(cls, Unicode) and isinstance(obj, six.string_types):
        if len(obj) > MAX_STRING_FIELD_LENGTH:
            return '%r(...)' % obj[:MAX_STRING_FIELD_LENGTH]

        else:
            return repr(obj)

    elif issubclass(cls, File) and isinstance(obj, PGFileJson.FileData):
        retval = log_repr(obj, PGFileJson.FileData, tags=tags)

    else:
        retval = repr(obj)

        if len(retval) > MAX_STRING_FIELD_LENGTH:
            retval = retval[:MAX_STRING_FIELD_LENGTH] + "(...)"

    return retval
Example #34
0
 class SomeService(Service):
     @rpc(_returns=Array(SomeComplexModel))
     def get(ctx):
         return v