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) serializer = Array(Person) element = serializer.to_xml(peeps) self.assertEquals(4, len(element.getchildren())) peeps2 = serializer.from_xml(element) for peep in peeps2: self.assertEquals(27, peep.age) self.assertEquals(25, len(peep.addresses)) self.assertEquals('funkytown', peep.addresses[18].city)
def test_array(self): serializer = Array(String) values = ['a', 'b', 'c', 'd', 'e', 'f'] element = serializer.to_xml(values) self.assertEquals(len(values), len(element.getchildren())) values2 = serializer.from_xml(element) self.assertEquals(values[3], values2[3])
class HelloWorldService(SimpleWSGISoapApp): maxIntegerSize = 5000 # adjust to your taste @soapmethod(String, Integer, _returns=Array(String)) def say_hello(self, name, times): results = [] for i in range(0, times): results.append('Hello, %s' % name) return results @soapmethod(SOAPRequest, _returns=Array(ReturnObject)) def get_integers(self, req): if req == None: raise Exception('invalid request: request object is null') else: if req.startrow < 0: raise Exception('invalid request: startrow < 0') print req.startrow print req.endrow retval = [] for i in range(req.startrow, req.startrow + 50): retelt = ReturnObject() retelt.byone = i retelt.bytwo = i * 2 retelt.bythree = i * 3 retelt.byfour = i * 4 retelt.byfive = i * 5 retval.append(retelt) return retval @soapmethod(_returns=Integer) def get_integers_count(self): return self.maxIntegerSize @soapmethod(_returns=String) def name(self): return self.__class__.__name__ @soapmethod(NestedObject, _returns=NestedObject) def get_nested(self, complex): retval = NestedObject() retval.date_time = datetime.now() retval.ro = ReturnObject() i = 5 retval.ro.byone = i retval.ro.bytwo = i * 2 retval.ro.bythree = i * 3 retval.ro.byfour = i * 4 retval.ro.byfive = i * 5 retval.arr = ['asd097n09a', 'askdj0n3t'] return retval
def test_array_empty(self): serializer = Array(String) serializer.resolve_namespace("zbank") values = [] element = serializer.to_xml(values, ns_test) self.assertEquals(len(values), len(element.getchildren())) values2 = serializer.from_xml(element) self.assertEquals(len(values2), 0)
class types: name = String pathway = String length = Integer pseudo_count = Float sites = Integer factors = Array(String)
class HelloWorldService(SimpleWSGISoapApp): @soapmethod(String, Integer, _returns=Array(String)) def say_hello(self, name, times): results = [] raise Exception("this is some crazy crap") for i in range(0, times): results.append('Hello, %s' % name) return results def onCall(self, environ): request.additional['call_start'] = time() def onMethodExec(self, environ, body, py_params, soap_params): request.additional['method_start'] = time() def onResults(self, environ, py_results, soap_results): request.additional['method_end'] = time() def onReturn(self, environ, returnString): call_start = request.additional['call_start'] call_end = time() method_start = request.additional['method_start'] method_end = request.additional['method_end'] print 'Method took [%s] - total execution time[%s]' % ( method_end - method_start, call_end - call_start)
class HelloWorldService(SimpleWSGISoapApp): @soapmethod(Attachment, Integer, _returns=Array(String), _mtom=True) def say_hello(self, name, times): results = [] for i in range(0, times): results.append('Hello, %s' % name.data) return results
class UserManager(SimpleWSGISoapApp): @soapmethod(User, _returns=Integer) def add_user(self, user): global user_database global userid_seq user.userid = userid_seq userid_seq = userid_seq + 1 user_database[user.userid] = user return user.userid @soapmethod(Integer, _returns=User) def get_user(self, userid): global user_database return user_database[userid] @soapmethod(User) def modify_user(self, user): global user_database user_database[user.userid] = user @soapmethod(Integer) def delete_user(self, userid): global user_database del user_database[userid] @soapmethod(_returns=Array(User)) def list_users(self): global user_database return [v for k, v in user_database.items()]
def extract_complex(self, element, parent=None, inuse=False): """ Create an complex object based on the supplied element. The resulting object is stored in ctypes and returned if created. parent - if supplied the parent object can be used to create a class, this is used for inline complextypes which are unnamed. The resulting class is created as <nameofparentelement>+CT. inuse - if inuse is True the extracted type is flagged as used by another type types that are not used e.g. messages are not marked and are not written out by the typeparser. This prevents add_userResponse being created as a ClassSerializer. """ #if element.tag == ccontent: # typelist = [] # for child in element.getchildren(): # typelist += self.extract_complex(child, inuse=True) # return typelist #print 'complexType', element, element.get('name'), parent if element.tag == ctype: name = element.get('name') if name is None: name = parent.get('name') + 'CT' klass = self.get_class(name, inuse=inuse) #attempt to detect a nested array type here #and tag it as an array, we can then later replace the #types with their array types in a second parse try: children = element.xpath('./xs:sequence/xs:element', namespaces={'xs': schnamespace}) children.extend( element.xpath('./xs:choice/xs:element', namespaces={'xs': schnamespace})) if len(children) == 1 and ( children[0].get('maxOccurs') == 'unbounded' or children[0].get('maxOccurs') > 0): child = children[0] typelist = self.extract_complex(child, inuse=True) #items in a soaplib Array are named according to their datatype, #if this isn't the case we're just have a Repeating wrapped in #a class so don't tag childtype = typelist.pop() if childtype[0] == childtype[1].serializer.get_datatype(): #we have an array so tag it for repointing after we've finished parsing. klass.arraytag = (childtype[0], Array(childtype[1].serializer)) except Exception, e: print e typelist = [] for child in element.getchildren(): typelist += self.extract_complex(child, inuse=True) for (typename, typevalue) in typelist: setattr(klass.types, typename, typevalue) #reassign metaclass: as dynamically building the class #means the metaclass code is run before the types have #been set so we re-call it here. ClassSerializerMeta.__init__(klass, name, ClassSerializer, {}) return [(None, klass)]
class types: ID = Integer name = NewString directoryID = Integer active = Boolean conception = DateTime description = NewString lastModified = DateTime attributes = Array(SOAPAttribute)
def test_class_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 peeps.append(a) serializer = Array(Person) element = serializer.to_xml(peeps) self.assertEquals(4, len(element.getchildren())) peeps2 = serializer.from_xml(element) for i in range(0, 4): self.assertEquals(peeps[i].name, names[i]) self.assertEquals(peeps[i].birthdate, datetime.datetime(1979, 1, 1))
class HelloWorldService(SimpleWSGISoapApp): @soapmethod(String, Integer, _returns=Array(String)) def say_hello(self, name, times): ''' Docstrings for service methods appear as documentation in the wsdl <b>what fun</b> @param name the name to say hello to @param the number of times to say hello @return the completed array ''' results = [] for i in range(0, times): results.append('Hello, %s' % name) return results
class DebexpoService(SimpleWSGISoapApp): def _get_packages(self, package_filter=None, package_version_filter=None, email=None): """ Helper method to construct the list for package information. """ pkg_ctl = PackagesController() if email is not None: user = pkg_ctl._get_user(email) if user is None: log.error('Could not find user; returning empty list') return [] package_filter = (Package.user_id == user.id) packages = pkg_ctl._get_packages( package_filter=package_filter, package_version_filter=package_version_filter) out = [] for item in packages: out.append([ item.name, item.package_versions[-1].version, '%s <%s>' % (item.user.name, item.user.email), item.description, config['debexpo.server'] + url('package', packagename=item.name) ]) return out @soapmethod(String, _returns=Array(Array(String))) def uploader(self, email): """ Return package list filtered on uploader. """ log.debug('Getting packages filtered on uploader = %s' % email) return self._get_packages(email=email) @soapmethod(String, _returns=Array(Array(String))) def section(self, section): """ Return package list filtered on section. """ log.debug('Getting packages filtered on section = %s' % section) return self._get_packages( package_version_filter=(PackageVersion.section == section)) @soapmethod(String, _returns=Array(Array(String))) def maintainer(self, email): """ Return package list filtered on maintainer. """ log.debug('Getting packages filtered on maintainer = %s' % email) return self._get_packages( package_version_filter=(PackageVersion.maintainer == email)) @soapmethod(_returns=Array(Array(String))) def packages(self): """ Return package list. """ log.debug('Getting package list') return self._get_packages() @soapmethod(String, String, _returns=Array(String)) def package(self, name, version): """ Return details a specific package and version. """ q = meta.session.query(Package).filter_by(name=name) q = q.filter(Package.id == PackageVersion.package_id) q = q.filter(PackageVersion.version == version) package = q.first() if package is None: return [] r = meta.session.query(PackageVersion).filter_by(version=version) r = r.filter(PackageVersion.package_id == Package.id) r = r.filter(Package.name == name) package_version = r.first() if package_version is None: return [] return [ package.name, '%s <%s>' % (package.user.name, package.user.email), package.description, str(package.needs_sponsor), package_version.version, package_version.section, package_version.distribution, package_version.component, package_version.priority, package_version.closes, str(package_version.uploaded) ] @soapmethod(String, _returns=Array(String)) def versions(self, name): """ Returns a list of package versions for a package. """ q = meta.session.query(Package).filter_by(name=name) package = q.first() if package is None: return [] return [pv.version for pv in package.package_versions]
class types: userid = Integer username = String firstname = String lastname = String permissions = Array(Permission)
def extract_complex(self, element, parent=None, inuse=False): """ Create an complex object based on the supplied element. The resulting object is stored in ctypes and returned if created. parent - if supplied the parent object can be used to create a class, this is used for inline complextypes which are unnamed. The resulting class is created as <nameofparentelement>+CT. inuse - if inuse is True the extracted type is flagged as used by another type types that are not used e.g. messages are not marked and are not written out by the typeparser. This prevents add_userResponse being created as a ClassSerializer. """ #if element.tag == ccontent: # typelist = [] # for child in element.getchildren(): # typelist += self.extract_complex(child, inuse=True) # return typelist #print 'complexType', element, element.get('name'), parent if element.tag == ctype: name = element.get('name') if name is None: name = parent.get('name') + 'CT' klass = self.get_class(name, inuse=inuse) #attempt to detect a nested array type here #and tag it as an array, we can then later replace the #types with their array types in a second parse try: children = element.xpath('./xs:sequence/xs:element', namespaces={'xs': schnamespace}) children.extend(element.xpath('./xs:choice/xs:element', namespaces={'xs': schnamespace})) if len(children) == 1 and (children[0].get('maxOccurs') == 'unbounded' or children[0].get('maxOccurs', '1') != '1'): child = children[0] typelist = self.extract_complex(child, inuse=True) #items in a soaplib Array are named according to their datatype, #if this isn't the case we're just have a Repeating wrapped in #a class so don't tag childtype = typelist.pop() if childtype[0] == childtype[1].serializer.get_datatype(): #we have an array so tag it for repointing after we've finished parsing. klass.arraytag = (childtype[0], Array(childtype[1].serializer)) except Exception: traceback.print_exc() typelist = [] for child in element.getchildren(): typelist += self.extract_complex(child, inuse=True) for (typename, typevalue) in typelist: klass.types_ordered.append(typename) setattr(klass.types, typename, typevalue) #reassign metaclass: as dynamically building the class #means the metaclass code is run before the types have #been set so we re-call it here. ClassSerializerMeta.__init__(klass, name, ClassSerializer, {}) return [(None, klass)] elif element.tag == choice: typelist = [] for child in element.getchildren(): for complex_stype in self.extract_complex(child, inuse=True): if isinstance(complex_stype[1], Optional): typelist.append(complex_stype) else: typelist.append((complex_stype[0], Optional(complex_stype[1]))) return typelist elif element.tag == sequence or element.tag == all: typelist = [] for child in element.getchildren(): typelist += self.extract_complex(child, inuse=True) return typelist elif element.tag == scelement: minoccurs = element.get('minOccurs') etype = element.get('type') #cope with nested ctypes if etype is None: children = element.getchildren() if children: child = children[0] typelist = self.extract_complex(child, inuse=True, parent=element) try: (typename, typevalue) = typelist[0] if minoccurs == '0': typevalue = Optional(typevalue) return [(element.get('name'), typevalue)] except: return [] #if etype is None use Any built-in else #use qualify_type to search the built-ins using a qname if etype is None: serializer = Any elif self.qualify_type(etype) in builtins: serializer = builtins[self.qualify_type(etype)] else: try: serializer = self.get_class(self.extract_typename(etype), inuse=True) except: print "Could not get serializer for type: %s" % etype traceback.print_exc() return [] #check for array maxoccurs = element.get('maxOccurs', '1') if maxoccurs != '1' or maxoccurs == 'unbounded': return [(element.get('name'), Repeating(serializer))] else: if minoccurs == '0': return [(element.get('name'), Optional(serializer))] else: return [(element.get('name'), serializer)] elif element.tag == scany: if element.get('name'): return [(element.get('name'), Any)] else: return [('any', Any)] elif element.tag == stype: #yes this is as bad as at looks, we to be able #to support restrictions for us #to do any better though. child = element.getchildren()[0] etype = child.get('base') if etype in builtins: serializer = builtins[etype] else: try: serializer = self.get_class(self.extract_typename(etype)) except Exception: return [] return [(element.get('name'), serializer)] elif element.tag == scattr: self.unsupported.add('attributes') return [] else: try: if str(element.tag()) == '<!---->': #ignore xml comments return [] except: pass self.unsupported.add(element.tag) return []
class types: date_time = DateTime ro = ReturnObject arr = Array(String)
class types: simple = Array(SimpleClass) s = String i = Integer f = Float other = OtherClass
class SecurityServer(SimpleWSGISoapApp): __tns__ = 'urn:SecurityServer' @soapmethod(ApplicationAuthenticationContext, _returns=AuthenticatedToken, _inMessage='authenticateApplication', _outMessage='authenticateApplicationResponse', _outVariableName='out') def authenticateApplication(self, in0): pass @soapmethod(AuthenticatedToken, PrincipalAuthenticationContext, _returns=NewString, _inMessage='authenticatePrincipal', _outMessage='authenticatePrincipalResponse', _outVariableName='out') def authenticatePrincipal(self, in0, in1): pass @soapmethod(AuthenticatedToken, NewString, _returns=SOAPPrincipal, _inMessage='findPrincipalByToken', _outMessage='findPrincipalByTokenResponse', _outVariableName='out') def findPrincipalByToken(self, in0, in1): pass @soapmethod(AuthenticatedToken, NewString, _returns=SOAPPrincipal, _inMessage='findPrincipalByName', _outMessage='findPrincipalByNameResponse', _outVariableName='out') def findPrincipalByName(self, in0, in1): pass @soapmethod(AuthenticatedToken, _returns=Array(String), _inMessage='findAllPrincipalNames', _outMessage='findAllPrincipalNamesResponse', _outVariableName='out') def findAllPrincipalNames(self, in0): pass @soapmethod(AuthenticatedToken, NewString, Array(ValidationFactor), _returns=Boolean, _inMessage='isValidPrincipalToken', _outMessage='isValidPrincipalTokenResponse', _outVariableName='out') def isValidPrincipalToken(self, in0, in1, in2): pass @soapmethod(AuthenticatedToken, NewString, _returns=None, _inMessage='invalidatePrincipalToken', _outMessage='invalidatePrincipalTokenResponse', _outVariableName='out') def invalidatePrincipalToken(self, in0, in1): pass
class types: name = String birthdate = DateTime age = Integer addresses = Array(Address) titles = Array(String)
class types: level2 = Level2 level3 = Array(Level3) level4 = Array(Level4)
class InteropService(SimpleWSGISoapApp): # basic primitives @soapmethod(Integer, _returns=Integer) def echoInteger(self, i): return i @soapmethod(String, _returns=String) def echoString(self, s): return s @soapmethod(DateTime, _returns=DateTime) def echoDateTime(self, dt): return dt @soapmethod(Float, _returns=Float) def echoFloat(self, f): return f @soapmethod(Boolean, _returns=Boolean) def echoBoolean(self, b): return b # lists of primitives @soapmethod(Array(Integer), _returns=Array(Integer)) def echoIntegerArray(self, ia): return ia @soapmethod(Array(String), _returns=Array(String)) def echoStringArray(self, sa): return sa @soapmethod(Array(DateTime), _returns=Array(DateTime)) def echoDateTimeArray(self, dta): return dta @soapmethod(Array(Float), _returns=Array(Float)) def echoFloatArray(self, fa): return fa @soapmethod(Array(Boolean), _returns=Array(Boolean)) def echoBooleanArray(self, ba): return ba # classses @soapmethod(SimpleClass, _returns=SimpleClass) def echoSimpleClass(self, sc): return sc @soapmethod(Array(SimpleClass), _returns=Array(SimpleClass)) def echoSimpleClassArray(self, sca): return sca @soapmethod(NestedClass, _returns=NestedClass) def echoNestedClass(self, nc): return nc @soapmethod(Array(NestedClass), _returns=Array(NestedClass)) def echoNestedClassArray(self, nca): return nca @soapmethod(Attachment, _returns=Attachment) def echoAttachment(self, a): return a @soapmethod(Array(Attachment), _returns=Array(Attachment)) def echoAttachmentArray(self, aa): return aa @soapmethod() def testEmpty(self): # new pass @soapmethod(String, Integer, DateTime) def multiParam(self, s, i, dt): # new pass @soapmethod(_returns=String) def returnOnly(self): # new return 'howdy' @soapmethod(String, _returns=String, _soapAction="http://sample.org/webservices/doSomething") def doSomethingElse(self, s): return s
class types: name = NewString values = Array(NewString)