class Country(TableModel): __tablename__ = 'cc_country' id = Integer64(primary_key=True) countrycode = Unicode(1) countryname = Unicode(1) countryprefix = Unicode(1)
class HelloWorldService(ServiceBase): @rpc(Unicode(default='World'), UnsignedInteger(default=5), _returns=Iterable(Unicode)) def say_hello(ctx, name, times): # workaround for Python2's lacking of nonlocal times = [times] def _cb(push): # This callback is called immediately after the function returns. if times[0] > 0: times[0] -= 1 data = u'Hello, %s' % name print data # The object passed to the append() method is immediately # serialized to bytes and pushed to the response stream's # file-like object. push.append(data) # When a push-callback returns anything other than a deferred, # the response gets closed. return deferLater(reactor, 1, _cb, push) # This is Spyne's way of returning NOT_DONE_YET return Iterable.Push(_cb) @rpc(Unicode(default='World'), _returns=Iterable(Unicode)) def say_hello_forever(ctx, name): def _cb(push): push.append(u'Hello, %s' % name) return deferLater(reactor, 0.1, _cb, push) return Iterable.Push(_cb)
class Iso639(TableModel): __tablename__ = 'cc_iso639' charset = Unicode(1) code = Unicode(1, primary_key=True) lname = Unicode(1) name = Unicode(1, unique=True)
class Backup(TableModel): __tablename__ = 'cc_backup' creationdate = Date id = Integer64(primary_key=True) name = Unicode(1, unique=True) path = Unicode(1)
class NameType(ComplexModel): """Type of name. Possible values for attribute 'name' are implementation dependent but standard profiles may specify types. An enterprise may have multiple IT systems each having its own local name for the same object, e.g. a planning system may have different names from an EMS. An object may also have different names within the same IT system, e.g. localName as defined in CIM version 14. The definition from CIM14 is:The localName is a human readable name of the object. It is a free text name local to a node in a naming hierarchy similar to a file directory structure. A power system related naming hierarchy may be: Substation, VoltageLevel, Equipment etc. Children of the same parent in such a hierarchy have names that typically are unique among them.""" member_data_items_ = [('description', Unicode.customize(max_occurs=1, min_occurs=0)), ('name', Unicode.customize(max_occurs=1, min_occurs=1)), ('NameTypeAuthority', NameTypeAuthority.customize(max_occurs=1, min_occurs=0))] def __init__(self, description=None, name=None, nameTypeAuthority=None, **kwargs): super().__init__(description=description, name=name, NameTypeAuthority=nameTypeAuthority, **kwargs) self.description = description self.name = name self.nameTypeAuthority = nameTypeAuthority
class Status(ComplexModel): """Current status information relevant to an entity.""" _type_info = [ ('dateTime', DateTime.customize(max_occurs=1, min_occurs=0)), ('reason', Unicode.customize(max_occurs=1, min_occurs=0)), ('remark', Unicode.customize(max_occurs=1, min_occurs=0)), ('value', Unicode.customize(max_occurs=1, min_occurs=0)), ] def __init__(self, dateTime=None, reason=None, remark=None, value=None, **kwargs): super().__init__(dateTime=dateTime, reason=reason, remark=remark, value=value, **kwargs) if isinstance(dateTime, str): initvalue_ = datetime_.datetime.strptime(dateTime, '%Y-%m-%dT%H:%M:%S') else: initvalue_ = dateTime self.dateTime = initvalue_ self.reason = reason self.remark = remark self.value = value
class Support(TableModel): __tablename__ = 'cc_support' id = Integer32(primary_key=True) email = Unicode(1) language = Unicode(1) name = Unicode(1)
class StockService(Service): @rpc(Unicode(encoding='utf-8'), Float(ge=0.0), _in_header=(AuthHeader,), _operation_name='CreateStock', _returns=String) def create_stock(ctx, StockName, StockPrice): user_name = ctx.in_header.UserName token = ctx.in_header.Token if all([user_name, token]): result = handlers.create_stock(user_name, token, StockName, StockPrice) if result['result']: return result['message'] raise Fault(result['side'], result['message']) raise Fault('Client', 'Нет прав доступа') @rpc(Unicode(encoding='utf-8'), _operation_name='GetStockPrice', _returns=Float) def get_stock_price(ctx, StockName): result = handlers.get_stock_price(StockName) if result['result']: return result['message'] raise Fault(result['side'], result['message']) @rpc(Unicode(encoding='utf-8'), Float(ge=0.0), _in_header=(AuthHeader,), _operation_name='SetStockPrice', _returns=Integer) def set_stock_price(ctx, StockName, Price): user_name = ctx.in_header.UserName token = ctx.in_header.Token if all([user_name, token]): result = handlers.set_stock_price(user_name, token, StockName, Price) if result['result']: return result['message'] raise Fault(result['side'], result['message']) raise Fault('Client', 'Нет прав доступа.')
class Campaign(TableModel): __tablename__ = 'cc_campaign' id = Integer64(primary_key=True) creationdate = Date daily_start_time = Time daily_stop_time = Time description = Unicode expirationdate = Date forward_number = Unicode(1) frequency = Integer32 friday = Integer32 id_campaign_config = Integer32 id_card = Integer64 id_cid_group = Integer32 monday = Integer32 name = Unicode(1, unique=True) nb_callmade = Integer32 saturday = Integer32 secondusedreal = Integer32 startingdate = Date status = Integer32 sunday = Integer32 thursday = Integer32 tuesday = Integer32 wednesday = Integer32
class Timezone(TableModel): __tablename__ = 'cc_timezone' id = Integer32(primary_key=True) gmtoffset = Integer64 gmttime = Unicode(1) gmtzone = Unicode(1)
def create_parameters_model(self): type_info = ( ('checkedOutId', Unicode.customize()), ('checkedOutBy', Unicode.customize(min_occurs=0)), ) parameters_model = complex_model_factory('Parameters-zs-dms-r', ZDS_XML_NS, type_info) return parameters_model
def test_unicode_values(self): v = "a" cls = Unicode(100, type_name="tn", values=list("abcd")) assert not cls.get_type_name() is Unicode.Empty elt = _test_type(cls, v).xpath("div/select")[0] assert elt.tag == "select" assert elt.xpath("option/@value") == [""] + list("abcd") assert elt.xpath("option[@selected]/text()") == [v]
def test_unicode_values(self): v = 'a' cls = Unicode(100, type_name="tn", values=list('abcd')) assert not cls.get_type_name() is Unicode.Empty elt = _test_type(cls, v).xpath('div/select')[0] assert elt.tag == 'select' assert elt.xpath("option/@value") == [''] + list('abcd') assert elt.xpath("option[@selected]/text()") == [v]
class Permission(TableModel): __tablename__ = 'permission' __namespace__ = 'spyne.examples.user_manager' __table_args__ = {"sqlite_autoincrement": True} id = UnsignedInteger32(pk=True) application = Unicode(values=('usermgr', 'accountmgr')) operation = Unicode(values=('read', 'modify', 'delete'))
class Permission(TableModel): __tablename__ = 'permission' __namespace__ = 'spyne.examples.sql_crud' __table_args__ = {"sqlite_autoincrement": True} id = UnsignedInteger32(primary_key=True) application = Unicode(256) operation = Unicode(256)
class CampaignConfig(TableModel): __tablename__ = 'cc_campaign_config' id = Integer32(primary_key=True) context = Unicode(1) description = Unicode flatrate = Decimal name = Unicode(1)
class Callerid(TableModel): __tablename__ = 'cc_callerid' id = Integer64(primary_key=True) # id_cc_card = Integer64 cc_card = Card.store_as(table(left='id_cc_card')) activated = Unicode(1, default='t') cid = Unicode(1, unique=True)
class SomeObject(ComplexModel): _type_info = [ ('i0', Integer), ('s0', Unicode), ('i1', Integer(fieldset=fset_one)), ('s1', Unicode(fieldset=fset_one)), ('i2', Integer(fieldset=fset_two)), ('s2', Unicode(fieldset=fset_two)), ]
class SubscriptionSignup(TableModel): __tablename__ = 'cc_subscription_signup' description = Unicode(1) enable = Integer32 id = Integer64(primary_key=True) id_callplan = Integer64 id_subscription = Integer64 label = Unicode(1)
class Speeddial(TableModel): __tablename__ = 'cc_speeddial' creationdate = Date id = Integer64(primary_key=True) id_cc_card = Integer64 name = Unicode(1) phone = Unicode(1) speeddial = Integer32
def create_object_model(self): type_info = ( ('identificatie', Unicode.customize(sub_ns=self.stuf_zkn_ns)), ('functie', XmlAttribute(Unicode.customize(sub_ns=self.stuf_ns), ns='http://www.egem.nl/StUF/StUF0301')), ('entiteittype', XmlAttribute(Unicode.customize(sub_ns=self.stuf_ns, ns='http://www.egem.nl/StUF/StUF0301'))), ) object_model = complex_model_factory( '{}_{}'.format(self.entiteittype, self.shortname), self.stuf_zkn_ns, type_info) return object_model
class User(TableModel): __tablename__ = 'user' id = Integer64(primary_key=True) active = Integer32 admin = Integer32 email = Unicode(1, unique=True) password = Unicode(1) username = Unicode(1, unique=True)
class Extensions(TableModel): __tablename__ = 'cc_extension' id = Integer32(primary_key=True) context = Unicode(64, default='home') exten = Unicode(20, default='') priority = Unicode(4, default='0') app = Unicode(20, default='Dial') appdata = Unicode(128, default='')
class Currencies(TableModel): __tablename__ = 'cc_currencies' id = Integer32(primary_key=True) basecurrency = Unicode(1) currency = Unicode(1, unique=True) lastupdate = Date name = Unicode(1) value = Decimal
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')
class ServerManager(TableModel): __tablename__ = 'cc_server_manager' id = Integer64(primary_key=True) id_group = Integer32 lasttime_used = Date manager_host = Unicode(1) manager_secret = Unicode(1) manager_username = Unicode(1) server_ip = Unicode(1)
def create_parameters_model(self): type_info = (('checkedOutId', Unicode.customize(type_name='checkedOutId')), ('versioningState', Unicode.customize(type_name='versioningState', min_occurs=0))) parameters_model = complex_model_factory( '{}_Parameters_{}'.format(self.berichtcode, self.shortname), self.stuf_zds_ns, type_info) return parameters_model
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 Notification(TableModel): __tablename__ = 'cc_notification' date = Date from_ = Integer64(db_column='from_id') from_type = Integer32 id = Integer64(primary_key=True) key_value = Unicode(1) link = Integer64(db_column='link_id') link_type = Unicode(1) priority = Integer32
class Invoice(TableModel): __tablename__ = 'cc_invoice' date = Date description = Unicode id = Integer64(primary_key=True) id_card = Integer64 paid_status = Integer32 reference = Unicode(1, unique=True) status = Integer32 title = Unicode(1)
class Phonenumber(TableModel): __tablename__ = 'cc_phonenumber' amount = Integer32 creationdate = Date id = Integer64(primary_key=True) id_phonebook = Integer32 info = Unicode name = Unicode(1) number = Unicode(1) status = Integer32
def create_stuurgegevens_model(self): type_info = ( ('berichtcode', Unicode.customize(sub_ns=STUF_XML_NS, pattern=self.berichtcode)), ) stuurgegevens_model = complex_model_factory('{}_Stuurgegevens_{}'.format( self.berichtcode, self.shortname), STUF_XML_NS, type_info) return stuurgegevens_model
def create_parameters_model(self): # See StUF 3.01 Tabel 5.2, only mutatiesoort should be part of the parameters. mutatiesoort = 'W' if self.update else 'T' type_info = ( ('mutatiesoort', Unicode.customize(sub_ns=STUF_XML_NS, fixed=mutatiesoort, min_occurs=1, max_occurs=1, nillable=False)), ) parameters_model = self.create_reusable_model(self.create_parameters_name(), STUF_XML_NS, type_info) return parameters_model
def create_parameters_model(self): type_info = ( ('checkedOutId', Unicode.customize(type_name='checkedOutId')), # ('versioningState', Unicode.customize(type_name='versioningState', min_occurs=0)) ) parameters_model = complex_model_factory('{}_Parameters_{}'.format( self.berichtcode, self.shortname), ZDS_XML_NS, type_info) return parameters_model
def create_document_model(self): type_info = ( ('identificatie', Unicode.customize(min_occurs=1, max_occurs=1, nillable=False)), ('functie', functie), ('entiteittype', entiteittype), ('verwerkingssoort', verwerkingssoort) ) document_model = complex_model_factory('EDC_cc_e', ZKN_XML_NS, type_info) return document_model
def create_parameters_model(self): # See StUF 3.01 Tabel 5.2 mutatiesoort = 'W' if self.update else 'T' type_info = ( ('mutatiesoort', Unicode.customize(sub_ns=STUF_XML_NS, fixed=mutatiesoort, min_occurs=1, max_occurs=1, nillable=False)), ('indicatorOvername', IndicatorOvername.customize(min_occurs=1, max_occurs=1, nillable=False)), ) parameters_model = self.create_reusable_model(self.create_parameters_name(), STUF_XML_NS, type_info) return parameters_model
def create_stuurgegevens_model(self): type_info = ( ('berichtcode', Unicode.customize(type_name='BerichtcodeDi02', sub_ns=self.stuf_ns, pattern=self.berichtcode)), # sub_ns=self.stuf_ns ('zender', Systeem), ('ontvanger', Systeem), ('referentienummer', simple_types.Refnummer.customize(min_occurs=0)), ('tijdstipBericht', simple_types.Tijdstip.customize(min_occurs=0)), ('functie', simple_types.Functie), ) stuurgegevens_model = complex_model_factory('{}_Stuurgegevens_{}'.format( self.berichtcode, self.shortname), self.stuf_ns, type_info) return stuurgegevens_model
def create_stuurgegevens_model(self): BerichtCode = Unicode.customize(type_name='BerichtcodeLk01', sub_ns=STUF_XML_NS, fixed=self.berichtcode, min_occurs=1, max_occurs=1, nillable=False) type_info = ( ('berichtcode', BerichtCode.customize(min_occurs=1, max_occurs=1, nillable=False)), ('zender', Systeem.customize(min_occurs=1, max_occurs=1, nillable=False)), ('ontvanger', Systeem.customize(min_occurs=1, max_occurs=1, nillable=False)), ('referentienummer', simple_types.Refnummer), ('tijdstipBericht', simple_types.Tijdstip), ('entiteittype', simple_types.Entiteittype.customize(fixed=self.stuf_entiteit.get_mnemonic(), nillable=False, min_occurs=1, max_occurs=1)), ) name = self.create_stuurgegevens_name() return self.create_reusable_model(name, STUF_XML_NS, type_info)
def create_stuurgegevens_model(self): type_info = ( ('berichtcode', Unicode.customize(type_name='BerichtcodeLv01', fixed=BerichtcodeChoices.lv01, min_occurs=1, nillable=False)), ('zender', Systeem.customize(min_occurs=0, nillable=False)), ('ontvanger', Systeem.customize(min_occurs=0, nillable=False)), ('referentienummer', simple_types.Refnummer.customize(min_occurs=0, nillable=False)), ('tijdstipBericht', simple_types.Tijdstip.customize(min_occurs=0, nillable=False)), # Technically: EntiteittypeBSL, EntiteittypeZAK, EntiteittypeEDC ('entiteittype', simple_types.Entiteittype.customize(fixed=self.stuf_entiteit.get_mnemonic(), min_occurs=1, nillable=False)), ) stuurgegevens_model = self.create_reusable_model(self.create_stuurgegevens_name(), STUF_XML_NS, type_info).customize(min_occurs=1, nillable=False) return stuurgegevens_model
def create_stuurgegevens_model(self): type_info = [ ('berichtcode', Unicode.customize(type_name='BerichtcodeLa01')), ('zender', Systeem.customize(min_occurs=0)), ('ontvanger', Systeem.customize(min_occurs=0)), ('referentienummer', simple_types.Refnummer.customize(min_occurs=0)), ('tijdstipBericht', simple_types.Tijdstip.customize(min_occurs=0)), ('crossRefnummer', simple_types.Refnummer.customize(min_occurs=0)), # Technically: EntiteittypeBSL, EntiteittypeZAK, EntiteittypeEDC ('entiteittype', simple_types.Entiteittype), ] stuurgegevens_model = self.create_reusable_model(self.create_stuurgegevens_name(), STUF_XML_NS, type_info) return stuurgegevens_model
from spyne import Unicode from spyne.model.complex import XmlAttribute from ...utils.stuf_datetime import IndicatieOnvolledigeDatum from ..stuf.choices import ScopeChoices from .constants import STUF_XML_NS, XMIME_XML_NS from .simple_types import Entiteittype, Exact, Functie Bestandsnaam = Unicode.customize(__namespace__=STUF_XML_NS, type_name='Bestandsnaam', max_len=255) ContentType = Unicode.customize(__namespace__=XMIME_XML_NS, type_name='ContentType', min_len=3) # J = de datum heeft een waarde maar jaar, maand en dag zijn onbekend # M = de datum heeft een waarde maar maand en dag zijn onbekend # D = de datum heeft een waarde maar de dag is onbekend # V = datum is volledig IndOnvolledigeDatum = Unicode.customize(__namespace__=STUF_XML_NS, type_name='IndOnvolledigeDatum', values=set(IndicatieOnvolledigeDatum.values.keys()), default='V') NoValue = Unicode.customize(__namespace__=STUF_XML_NS, type_name='NoValue', values={'nietOndersteund', 'nietGeautoriseerd', 'geenWaarde', 'waardeOnbekend', 'vastgesteldOnbekend'}) Scope__Anonymous = Unicode.customize(__namespace__=STUF_XML_NS, values=set(ScopeChoices.values.keys())) # T = Toevoeging # W = Wijziging of correctie # V = Verwijdering # E = Een relatie entiteit wordt beeindigd. # I = Entiteit bevat alleen identificerende gegevens. # R = Een relatie entiteit wordt vervangen door een nieuwe relatie entiteit. # S = De sleutel van een entiteit wordt gewijzigd. # O = Het object in de oude entiteit wordt in het kader van een ontdubbeling samengevoegd met het object in de
from lxml import etree from spyne import Unicode from spyne.model.complex import TypeInfo from spyne.util.django import DEFAULT_FIELD_MAP as _DEFAULT_FIELD_MAP from ...utils import stuf_datetime from ...utils.fields import GMLField from .models import DatumMetIndicator, TijdstipMetIndicator from .simple_types import GeometrieIMGeo_e DEFAULT_FIELD_MAP = dict(_DEFAULT_FIELD_MAP) DEFAULT_FIELD_MAP['StUFDateField'] = DatumMetIndicator DEFAULT_FIELD_MAP['StUFDateTimeField'] = TijdstipMetIndicator DEFAULT_FIELD_MAP['GMLField'] = GeometrieIMGeo_e DEFAULT_FIELD_MAP['ArrayField'] = Unicode.customize(max_occurs=Decimal('inf')) def get_model_value(obj, field_name): """ Returns the value belonging to `field_name` on `Model` instance. This works for related fields. Example:: >>> get_model_value(Zaak, 'zaaktype__zaaktypeomschrijving') 'Some description' """ fields = field_name.split(LOOKUP_SEP) for field in fields:
import logging logging.basicConfig(level=logging.DEBUG) from spyne import Application, rpc, ServiceBase, \ Integer, Unicode from spyne import Iterable from spyne.protocol.soap import Soap11 from spyne.server.wsgi import WsgiApplication EmailString = Unicode.customize( max_length=128, pattern='[^@]+@[^@]+', type_name='EmailString', ) class EmailValidation(ServiceBase): @rpc(Unicode, EmailString, _returns=Unicode) def validate_email(ctx, username, email): return 'That is %s and %s' % (username, email) class HelloWorldService(ServiceBase): @rpc(Unicode, Integer, _returns=Iterable(Unicode)) def say_hello(ctx, name, times): for i in range(times): yield 'Hello, %s' % name application = Application([HelloWorldService, EmailValidation], tns='spyne.examples.hello', in_protocol=Soap11(), out_protocol=Soap11() ) if __name__ == '__main__':
def test_new_type(self): """Customized primitives go into namespace based on module name.""" custom_type = Unicode(pattern='123') self.assertEqual(custom_type.get_namespace(), custom_type.__module__)
def test_simple_type_explicit_customization(self): assert Unicode(max_len=5).__extends__ is not None assert Unicode.customize(max_len=5).__extends__ is not None