本文整理汇总了Python中ZSI.SoapWriter类的典型用法代码示例。如果您正苦于以下问题:Python SoapWriter类的具体用法?Python SoapWriter怎么用?Python SoapWriter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SoapWriter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_local_serialize_schema
def test_local_serialize_schema(self):
from ZSI import SoapWriter
from ZSI import _child_elements
from xml.dom.ext.reader import PyExpat
msg = self.client_module.DSQueryRegistrySoapOut()
msg.DSQueryRegistryResult = msg.new_DSQueryRegistryResult()
msg.DSQueryRegistryResult.Any = 'hi'
input = open('wsdl/nvo-admin.wsdl').read()
reader = PyExpat.Reader()
dom = reader.fromString(input)
dnode = _child_elements(dom)[0]
tnode = _child_elements(dnode)[0]
snode = _child_elements(tnode)[0]
msg.DSQueryRegistryResult.Schema = snode
sw = SoapWriter()
sw.serialize(msg)
soap = str(sw)
print soap
ps = ParsedSoap(soap)
pyobj = ps.Parse(msg.typecode)
self.failUnlessEqual(pyobj.DSQueryRegistryResult.Any, msg.DSQueryRegistryResult.Any)
self.failUnless(_is_element(pyobj.DSQueryRegistryResult.Schema))
print _get_element_nsuri_name(pyobj.DSQueryRegistryResult.Schema)
self.failUnlessEqual(_get_element_nsuri_name(pyobj.DSQueryRegistryResult.Schema), (u'http://www.w3.org/2001/XMLSchema', u'schema'))
示例2: setBody
def setBody(self, body, title='', is_error=0, bogus_str_search=None):
if isinstance(body, Fault):
# Convert Fault object to SOAP response.
body = body.AsSOAP()
else:
# Marshall our body as an SOAP response. Strings will be sent
# strings, integers as integers, etc. We do *not* convert
# everything to a string first.
try:
target = self._method
body = premarshal(body)
result = body
if hasattr(result, 'typecode'):
tc = result.typecode
else:
tc = TC.Any(aslist=1, pname=target + 'Response')
result = [result]
sw = SoapWriter(nsdict={}, header=True, outputclass=None,
encodingStyle=None)
body = str(sw.serialize(result, tc))
Node.unlink(sw.dom.node)
Node.unlink(sw.body.node)
del sw.dom.node
del sw.body.node
del sw.dom
del sw.body
except:
self.exception()
return
# Set our body to the message, and fix our MIME type.
self._real.setBody(body)
self._setHeader()
return self
示例3: test_local_anyType
def test_local_anyType(self):
"""rpc/lit, testing if <any/> lax content handling
should get back dicts and strings
"""
ps = ParsedSoap(MSG)
pyobj = ps.Parse(self.client_module.EventApproximatesSoapOut.typecode)
any = {'PoolTotals': {'Pool': {'Total': u'4117.66', 'ENumbers': None, 'JackpotNet': None}}, 'Approximates': {'Pool': {'Win': u'3.90,0.00,10.40,11.80,4.70,29.50,29.90,2.40,19.80,0.00', 'Place': u'1.04,0.00,2.80,5.90,2.00,5.20,7.40,1.04,4.00,0.00'}}}
self.failUnless(pyobj.EventApproximatesResult.Any == any, 'Failed match:\n %s\n\n%s' %(
pyobj.EventApproximatesResult.Any, any))
pyobj.EventApproximatesResult.Any = dict(pyobj.EventApproximatesResult.Any)
sw = SoapWriter()
sw.serialize(pyobj)
print str(sw)
ps2 = ParsedSoap(str(sw))
pyobj2 = ps.Parse(self.client_module.EventApproximatesSoapOut.typecode)
print "EAR: ", pyobj2.EventApproximatesResult
print "Any: ", pyobj2.EventApproximatesResult.Any
self.failUnless(pyobj.EventApproximatesResult.Any == pyobj2.EventApproximatesResult.Any,
'Failed match:\n %s\n\n%s' %(pyobj.EventApproximatesResult.Any, pyobj2.EventApproximatesResult.Any))
示例4: AsSOAP
def AsSOAP(self, **kw):
header = self.DataForSOAPHeader()
sw = SoapWriter(**kw)
self.serialize(sw)
if header is not None:
sw.serialize_header(header, header.typecode, typed=False)
return str(sw)
示例5: check_any_dict_list_rpcenc
def check_any_dict_list_rpcenc(self):
sw = SoapWriter()
testObj = [{"a":1,"b":2}, {"d":4,"e":5}, {"f":{"x":9}, "g":[6,7.0]}]
typecode = TC.Any(aslist=True)
sw.serialize(testObj, typecode=typecode)
xml = str(sw)
ps = ParsedSoap(xml)
result = TC.Any().parse(ps.body_root, ps)
self.failUnless(result == testObj)
示例6: _cache_soap
def _cache_soap(self, name, res):
from ZSI import SoapWriter
sw = SoapWriter()
xml = str(sw.serialize(res))
self._soapcache[name] = xml
# hack to get the cache to save
self._soapcache = self._soapcache
示例7: check_parse_empty_string
def check_parse_empty_string(self):
# Empty String
typecodes = list(TC.Any.parsemap.values())
for tc in [c for c in list(TC.Any.parsemap.values()) if isinstance(c, TC.String)]:
sw = SoapWriter()
sw.serialize("", typecode=tc, typed=True)
soap = str(sw)
ps = ParsedSoap(soap)
parsed = ps.Parse(TC.Any())
self.assertEqual("", parsed)
示例8: check_parse_empty_all
def check_parse_empty_all(self):
# None
skip = [TC.FPEnumeration, TC.Enumeration, TC.IEnumeration, TC.List, TC.Integer]
for typeclass in [c for c in list(TC.__dict__.values()) if type(c) in [type,type] and not issubclass(c, TC.String) and issubclass(c, TC.SimpleType)]:
if typeclass in skip: continue
tc = typeclass()
sw = SoapWriter()
sw.serialize(None, typecode=tc, typed=True)
soap = str(sw)
ps = ParsedSoap(soap)
parsed = ps.Parse(TC.Any())
self.assertEqual(None, parsed)
示例9: test_local_generateMessageAttachment
def test_local_generateMessageAttachment(self):
"""doc/lit, generating a message using MIME attachment,
we don't have the server side implementation so we can
really do a full test yet
"""
from TestService_server import uploadFileRequest
#stubs were properly generated
request = uploadFileRequest()
request._name = "TestService_client.py"
request._attachment = open("stubs/TestService_client.py", 'r')
sw = SoapWriter({}, header=True, outputclass=None, encodingStyle=None)
sw.serialize(request)
print "the request message is: " + str(sw)
示例10: check_builtins
def check_builtins(self):
myInt,myLong,myStr,myDate,myFloat = 123,2147483648,\
"hello", time.gmtime(), 1.0001
orig = [myInt,myLong,myStr,myDate,myFloat]
sw = SoapWriter()
sw.serialize(orig, typecode=TC.Any(pname="builtins", aslist=True))
ps = ParsedSoap(str(sw))
parsed = ps.Parse(TC.Any())
self.assertEqual(len(orig), len(parsed))
self.assertEqual(myInt, parsed[0])
self.assertEqual(myLong, parsed[1])
self.assertEqual(myStr, parsed[2])
self.assertEqual(myDate[0:6], parsed[3][0:6])
self.assertEqual(myFloat, parsed[4])
self.assertEqual(type(myInt), type(parsed[0]))
self.assertEqual(type(myLong), type(parsed[1]))
self.assertEqual(type(myStr), type(parsed[2]))
self.assertEqual(tuple, type(parsed[3]))
self.assertEqual(type(myFloat), type(parsed[4]))
示例11: check_uri_quoting
def check_uri_quoting(self):
""" all reserved characters used for reserved purpose.
"""
sw1 = SoapWriter(envelope=False)
tc1 = TC.URI("sourceforge")
orig = "https://sourceforge.net/tracker/index.php?func=detail&aid=1520092&group_id=26590&atid=387667"
sw1.serialize(orig, typecode=tc1, typed=False)
s1 = str(sw1)
sw2 = SoapWriter(envelope=False)
tc2 = TC.String("sourceforge")
sw2.serialize(orig, typecode=tc2, typed=False)
s2 = str(sw2)
# print s1
# print s2
self.failUnless(s1 == s2, "reserved characters used for reserved purpose should not be escaped.")
ps = ParsedSoap(s2, envelope=False)
pyobj = ps.Parse(tc2)
self.failUnless(pyobj == orig, "parsed object should be equivalent to original")
示例12: checkt7
def checkt7(self):
ps = ParsedSoap(text)
tcdict = TC.Apache.Map('c-gensym1')
tclist = TC.Apache.Map('c-gensym1', aslist=1)
d = tcdict.parse(ps.body_root, ps)
self.assertEqual(d, { u'a':123, '\x00\x01':456 })
#print 'as dictionary\n', d
l = tclist.parse(ps.body_root, ps)
self.assertEqual(l, [('\x00\x01', 456), (u'a', 123)])
#print '\n', '=' * 30
#print 'as list\n', l
#print '\n', '=' * 30
sw = SoapWriter()
sw.serialize(d, tcdict)
#print >>sys.stdout, sw
#print '\n', '=' * 30
sw = SoapWriter()
sw.serialize(l, tclist)
示例13: Send
def Send(self, url, opname, obj, nsdict={}, soapaction=None, wsaction=None,
endPointReference=None, soapheaders=(), **kw):
'''Send a message. If url is None, use the value from the
constructor (else error). obj is the object (data) to send.
Data may be described with a requesttypecode keyword, the default
is the class's typecode (if there is one), else Any.
Try to serialize as a Struct, if this is not possible serialize an Array. If
data is a sequence of built-in python data types, it will be serialized as an
Array, unless requesttypecode is specified.
arguments:
url --
opname -- struct wrapper
obj -- python instance
key word arguments:
nsdict --
soapaction --
wsaction -- WS-Address Action, goes in SOAP Header.
endPointReference -- set by calling party, must be an
EndPointReference type instance.
soapheaders -- list of pyobj, typically w/typecode attribute.
serialized in the SOAP:Header.
requesttypecode --
'''
url = url or self.url
endPointReference = endPointReference or self.endPointReference
# Serialize the object.
d = {}
d.update(self.nsdict)
d.update(nsdict)
sw = SoapWriter(nsdict=d, header=True, outputclass=self.writerclass,
encodingStyle=kw.get('encodingStyle'),)
requesttypecode = kw.get('requesttypecode')
if kw.has_key('_args'): #NamedParamBinding
tc = requesttypecode or TC.Any(pname=opname, aslist=False)
sw.serialize(kw['_args'], tc)
elif not requesttypecode:
tc = getattr(obj, 'typecode', None) or TC.Any(pname=opname, aslist=False)
try:
if type(obj) in _seqtypes:
obj = dict(map(lambda i: (i.typecode.pname,i), obj))
except AttributeError:
# can't do anything but serialize this in a SOAP:Array
tc = TC.Any(pname=opname, aslist=True)
else:
tc = TC.Any(pname=opname, aslist=False)
sw.serialize(obj, tc)
else:
sw.serialize(obj, requesttypecode)
for i in soapheaders:
sw.serialize_header(i)
#
# Determine the SOAP auth element. SOAP:Header element
if self.auth_style & AUTH.zsibasic:
sw.serialize_header(_AuthHeader(self.auth_user, self.auth_pass),
_AuthHeader.typecode)
#
# Serialize WS-Address
if self.wsAddressURI is not None:
if self.soapaction and wsaction.strip('\'"') != self.soapaction:
raise WSActionException, 'soapAction(%s) and WS-Action(%s) must match'\
%(self.soapaction,wsaction)
self.address = Address(url, self.wsAddressURI)
self.address.setRequest(endPointReference, wsaction)
self.address.serialize(sw)
#
# WS-Security Signature Handler
if self.sig_handler is not None:
self.sig_handler.sign(sw)
scheme,netloc,path,nil,nil,nil = urlparse.urlparse(url)
transport = self.transport
if transport is None and url is not None:
if scheme == 'https':
transport = self.defaultHttpsTransport
elif scheme == 'http':
transport = self.defaultHttpTransport
else:
raise RuntimeError, 'must specify transport or url startswith https/http'
# Send the request.
if issubclass(transport, httplib.HTTPConnection) is False:
raise TypeError, 'transport must be a HTTPConnection'
soapdata = str(sw)
self.h = transport(netloc, None, **self.transdict)
self.h.connect()
self.SendSOAPData(soapdata, url, soapaction, **kw)
示例14: register_results
def register_results(algsynonim, password, pocketid, results):
"""Posts results to the poligon server"""
register_request = RegisterResultSoapIn()
register_request.AlgSynonim = algsynonim
register_request.Password = password
register_request.PocketKey = int(pocketid)
register_request.LearnResults = register_request.new_learnResults()
register_request.TestResults = register_request.new_testResults()
for i in range(len(results)):
test_result = register_request.TestResults.new_TestResult()
learn_result = register_request.LearnResults.new_TestResult()
test_result.Index = i
learn_result.Index = i
test_result.Error = results[i].Error
test_result.ErrorException = results[i].ErrorException
learn_result.Error = results[i].Error
learn_result.ErrorException = results[i].ErrorException
if not results[i].Error:
test_result.Error = results[i].Test.Error
test_result.ErrorException = results[i].Test.ErrorException
learn_result.Error = results[i].Test.Error
learn_result.ErrorException = results[i].Test.ErrorException
# Answers
test_result.Answers = test_result.new_Answers()
learn_result.Answers = learn_result.new_Answers()
for j in range(len(results[i].Learn.Targets)):
learn_result.Answers.Int.append(int(results[i].Learn.Targets[j]))
for j in range(len(results[i].Test.Targets)):
test_result.Answers.Int.append(int(results[i].Test.Targets[j]))
# PropertiesWeights
#test_result.PropertiesWeights = test_result.new_PropertiesWeights()
#learn_result.PropertiesWeights = learn_result.new_PropertiesWeights()
#for j in range(len(results[i].LearnPropertiesWeights)):
# learn_result.PropertiesWeights.Double.append(results[i].LearnPropertiesWeights[j])
#for j in range(len(results[i].TestPropertiesWeights)):
# test_result.PropertiesWeights.Double.append(results[i].TestPropertiesWeights[j])
# Object weights
#test_result.ObjectsWeights = test_result.new_ObjectsWeights()
#learn_result.ObjectsWeights = learn_result.new_ObjectsWeights()
#for j in range(len(results[i].LearnObjectsWeights)):
# learn_result.ObjectsWeights.Double.append(results[i].LearnObjectsWeights[j])
#for j in range(len(results[i].TestObjectsWeights)):
# test_result.ObjectsWeights.Double.append(results[i].TestObjectsWeights[j])
# ProbabilityMatrix
test_result.ProbabilityMatrix = test_result.new_ProbabilityMatrix()
learn_result.ProbabilityMatrix = learn_result.new_ProbabilityMatrix()
for vector in results[i].Test.ProbabilityMatrix:
array = test_result.ProbabilityMatrix.new_ArrayOfDouble()
for item in vector:
array.Double.append(item)
test_result.ProbabilityMatrix.ArrayOfDouble.append(array)
for vector in results[i].Learn.ProbabilityMatrix:
array = learn_result.ProbabilityMatrix.new_ArrayOfDouble()
for item in vector:
array.Double.append(item)
learn_result.ProbabilityMatrix.ArrayOfDouble.append(array)
register_request.TestResults.TestResult.append(test_result)
register_request.LearnResults.TestResult.append(learn_result)
try:
sw = SoapWriter()
sw.serialize(register_request)
file = open('RegisterResult.xml', 'w')
file.write(str(sw))
file.close()
except:
logger.error('Can\'t write file results file')
if REGISTER_RESULTS:
try:
response = service.RegisterResult(register_request, **KW)
if response.RegisterResultResult.Status == 'Ok':
logger.info('Results are posted successfully')
else:
logger.error(
'Error occured while posting results\n{0}'.format(response.RegisterResultResult.Message.encode('unicode', 'replace')))
return response.RegisterResultResult
except:
logger.error(
'Error occured while posting results \'{0}\'\n{1}'.format(pocketid, sys.exc_info()[0]))
#.........这里部分代码省略.........
示例15: int
else:
length = int(self.headers['content-length'])
ps = ParsedSoap(self.rfile.read(length))
except ParseException, e:
ConsumerServer.logger.error(str(e))
self.send_fault(FaultFromZSIException(e))
return
except Exception, e:
ConsumerServer.logger.error(str(e))
self.send_fault(FaultFromException(e, 1, sys.exc_info()[2]))
return
try:
self.handleNotify(ps.body_root)
#TODO: missing namespace cemon_consumer
sw = SoapWriter(nsdict=NSTable)
sw.serialize(Notify(), Notify.typecode)
sw.close()
self.send_xml(str(sw))
except Exception, e:
ConsumerServer.logger.error(str(e))
import traceback
traceback.print_tb(sys.exc_info()[2])
self.send_fault(FaultFromException(e, 0, sys.exc_info()[2]))
class ConnectionFixer(object):
""" wraps a socket connection so it implements makefile """
def __init__(self, conn):
self.__conn = conn
def makefile(self, mode, bufsize):
return socket._fileobject(self.__conn, mode, bufsize)