Example #1
0
class Person(ComplexModel):
    Id = Integer
    MelwinId = Integer
    FullName = Unicode
    BirthDate = DateTime
    GenderId = Integer
    GenderText = Unicode
    Email = Unicode
    Phone = Unicode
    Address = Unicode
    PostNumber = Unicode
    City = Unicode
    Updated = DateTime
    Created = DateTime
    MongoId = Unicode

    IsActive = Boolean
    ClubId = Integer
    PaymentStatus = Integer

    Gren = Array(Activity)
    activities = Array(Activity)
    clubs_payment = Array(ClubsPayment)
    Magazines = Array(Magazines)
    Products = Array(Products)
Example #2
0
class NestedClass(ComplexModel):
    __namespace__ = "punk.tunk"

    simple = Array(SimpleClass)
    s = String
    i = Integer
    f = Float
    other = OtherClass
    ai = Array(Integer)
Example #3
0
class InteropMisc(Service):
    @srpc(_returns=[
        Integer, String, Integer,
        Array(Enum("MEMBER", type_name="RoleEnum"))
    ],
          _out_variable_names=[
              'resultCode', 'resultDescription', 'transactionId', 'roles'
          ])
    def complex_return():
        return [1, "Test", 123, ["MEMBER"]]

    @srpc(_returns=Integer)
    def huge_number():
        return 2**int(1e5)

    @srpc(_returns=String)
    def long_string():
        return ('0123456789abcdef' * 16384)

    @srpc()
    def test_empty():
        pass

    @srpc(String, Integer, DateTime)
    def multi_param(s, i, dt):
        pass

    @srpc(NonNillableClass, _returns=String)
    def non_nillable(n):
        return "OK"

    @srpc(String, _returns=String, _operation_name="do_something")
    def do_something_else(s):
        return s

    @srpc(Integer, _returns=Array(OtherClass))
    def return_other_class_array(num):
        for i in range(num):
            yield OtherClass(dt=datetime(2010, 12, 6), d=3.0, b=True)

    @srpc(_returns=Integer)
    def return_invalid_data():
        return 'a'

    @srpc(
        String,
        # FIXME: find out why this could be needed
        # _public_name="urn:#getCustomMessages",
        _in_message_name="getCustomMessagesMsgIn",
        _out_message_name="getCustomMessagesMsgOut",
        _out_variable_name="CustomMessages",
        _returns=String)
    def custom_messages(s):
        return s
class Equipments(ComplexModel):
    _type_info = [
        ('synchronousMachines', Array(SynchronousMachine)),
        ('solars', Array(Solar)),
        ('batteries', Array(Battery)),
    ]

    def __init__(self, synchronousMachines, solars, batteries):
        super().__init__()
        self.synchronousMachines = synchronousMachines
        self.solars = solars
        self.batteries = batteries
Example #5
0
class TfbOrmService(ServiceBase):
    @rpc(_returns=World)
    def db(ctx):
        retval = ctx.udc.session.query(World).get(randint(1, 10000))
        return retval

    @rpc(NumQueriesType, _returns=Array(World))
    def dbs(ctx, queries):
        if queries is None:
            queries = 1

        q = ctx.udc.session.query(World)
        return [q.get(randint(1, 10000)) for _ in xrange(queries)]

    @rpc(_returns=Array(Fortune, html_cloth=T_INDEX), _body_style="out_bare")
    def fortunes(ctx):
        # This is normally specified at the application level as it's a good
        # practice to group rpc endpoints with similar return types under the
        # same url fragment. eg. https://example.com/api/json
        ctx.out_protocol = HtmlCloth()
        ctx.outprot_ctx = ctx.out_protocol.get_context(ctx, ctx.transport)

        fortunes = ctx.udc.session.query(Fortune).all()
        fortunes.append(
            Fortune(id=0,
                    message=u"Additional fortune added at request time."))

        fortunes.sort(key=lambda x: x.message)

        return fortunes

    @rpc(NumQueriesType, _returns=Array(World))
    def updates(ctx, queries):
        """Test 5: Database Updates"""

        if queries is None:
            queries = 1

        retval = []
        q = ctx.udc.session.query(World)
        for id in (randint(1, 10000) for _ in xrange(queries)):
            world = q.get(id)
            world.randomNumber = randint(1, 10000)
            retval.append(world)

        ctx.udc.session.commit()

        return retval
Example #6
0
class HelloWorldService(ServiceBase):
    @rpc(Unicode, Integer, _returns=Iterable(Unicode))
    def say_hello(self, name, times):
        for i in range(times):
            yield "Hello %s, It's the %s time to meet you." % (name, i + 1)

    @rpc(Unicode, Integer, _returns=Iterable(Unicode))
    def say_hello(self, name, times):
        for i in times:
            yield 'Hello, %s' % name

        # if re.match(r'^[0-9a-zA-Z_]{0,19}@[0-9a-zA-Z]{1,13}\.[com,cn,net]{1,3}$', _url):
        #     return "Y"
        # else:

    #       return "N"

    @rpc(Array(Person), _returns=Iterable(Unicode))
    def say_hello_1(self, persons):
        print('-------say_hello_1()--------')
        if not persons:
            yield 'None'
        for person in persons:
            print('name is : %s, age is %s.' % (person.name, person.age))
            yield 'name is : %s, age is %s.' % (person.name, person.age)
Example #7
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 #8
0
class SomeSoapService(spyne.Service):
    __service_url_path__ = '/soap/someservice'
    __in_protocol__ = Soap11()
    __out_protocol__ = Soap11()
    __tns__ = 'http://127.0.0.1/'

    @spyne.srpc(
        Array(Person),  # 请求类型
        _returns=Iterable(Unicode),  # 返回类型
        _in_variable_names={'data': 'param'},  # 请求节点名,默认为函数定义,修改为param
        _out_variable_name='return')  # 返回节点名
    def person(self, data):
        if not data:
            yield 'None'
        for person in data:
            yield 'name is : %s, age is %s.' % (person.name, person.age)

    @spyne.srpc(Integer, _returns=Integer, _out_variable_name='return')
    def block(ctx, seconds):
        print(1)
        return '1'

    __aux__ = ThreadAuxProc(pool_size=1)

    @spyne.srpc(Integer)
    def block(ctx, seconds):
        print(2)
Example #9
0
class IRService(ServiceBase):
    """Image recognition service."""
    @rpc(Unicode, Unicode, _returns=Array(Unicode))
    def predict(ctx, image_file, device):
        """Classify an image."""
        ctx.udc.create_graph()
        return ctx.udc.predict(image_file, device)
Example #10
0
class InteropBare(ServiceBase):
    @srpc(String, _returns=String, _body_style='bare')
    def echo_simple_bare(ss):
        return ss

    @srpc(Array(String), _returns=Array(String), _body_style='bare')
    def echo_complex_bare(ss):
        return ss

    @srpc(_returns=String, _body_style='bare')
    def empty_input_bare():
        return "empty"

    @srpc(String, _body_style='bare')
    def empty_output_bare(ss):
        assert ss is not None
Example #11
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)

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

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

        peeps2 = XmlDocument().from_element(None, arr, element)
        for peep in peeps2:
            self.assertEquals(27, peep.age)
            self.assertEquals(25, len(peep.addresses))
            self.assertEquals('funkytown', peep.addresses[18].city)
Example #12
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 #13
0
class Reco_Equipment (ComplexModel):
    equiName = String
    area = Img_Rectangle
    acreage = int
    state = Unicode
    score = Unicode
    children = Array(Reco_Equipment_child)
Example #14
0
class HelloWorldService2(ServiceBase):
    @rpc(Array(String), _returns=Iterable(Unicode))
    def say_hello_plus2(self, name_plus):
        if not name_plus:
            yield 'None'

        for name in name_plus:
            yield name
Example #15
0
class HelloWorldService(ServiceBase):
    @rpc(_returns=Array(Permission))
    def simple(ctx):
        return v

    @rpc(_returns=Permission.customize(max_occurs=float('inf')))
    def complex(ctx):
        return v
Example #16
0
class User(ComplexModel):
    __namespace__ = "user"

    userid = Integer
    username = String
    firstname = String
    lastname = String
    permissions = Array(Permission)
Example #17
0
class RestApiWrapperService(Service):
    @rpc(Unicode, String, Array(feature, min_occurs=1), _returns=response)
    def makeDecision(ctx, id, entity, features):
        api_data = {f.name: f.value for f in features}
        adjusted_prediction = DecisionEngine().makeDecision(api_data, entity)

        resp = response(identifier=id, decision=adjusted_prediction.iloc[0])
        return resp
Example #18
0
class HelloWorldService2(ServiceBase):
    @rpc(Array(String), _returns=Iterable(Unicode))
    def say_hello_2(self, persons):
        if not persons:
            yield 'None'

        for person in persons:
            yield person
Example #19
0
class ExtListScreen(ScreenBase):
    main = Array(
        Extensions.customize(
            child_attrs_all=dict(exc=False, ),
            child_attrs=dict(id=dict(prot=HrefWidget("/get_ext?id={}")),
                             **EXTENSION_CUST),
        ),
        prot=HtmlColumnTable(before_table=_write_new_ext_link),
    )
Example #20
0
    def test_cust_array_again(self):
        A = Array(Unicode)

        A = A.customize(foo='bar')

        assert A.Attributes.foo == 'bar'
        assert A.__orig__ is Array
        assert A.__extends__ is None
        assert issubclass(A, Array)
class HelloWorldService(ServiceBase):
    @rpc(Unicode, Integer, _returns=Array(Unicode))
    def say_hello(self, name, times):
        results = []
        for i in range(0, times):
            results.append('Hello {0}'.format(name))
        return results

    @rpc(Project, _returns=Unicode)
    def make_project(self, pro):
        return '{0}+{1}'.format(pro.name, pro.version)

    @rpc(Array(Project), _returns=Iterable(Unicode))
    def show_project(self, pros):
        if not pros:
            yield 'None'
        for pro in pros:
            yield pro.name + pro.version
Example #22
0
    def test_simple_array(self):
        v = range(5)
        elt = _test_type(Array(Integer), v)[0]

        assert elt.xpath('table/tbody/tr/td/div/input/@value') == \
                                                       ['0', '1', '2', '3', '4']
        assert elt.xpath('table/tbody/tr/td/button/text()') == ['-'] * 5 + ['+']
        for i, name in enumerate(elt.xpath('div/div/input/@name')):
            assert re.match(r'ints\[0*%d\]' % i, name)
Example #23
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')
class ApiWrapperService(Service):

    # noinspection PyMethodParameters
    @rpc(Unicode, Array(feature, min_occurs=1), Unicode, _returns=response)
    def makeDecision(ctx, id, features, entity):
        api_data = {f.name: f.value for f in features}
        adjusted_prediction = DecisionEngine().makeDecision(api_data, entity)

        resp = response(identifier=id, decision=adjusted_prediction.iloc[0])
        return resp
Example #25
0
    def test_cust_array_serializer(self):
        A = Array(Unicode)

        A = A.customize(serializer_attrs=dict(max_len=10, ), )

        serializer, = A._type_info.values()

        assert serializer.Attributes.max_len == 10
        assert serializer.__orig__ is Unicode
        assert issubclass(serializer, Unicode)
Example #26
0
class User(TableModel):
    __tablename__ = 'user'
    __namespace__ = 'spyne.examples.user_manager'
    __table_args__ = {"sqlite_autoincrement": True}

    id = UnsignedInteger32(pk=True)
    email = Unicode(64, pattern=r'[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}')
    user_name = Unicode(32, min_len=4, pattern='[a-z0-9.]+')
    full_name = Unicode(64, pattern='\w+( \w+)+')
    permissions = Array(Permission).store_as('table')
Example #27
0
class SipBuddyListScreen(ScreenBase):
    main = Array(
        SipBuddy.customize(
            child_attrs_all=dict(exc=True,),
            child_attrs=dict(
                id=dict(prot=HrefWidget("/get_sip_buddy?id={}")),
            **SIP_BUDDY_CUST
            ),
        ),
        prot=HtmlColumnTable(before_table=_write_new_sip_buddy_link),
    )
Example #28
0
class Org(ComplexModel):
    Address = Unicode
    BrregOrgNo = Unicode
    City = Unicode
    County = Unicode
    CountyId = Integer
    Email = Unicode
    Id = Integer
    Name = Unicode
    NameDescr = Unicode
    OrgType = Unicode
    OrgTypeId = Integer
    Url = Unicode
    Zip = Unicode
    _down = Array(Integer)
    _up = Array(Integer)
    _updated = DateTime
    _created = DateTime
    _etag = Unicode
    _id = Unicode
Example #29
0
class WebAPIService(ServiceBase):
    @rpc(Unicode, Integer, _returns=Iterable(Unicode))
    def say_hello(self, name, times):
        for i in range(times):
            yield "Hello %s, It's the %s time to meet you." % (name, i + 1)

    @rpc(Array(Person), Unicode, Unicode, _returns=Iterable(Unicode))
    def notify(self, persons, username, password):
        for person in persons:
            yield "name: %s, age: %s, %s, %s notify success" % (
                person.name, person.age, username, password)
Example #30
0
class InteropClass(ServiceBase):
    @srpc(SimpleClass, _returns=SimpleClass)
    def echo_simple_class(sc):
        return sc

    @srpc(Array(SimpleClass), _returns=Array(SimpleClass))
    def echo_simple_class_array(sca):
        return sca

    @srpc(NestedClass, _returns=NestedClass)
    def echo_nested_class(nc):
        return nc

    @srpc(Array(NestedClass), _returns=Array(NestedClass))
    def echo_nested_class_array(nca):
        return nca

    @srpc(ExtensionClass, _returns=ExtensionClass)
    def echo_extension_class(nc):
        return nc

    @srpc(ClassWithSelfReference, _returns=ClassWithSelfReference)
    def echo_class_with_self_reference(sr):
        return sr

    @srpc(Attachment, _returns=Attachment)
    def echo_attachment(a):
        assert isinstance(a, Attachment)
        return a

    @srpc(Array(Attachment), _returns=Array(Attachment))
    def echo_attachment_array(aa):
        return aa