本文整理汇总了Python中soaplib.etimport.ElementTree类的典型用法代码示例。如果您正苦于以下问题:Python ElementTree类的具体用法?Python ElementTree怎么用?Python ElementTree使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ElementTree类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: to_xml
def to_xml(cls,value,name='retval'):
if type(value) == str:
value = ElementTree.fromstring(value)
e = ElementTree.Element(name)
e.set('xmlns','')
e.append(value)
return e
开发者ID:esauro,项目名称:SingularMS,代码行数:7,代码来源:primitive.py
示例2: importtypes
def importtypes(self, document):
"""
Processes any imported xmlschema in a wsdl:types element
within document, returns a soaplib.parsers.typeparse.TypeParser
containing the parsed schema.
"""
for t in document.findall(wsdlqname+"types"):
url = None
for s in t.findall(schqname+"schema"):
for i in s.findall(schqname+"import"):
url = i.get('schemaLocation')
if url is not None:
#work out if relative or absolute url
if '://' not in url:
#relative
url = path.join(path.dirname(self.url), url)
f = ulib.urlopen(url)
d = f.read()
f.close()
element = ElementTree.fromstring(d)
else:
#inline schema
for element in t.findall(schqname+"schema"):
self._add_tp(TypeParser(element, global_ctypes=self.ctypes, global_elements=self.elements))
return
self._add_tp(TypeParser(element, global_ctypes=self.ctypes, global_elements=self.elements))
return
开发者ID:mpsinfo,项目名称:soaplib,代码行数:28,代码来源:wsdlparse.py
示例3: to_xml
def to_xml(cls, value, name="retval"):
if type(value) == str:
value = ElementTree.fromstring(value)
e = ElementTree.Element(name)
e.set("xmlns", "")
e.append(value)
return e
开发者ID:certik,项目名称:debexpo,代码行数:7,代码来源:primitive.py
示例4: importwsdl
def importwsdl(self, document):
"""
Processes any wsdl documents imported by document
(messages are sometimes held in a seperate document, for example).
Recusively calls WsdlParser to descend through imports
"""
reimport = 0
for imp in document.findall('%simport' % wsdlqname):
url = str(imp.get('location'))
#work out if relative or absolute url
if '://' not in url:
#relative
url = path.join(path.dirname(self.url), url)
f = ulib.urlopen(url)
d = f.read()
f.close()
root = ElementTree.fromstring(d)
wp = WSDLParser(root, url)
for cats in ['ctypes', 'elements', 'messagecat', 'portcat', 'bindingcat']:
getattr(self, cats).update(getattr(wp, cats))
document.remove(imp)
if self.tp is None:
self.tp = wp.tp
elif wp.tp is not None:
self.tp.ctypes.update(wp.tp.ctypes)
self.tp.elements.update(wp.tp.elements)
开发者ID:edevil,项目名称:soaplib,代码行数:26,代码来源:wsdlparse.py
示例5: element2dict
def element2dict(element):
deprecate('element2dict')
if type(element) == str:
element = ElementTree.fromstring(element)
children = element.getchildren()
tag = element.tag.split('}')[-1]
return {tag: _element2dict(children)}
开发者ID:fabregas,项目名称:old_projects,代码行数:8,代码来源:util.py
示例6: from_string
def from_string(cls, xml, url):
"""
return a new WSDLParser with WSDL parsed from the supplied xml,
the url is required incase of additional wsdl or schema files
need to be fetched.
"""
element = ElementTree.fromstring(xml)
return WSDLParser(element, url)
开发者ID:mpsinfo,项目名称:soaplib,代码行数:8,代码来源:wsdlparse.py
示例7: join_attachment
def join_attachment(id, envelope, payload, prefix=True):
'''
Helper function for swa_to_soap.
Places the data from an attachment back into a SOAP message, replacing
its xop:Include element or href.
@param id content-id or content-location of attachment
@param prefix Set this to true if id is content-id or false if
it is content-location. It prefixes a "cid:" to
the href value.
@param envelope soap envelope string to be operated on
@param payload attachment data
@return tuple of length 2 with the new message and the
number of replacements made
'''
# grab the XML element of the message in the SOAP body
soapmsg = StringIO(envelope)
soaptree = ElementTree.parse(soapmsg)
soapns = soaptree.getroot().tag.split('}')[0].strip('{')
soapbody = soaptree.getroot().find("{%s}Body" % soapns)
message = None
for child in list(soapbody):
if child.tag != "%sFault" % (soapns,):
message = child
break
numreplaces = 0
idprefix = ''
if prefix == True: idprefix = "cid:"
id = "%s%s" % (idprefix, id, )
# Make replacement.
for param in message:
# Look for Include subelement.
for sub in param:
if sub.tag.split('}')[-1] == 'Include' and \
sub.attrib.get('href') == id:
param.remove(sub)
param.text = payload
numreplaces += 1
if numreplaces < 1 and param.attrib.get('href') == id:
del(param.attrib['href'])
param.text = payload
numreplaces += 1
soapmsg.close()
soapmsg = StringIO()
soaptree.write(soapmsg)
joinedmsg = soapmsg.getvalue()
soapmsg.close()
return (joinedmsg, numreplaces)
开发者ID:esauro,项目名称:SingularMS,代码行数:54,代码来源:soap.py
示例8: from_xml
def from_xml(cls, element):
code = _element_to_string(element.find('faultcode'))
string = _element_to_string(element.find('faultstring'))
detail_element = element.find('detail')
if detail_element:
if len(detail_element.getchildren()):
detail = ElementTree.tostring(detail_element)
else:
detail = _element_to_string(element.find('detail'))
else:
detail = ''
return Fault(faultcode = code, faultstring = string, detail = detail)
开发者ID:esauro,项目名称:SingularMS,代码行数:12,代码来源:primitive.py
示例9: importwsdl
def importwsdl(self, document):
"""
Processes any wsdl documents imported by document
(messages are sometimes held in a seperate document, for example).
Recusively calls WsdlParser to descend through imports
"""
reimport = 0
for imp in document.findall("%simport" % wsdlqname):
url = str(imp.get("location"))
# work out if relative or absolute url
if "://" not in url:
# relative
url = path.join(path.dirname(self.url), url)
f = ulib.urlopen(url)
d = f.read()
f.close()
root = ElementTree.fromstring(d)
wp = WSDLParser(root, url)
for cats in ["ctypes", "elements", "messagecat", "portcat", "bindingcat"]:
getattr(self, cats).update(getattr(wp, cats))
document.remove(imp)
for tp in wp.tps:
self._add_tp(tp)
开发者ID:TitanEntertainmentGroup,项目名称:soaplib,代码行数:23,代码来源:wsdlparse.py
示例10: from_string
def from_string(cls, xml):
""" return a new TypeParser with XSD parsed from the supplied xml """
element = ElementTree.fromstring(xml)
return TypeParser(element)
开发者ID:stacktracer,项目名称:soaplib_0.8.x,代码行数:4,代码来源:typeparse.py
示例11: __call__
def __call__(self, environ, start_response):
'''
This method conforms to the WSGI spec for callable wsgi applications (PEP 333).
This method looks in environ['wsgi.input'] for a fully formed soap request envelope,
will deserialize the request parameters and call the method on the object returned
by the getHandler() method.
@param the http environment
@param a callable that begins the response message
@returns the string representation of the soap call
'''
methodname = ''
try:
reset_request()
request.environ = environ
# implementation hook
self.onCall(environ)
serviceName = environ['PATH_INFO'].split('/')[-1]
service = self.getHandler(environ)
if serviceName.lower().endswith('wsdl'):
# get the wsdl for the service
#
# Assume path_info matches pattern
# /stuff/stuff/stuff/serviceName.wsdl or ?WSDL
#
serviceName = serviceName.split('.')[0]
url = reconstruct_url(environ).split('.wsdl')[0]
start_response('200 OK',[('Content-type','text/xml')])
try:
wsdl_content = service.wsdl(url)
# implementation hook
self.onWsdl(environ,wsdl_content)
except Exception, e:
# implementation hook
buffer = cStringIO.StringIO()
traceback.print_exc(file=buffer)
buffer.seek(0)
stacktrace = str(buffer.read())
faultStr = ElementTree.tostring(make_soap_fault( str(e), detail=stacktrace), encoding=string_encoding)
exceptions(faultStr)
self.onWsdlException(environ,e,faultStr)
# initiate the response
start_response('500',[('Content-type','text/xml'),('Content-length',str(len(faultStr)))])
return [faultStr]
reset_request()
return [wsdl_content]
if environ['REQUEST_METHOD'].lower() != 'post':
start_response('405 Method Not Allowed',[('Allow','POST')])
return ''
input = environ.get('wsgi.input')
length = environ.get("CONTENT_LENGTH")
body = input.read(int(length))
debug(body)
body = collapse_swa( environ.get("CONTENT_TYPE"), body)
# deserialize the body of the message
payload, header = from_soap(body)
if payload:
methodname = payload.tag.split('}')[-1]
else:
# check HTTP_SOAPACTION
methodname = environ.get("HTTP_SOAPACTION")
if methodname.startswith('"') and methodname.endswith('"'):
methodname = methodname[1:-1]
request.header = header
# call the method
func = getattr(service, methodname)
# retrieve the method descriptor
descriptor = func(_soap_descriptor=True)
if payload:
params = descriptor.inMessage.from_xml(*[payload])
else:
params = ()
# implementation hook
self.onMethodExec(environ,body,params,descriptor.inMessage.params)
# call the method
retval = func(*params)
# transform the results into an element
# only expect a single element
results = None
if not (descriptor.isAsync or descriptor.isCallback):
results = descriptor.outMessage.to_xml(*[retval])
# implementation hook
self.onResults(environ,results,retval)
#.........这里部分代码省略.........
开发者ID:tubav,项目名称:teagle,代码行数:101,代码来源:wsgi_soap.py
示例12: __call__
def __call__(self, *args, **kwargs):
'''
This method executes the http request to the remote web service. With
the exception of 'headers', 'msgid', and 'mtom'; all keyword arguments
to this method are put in the http header. The 'headers' keyword is to
denote a list of elements to be included in the soap header, 'msgid'
is a convenience keyword used in async web services which creates a
WS-Addressing messageid header to be included in the soap headers, and
'mtom' enables the Message Transmission Optimization Mechanism.
@param the arguments to the remote method
@param the keyword arguments
'''
if len(args) != len(self.descriptor.inMessage.params):
argstring = '\r\n'.join([' ' + str(arg) for arg in args])
paramstring = '\r\n'.join([' ' + str(p[0])
for p in self.descriptor.inMessage.params])
err_msg = _err_format % (argstring, paramstring)
raise Exception(err_msg)
msg = self.descriptor.inMessage.to_xml(*args)
# grab the soap headers passed into this call
headers = kwargs.get('headers', [])
mtom = kwargs.get('mtom', False)
msgid = kwargs.get('msgid')
if msgid:
# special case for the msgid field as a convenience
# when dealing with async callback methods
headers.append(create_relates_to_header(msgid))
tns = self.descriptor.inMessage.ns
envelope = make_soap_envelope(msg, tns, header_elements=headers)
body = ElementTree.tostring(envelope)
methodName = '\"%s\"' % self.descriptor.soapAction
httpHeaders = {'Content-Length': len(body),
'Content-type': 'text/xml; charset="UTF-8"',
'Accept': ('application/soap+xml, application/dime, '
'multipart/related, text/*'),
'User-Agent': 'Soaplib/1.0',
'SOAPAction': methodName,
}
for k, v in kwargs.items():
# add all the other keywords to the http headers
if k not in ('headers', 'msgid', 'mtom'):
httpHeaders[k] = v
if mtom:
httpHeaders, body = apply_mtom(httpHeaders, body,
self.descriptor.inMessage.params, args)
dump(self.host, self.path, httpHeaders, body)
if self.scheme == "http":
conn = httplib.HTTPConnection(self.host)
elif self.scheme == "https":
conn = httplib.HTTPSConnection(self.host)
else:
raise RuntimeError("Unsupported URI connection scheme: %s" %
self.scheme)
conn.request("POST", self.path, body=body, headers=httpHeaders)
response = conn.getresponse()
data = response.read()
dump(self.host, self.path, dict(response.getheaders()), data)
contenttype = response.getheader('Content-Type')
data = collapse_swa(contenttype, data)
conn.close()
if str(response.status) not in['200', '202']:
# consider everything NOT 200 or 202 as an error response
if str(response.status) == '500':
fault = None
try:
payload, headers = from_soap(data)
fault = Fault.from_xml(payload)
except:
trace = StringIO()
import traceback
traceback.print_exc(file=trace)
fault = Exception("Unable to read response \n"
"%s %s \n %s \n %s" %
(response.status, response.reason, trace.getvalue(),
data))
raise fault
else:
raise Exception("%s %s" % (response.status, response.reason))
if not self.descriptor.outMessage.params:
return
payload, headers = from_soap(data)
results = self.descriptor.outMessage.from_xml(payload)
return results[0]
开发者ID:edevil,项目名称:soaplib,代码行数:100,代码来源:client.py
示例13: wsdl
def wsdl(self, url):
'''
This method generates and caches the wsdl for this object based
on the soap methods designated by the soapmethod or soapdocument
descriptors
@param url the url that this service can be found at. This must be
passed in by the caller because this object has no notion of the
server environment in which it runs.
@returns the string of the wsdl
'''
if not self.__wsdl__ == None:
# return the cached __wsdl__
return self.__wsdl__
url = url.replace('.wsdl','')
# otherwise build it
serviceName = self.__class__.__name__.split('.')[-1]
tns = self.__tns__
root = ElementTree.Element("definitions")
root.set('targetNamespace',tns)
root.set('xmlns:tns',tns)
root.set('xmlns:typens',tns)
root.set('xmlns','http://schemas.xmlsoap.org/wsdl/')
root.set('xmlns:soap','http://schemas.xmlsoap.org/wsdl/soap/')
root.set('xmlns:xs','http://www.w3.org/2001/XMLSchema')
root.set('xmlns:plnk','http://schemas.xmlsoap.org/ws/2003/05/partner-link/')
root.set('xmlns:SOAP-ENC',"http://schemas.xmlsoap.org/soap/encoding/")
root.set('xmlns:wsdl',"http://schemas.xmlsoap.org/wsdl/")
root.set('name',serviceName)
types = ElementTree.SubElement(root,"types")
methods = self.methods()
hasCallbacks = self._hasCallbacks()
self._add_schema(types,methods)
self._add_messages_for_methods(root,methods)
# add necessary async headers
# WS-Addressing -> RelatesTo ReplyTo MessageID
# callback porttype
if hasCallbacks:
root.set('xmlns:wsa','http://schemas.xmlsoap.org/ws/2003/03/addressing')
wsaSchemaNode = ElementTree.SubElement(types, "schema")
wsaSchemaNode.set("targetNamespace", tns+'Callback')
wsaSchemaNode.set("xmlns", "http://www.w3.org/2001/XMLSchema")
importNode = ElementTree.SubElement(wsaSchemaNode, "import")
importNode.set("namespace", "http://schemas.xmlsoap.org/ws/2003/03/addressing")
importNode.set("schemaLocation", "http://schemas.xmlsoap.org/ws/2003/03/addressing/")
reltMessage = ElementTree.SubElement(root,'message')
reltMessage.set('name','RelatesToHeader')
reltPart = ElementTree.SubElement(reltMessage,'part')
reltPart.set('name','RelatesTo')
reltPart.set('element','wsa:RelatesTo')
replyMessage = ElementTree.SubElement(root,'message')
replyMessage.set('name','ReplyToHeader')
replyPart = ElementTree.SubElement(replyMessage,'part')
replyPart.set('name','ReplyTo')
replyPart.set('element','wsa:ReplyTo')
idHeader = ElementTree.SubElement(root,'message')
idHeader.set('name','MessageIDHeader')
idPart = ElementTree.SubElement(idHeader,'part')
idPart.set('name','MessageID')
idPart.set('element','wsa:MessageID')
# make portTypes
callbackPortType = ElementTree.SubElement(root,'portType')
callbackPortType.set('name','%sCallback'%serviceName)
cbServiceName = '%sCallback'%serviceName
cbService = ElementTree.SubElement(root,'service')
cbService.set('name',cbServiceName)
cbWsdlPort = ElementTree.SubElement(cbService,'port')
cbWsdlPort.set('name',cbServiceName)
cbWsdlPort.set('binding','tns:%s'%cbServiceName)
cbAddr = ElementTree.SubElement(cbWsdlPort,'soap:address')
cbAddr.set('location',url)
serviceName = self.__class__.__name__.split('.')[-1]
portType = ElementTree.SubElement(root,'portType')
portType.set('name',serviceName)
for method in methods:
if method.isCallback:
operation = ElementTree.SubElement(callbackPortType,'operation')
else:
operation = ElementTree.SubElement(portType,'operation')
operation.set('name',method.name)
params = []
#.........这里部分代码省略.........
开发者ID:certik,项目名称:debexpo,代码行数:101,代码来源:service.py
示例14: __call__
def __call__(self, environ, start_response, address_url=None):
'''
This method conforms to the WSGI spec for callable wsgi applications
(PEP 333). It looks in environ['wsgi.input'] for a fully formed soap
request envelope, will deserialize the request parameters and call the
method on the object returned by the getHandler() method.
@param the http environment
@param a callable that begins the response message
@returns the string representation of the soap call
'''
methodname = ''
try:
reset_request()
request.environ = environ
# implementation hook
self.onCall(environ)
serviceName = environ['PATH_INFO'].split('/')[-1]
service = self.getHandler(environ)
if ((environ['QUERY_STRING'].endswith('wsdl') or
environ['PATH_INFO'].endswith('wsdl')) and
environ['REQUEST_METHOD'].lower() == 'get'):
# get the wsdl for the service
#
# Assume path_info matches pattern
# /stuff/stuff/stuff/serviceName.wsdl or ?WSDL
#
serviceName = serviceName.split('.')[0]
if address_url:
url = address_url
else:
url = reconstruct_url(environ).split('.wsdl')[0]
start_response('200 OK', [('Content-type', 'text/xml')])
try:
wsdl_content = service.wsdl(url)
# implementation hook
self.onWsdl(environ, wsdl_content)
except Exception, e:
# implementation hook
buffer = cStringIO.StringIO()
traceback.print_exc(file=buffer)
buffer.seek(0)
stacktrace = str(buffer.read())
faultStr = ElementTree.tostring(make_soap_fault(str(e),
detail=stacktrace), encoding=string_encoding)
exceptions(faultStr)
self.onWsdlException(environ, e, faultStr)
# initiate the response
start_response('500 Internal Server Error',
[('Content-type', 'text/xml'),
('Content-length', str(len(faultStr)))])
return [faultStr]
reset_request()
return [wsdl_content]
if environ['REQUEST_METHOD'].lower() != 'post':
start_response('405 Method Not Allowed', [('Allow', 'POST')])
return ''
input = environ.get('wsgi.input')
length = environ.get("CONTENT_LENGTH")
body = input.read(int(length))
methodname = environ.get("HTTP_SOAPACTION")
debug('\033[92m'+ methodname +'\033[0m')
debug(body)
body = collapse_swa(environ.get("CONTENT_TYPE"), body)
# deserialize the body of the message
try:
payload, header = from_soap(body)
except SyntaxError, e:
payload = None
header = None
开发者ID:Proga,项目名称:soaplib,代码行数:81,代码来源:wsgi_soap.py
示例15: hasattr
return [resp]
except Fault, e:
# grab any headers that were included in the request
response_headers = None
if hasattr(request, 'response_headers'):
response_headers = request.response_headers
# The user issued a Fault, so handle it just like an exception!
fault = make_soap_fault(
e.faultstring,
e.faultcode,
e.detail,
header_elements=response_headers)
faultStr = ElementTree.tostring(fault, encoding=string_encoding)
exceptions(faultStr)
self.onException(environ, e, faultStr)
reset_request()
# initiate the response
start_response('500 Internal Server Error',
[('Content-type', 'text/xml')])
return [faultStr]
except Exception, e:
# Dump the stack trace to a buffer to be sent
# back to the caller
开发者ID:Proga,项目名称:soaplib,代码行数:30,代码来源:wsgi_soap.py
示例16: to_xml
def to_xml(cls,value,name='retval',nsmap=ns):
if type(value) == str:
value = ElementTree.fromstring(value)
e = create_xml_element(name, nsmap)
e.append(value)
return e
开发者ID:finalbattle,项目名称:torweb,代码行数:6,代码来源:primitive.py
示例17: or
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
#
from soaplib.etimport import ElementTree
ElementTree.set_default_parser(ElementTree.ETCompatXMLParser())
class NamespaceLookup(object):
'''
Class to manage XML namespaces
'''
def __init__(self, tns = None, wsdl_map = False):
self.nsmap = {
'xs': 'http://www.w3.org/2001/XMLSchema',
'xsi': 'http://www.w3.org/1999/XMLSchema-instance',
'plnk': 'http://schemas.xmlsoap.org/ws/2003/05/partner-link/',
}
if wsdl_map:
self.nsmap['soap'] = 'http://schemas.xmlsoap.org/wsdl/soap/'
self.nsmap['wsdl'] = 'http://schemas.xmlsoap.org/wsdl/'
开发者ID:fabregas,项目名称:old_projects,代码行数:31,代码来源:xmlutils.py
示例18: test_override_default_names
def test_override_default_names(self):
wsdl = ElementTree.fromstring(OverrideNamespaceService().wsdl(''))
self.assertEquals(wsdl.get('targetNamespace'),
"http://someservice.com/override")
开发者ID:edevil,项目名称:soaplib,代码行数:4,代码来源:service_test.py
示例19: apply_mtom
def apply_mtom(headers, envelope, params, paramvals):
'''
Apply MTOM to a SOAP envelope, separating attachments into a
MIME multipart message.
References:
XOP http://www.w3.org/TR/xop10/
MTOM http://www.w3.org/TR/soap12-mtom/
http://www.w3.org/Submission/soap11mtom10/
@param headers Headers dictionary of the SOAP message that would
originally be sent.
@param envelope SOAP envelope string that would have originally been sent.
@param params params attribute from the Message object used for the SOAP
@param paramvals values of the params, passed to Message.to_xml
@return tuple of length 2 with dictionary of headers and
string of body that can be sent with HTTPConnection
'''
# grab the XML element of the message in the SOAP body
soapmsg = StringIO(envelope)
soaptree = ElementTree.parse(soapmsg)
soapns = soaptree.getroot().tag.split('}')[0].strip('{')
soapbody = soaptree.getroot().find("{%s}Body" % soapns)
message = None
for child in list(soapbody):
if child.tag != "%sFault" % (soapns,):
message = child
break
# Get additional parameters from original Content-Type
ctarray = []
for n, v in headers.items():
if n.lower() == 'content-type':
ctarray = v.split(';')
break
roottype = ctarray[0].strip()
rootparams = {}
for ctparam in ctarray[1:]:
n, v = ctparam.strip().split('=')
rootparams[n] = v.strip("\"'")
# Set up initial MIME parts
mtompkg = MIMEMultipart('related',boundary='?//<><>soaplib_MIME_boundary<>')
rootpkg = None
try:
rootpkg = MIMEApplication(envelope,'xop+xml', encode_7or8bit)
except NameError:
rootpkg = MIMENonMultipart("application", "xop+xml")
rootpkg.set_payload(envelope)
encode_7or8bit(rootpkg)
# Set up multipart headers.
del(mtompkg['mime-version'])
mtompkg.set_param('start-info',roottype)
mtompkg.set_param('start','<soaplibEnvelope>')
if headers.has_key('SOAPAction'):
mtompkg.add_header('SOAPAction', headers.get('SOAPAction'))
# Set up root SOAP part headers
del(rootpkg['mime-version'])
rootpkg.add_header('Content-ID','<soaplibEnvelope>')
for n, v in rootparams.items():
rootpkg.set_param(n,v)
rootpkg.set_param('type',roottype)
mtompkg.attach(rootpkg)
# Extract attachments from SOAP envelope.
for i in range(len(params)):
name, typ = params[i]
if typ == Attachment:
id = "soaplibAttachment_%s" % (len(mtompkg.get_payload()),)
param = message[i]
param.text = ""
incl = ElementTree.SubElement(
param,
"{http://www.w3.org/2004/08/xop/include}Include"
)
incl.attrib["href"] = "cid:%s" % id
if paramvals[i].fileName and not paramvals[i].data:
paramvals[i].load_from_file()
data = paramvals[i].data
attachment = None
try:
attachment = MIMEApplication(data, _encoder=encode_7or8bit)
except NameError:
attachment = MIMENonMultipart("application", "octet-stream")
attachment.set_payload(data)
encode_7or8bit(attachment)
del(attachment['mime-version'])
attachment.add_header('Content-ID','<%s>'%(id,))
mtompkg.attach(attachment)
# Update SOAP envelope.
soapmsg.close()
soapmsg = StringIO()
soaptree.write(soapmsg)
rootpkg.set_payload(soapmsg.getvalue())
soapmsg.close()
#.........这里部分代码省略.........
开发者ID:esauro,项目名称:SingularMS,代码行数:101,代码来源:soap.py
示例20: setUp
def setUp(self):
self.service = TestService()
self._wsdl = self.service.wsdl('')
self.wsdl = ElementTree.fromstring(self._wsdl)
开发者ID:edevil,项目名称:soaplib,代码行数:4,代码来源:service_test.py
注:本文中的soaplib.etimport.ElementTree类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论