repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_documentation_string
stringlengths 1
47.2k
| func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|
suds-community/suds | suds/wsdl.py | Service.do_resolve | def do_resolve(self, definitions):
"""
Resolve named references to other WSDL objects. Ports without SOAP
bindings are discarded.
@param definitions: A definitions object.
@type definitions: L{Definitions}
"""
filtered = []
for p in self.ports:
ref = qualify(p.binding, self.root, definitions.tns)
binding = definitions.bindings.get(ref)
if binding is None:
raise Exception("binding '%s', not-found" % (p.binding,))
if binding.soap is None:
log.debug("binding '%s' - not a SOAP binding, discarded",
binding.name)
continue
# After we have been resolved, our caller will expect that the
# binding we are referencing has been fully constructed, i.e.
# resolved, as well. The only scenario where the operations binding
# might possibly not have already resolved its references, and
# where this explicit resolve() call is required, is if we are
# dealing with a recursive WSDL import chain.
binding.resolve(definitions)
p.binding = binding
filtered.append(p)
self.ports = filtered | python | def do_resolve(self, definitions):
"""
Resolve named references to other WSDL objects. Ports without SOAP
bindings are discarded.
@param definitions: A definitions object.
@type definitions: L{Definitions}
"""
filtered = []
for p in self.ports:
ref = qualify(p.binding, self.root, definitions.tns)
binding = definitions.bindings.get(ref)
if binding is None:
raise Exception("binding '%s', not-found" % (p.binding,))
if binding.soap is None:
log.debug("binding '%s' - not a SOAP binding, discarded",
binding.name)
continue
# After we have been resolved, our caller will expect that the
# binding we are referencing has been fully constructed, i.e.
# resolved, as well. The only scenario where the operations binding
# might possibly not have already resolved its references, and
# where this explicit resolve() call is required, is if we are
# dealing with a recursive WSDL import chain.
binding.resolve(definitions)
p.binding = binding
filtered.append(p)
self.ports = filtered | Resolve named references to other WSDL objects. Ports without SOAP
bindings are discarded.
@param definitions: A definitions object.
@type definitions: L{Definitions} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/wsdl.py#L939-L967 |
suds-community/suds | suds/wsdl.py | Factory.create | def create(cls, root, definitions):
"""
Create an object based on the root tag name.
@param root: An XML root element.
@type root: L{Element}
@param definitions: A definitions object.
@type definitions: L{Definitions}
@return: The created object.
@rtype: L{WObject}
"""
fn = cls.tags.get(root.name)
if fn is not None:
return fn(root, definitions) | python | def create(cls, root, definitions):
"""
Create an object based on the root tag name.
@param root: An XML root element.
@type root: L{Element}
@param definitions: A definitions object.
@type definitions: L{Definitions}
@return: The created object.
@rtype: L{WObject}
"""
fn = cls.tags.get(root.name)
if fn is not None:
return fn(root, definitions) | Create an object based on the root tag name.
@param root: An XML root element.
@type root: L{Element}
@param definitions: A definitions object.
@type definitions: L{Definitions}
@return: The created object.
@rtype: L{WObject} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/wsdl.py#L991-L1005 |
suds-community/suds | suds/bindings/binding.py | Binding.get_reply | def get_reply(self, method, replyroot):
"""
Process the I{reply} for the specified I{method} by unmarshalling it
into into Python object(s).
@param method: The name of the invoked method.
@type method: str
@param replyroot: The reply XML root node received after invoking the
specified method.
@type replyroot: L{Element}
@return: The unmarshalled reply. The returned value is an L{Object} or
a I{list} depending on whether the service returns a single object
or a collection.
@rtype: L{Object} or I{list}
"""
soapenv = replyroot.getChild("Envelope", envns)
soapenv.promotePrefixes()
soapbody = soapenv.getChild("Body", envns)
soapbody = self.multiref.process(soapbody)
nodes = self.replycontent(method, soapbody)
rtypes = self.returned_types(method)
if len(rtypes) > 1:
return self.replycomposite(rtypes, nodes)
if len(rtypes) == 0:
return
if rtypes[0].multi_occurrence():
return self.replylist(rtypes[0], nodes)
if len(nodes):
resolved = rtypes[0].resolve(nobuiltin=True)
return self.unmarshaller().process(nodes[0], resolved) | python | def get_reply(self, method, replyroot):
"""
Process the I{reply} for the specified I{method} by unmarshalling it
into into Python object(s).
@param method: The name of the invoked method.
@type method: str
@param replyroot: The reply XML root node received after invoking the
specified method.
@type replyroot: L{Element}
@return: The unmarshalled reply. The returned value is an L{Object} or
a I{list} depending on whether the service returns a single object
or a collection.
@rtype: L{Object} or I{list}
"""
soapenv = replyroot.getChild("Envelope", envns)
soapenv.promotePrefixes()
soapbody = soapenv.getChild("Body", envns)
soapbody = self.multiref.process(soapbody)
nodes = self.replycontent(method, soapbody)
rtypes = self.returned_types(method)
if len(rtypes) > 1:
return self.replycomposite(rtypes, nodes)
if len(rtypes) == 0:
return
if rtypes[0].multi_occurrence():
return self.replylist(rtypes[0], nodes)
if len(nodes):
resolved = rtypes[0].resolve(nobuiltin=True)
return self.unmarshaller().process(nodes[0], resolved) | Process the I{reply} for the specified I{method} by unmarshalling it
into into Python object(s).
@param method: The name of the invoked method.
@type method: str
@param replyroot: The reply XML root node received after invoking the
specified method.
@type replyroot: L{Element}
@return: The unmarshalled reply. The returned value is an L{Object} or
a I{list} depending on whether the service returns a single object
or a collection.
@rtype: L{Object} or I{list} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/bindings/binding.py#L132-L162 |
suds-community/suds | suds/bindings/binding.py | Binding.replylist | def replylist(self, rt, nodes):
"""
Construct a I{list} reply.
Called for replies with possible multiple occurrences.
@param rt: The return I{type}.
@type rt: L{suds.xsd.sxbase.SchemaObject}
@param nodes: A collection of XML nodes.
@type nodes: [L{Element},...]
@return: A list of I{unmarshalled} objects.
@rtype: [L{Object},...]
"""
resolved = rt.resolve(nobuiltin=True)
unmarshaller = self.unmarshaller()
return [unmarshaller.process(node, resolved) for node in nodes] | python | def replylist(self, rt, nodes):
"""
Construct a I{list} reply.
Called for replies with possible multiple occurrences.
@param rt: The return I{type}.
@type rt: L{suds.xsd.sxbase.SchemaObject}
@param nodes: A collection of XML nodes.
@type nodes: [L{Element},...]
@return: A list of I{unmarshalled} objects.
@rtype: [L{Object},...]
"""
resolved = rt.resolve(nobuiltin=True)
unmarshaller = self.unmarshaller()
return [unmarshaller.process(node, resolved) for node in nodes] | Construct a I{list} reply.
Called for replies with possible multiple occurrences.
@param rt: The return I{type}.
@type rt: L{suds.xsd.sxbase.SchemaObject}
@param nodes: A collection of XML nodes.
@type nodes: [L{Element},...]
@return: A list of I{unmarshalled} objects.
@rtype: [L{Object},...] | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/bindings/binding.py#L164-L180 |
suds-community/suds | suds/bindings/binding.py | Binding.mkheader | def mkheader(self, method, hdef, object):
"""
Builds a soapheader for the specified I{method} using the header
definition (hdef) and the specified value (object).
@param method: A method name.
@type method: str
@param hdef: A header definition.
@type hdef: tuple: (I{name}, L{xsd.sxbase.SchemaObject})
@param object: The header value.
@type object: any
@return: The parameter fragment.
@rtype: L{Element}
"""
marshaller = self.marshaller()
if isinstance(object, (list, tuple)):
return [self.mkheader(method, hdef, item) for item in object]
content = Content(tag=hdef[0], value=object, type=hdef[1])
return marshaller.process(content) | python | def mkheader(self, method, hdef, object):
"""
Builds a soapheader for the specified I{method} using the header
definition (hdef) and the specified value (object).
@param method: A method name.
@type method: str
@param hdef: A header definition.
@type hdef: tuple: (I{name}, L{xsd.sxbase.SchemaObject})
@param object: The header value.
@type object: any
@return: The parameter fragment.
@rtype: L{Element}
"""
marshaller = self.marshaller()
if isinstance(object, (list, tuple)):
return [self.mkheader(method, hdef, item) for item in object]
content = Content(tag=hdef[0], value=object, type=hdef[1])
return marshaller.process(content) | Builds a soapheader for the specified I{method} using the header
definition (hdef) and the specified value (object).
@param method: A method name.
@type method: str
@param hdef: A header definition.
@type hdef: tuple: (I{name}, L{xsd.sxbase.SchemaObject})
@param object: The header value.
@type object: any
@return: The parameter fragment.
@rtype: L{Element} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/bindings/binding.py#L246-L265 |
suds-community/suds | suds/bindings/binding.py | Binding.envelope | def envelope(self, header, body):
"""
Build the B{<Envelope/>} for a SOAP outbound message.
@param header: The SOAP message B{header}.
@type header: L{Element}
@param body: The SOAP message B{body}.
@type body: L{Element}
@return: The SOAP envelope containing the body and header.
@rtype: L{Element}
"""
env = Element("Envelope", ns=envns)
env.addPrefix(Namespace.xsins[0], Namespace.xsins[1])
env.append(header)
env.append(body)
return env | python | def envelope(self, header, body):
"""
Build the B{<Envelope/>} for a SOAP outbound message.
@param header: The SOAP message B{header}.
@type header: L{Element}
@param body: The SOAP message B{body}.
@type body: L{Element}
@return: The SOAP envelope containing the body and header.
@rtype: L{Element}
"""
env = Element("Envelope", ns=envns)
env.addPrefix(Namespace.xsins[0], Namespace.xsins[1])
env.append(header)
env.append(body)
return env | Build the B{<Envelope/>} for a SOAP outbound message.
@param header: The SOAP message B{header}.
@type header: L{Element}
@param body: The SOAP message B{body}.
@type body: L{Element}
@return: The SOAP envelope containing the body and header.
@rtype: L{Element} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/bindings/binding.py#L267-L283 |
suds-community/suds | suds/bindings/binding.py | Binding.header | def header(self, content):
"""
Build the B{<Body/>} for a SOAP outbound message.
@param content: The header content.
@type content: L{Element}
@return: The SOAP body fragment.
@rtype: L{Element}
"""
header = Element("Header", ns=envns)
header.append(content)
return header | python | def header(self, content):
"""
Build the B{<Body/>} for a SOAP outbound message.
@param content: The header content.
@type content: L{Element}
@return: The SOAP body fragment.
@rtype: L{Element}
"""
header = Element("Header", ns=envns)
header.append(content)
return header | Build the B{<Body/>} for a SOAP outbound message.
@param content: The header content.
@type content: L{Element}
@return: The SOAP body fragment.
@rtype: L{Element} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/bindings/binding.py#L285-L297 |
suds-community/suds | suds/bindings/binding.py | Binding.headercontent | def headercontent(self, method):
"""
Get the content for the SOAP I{Header} node.
@param method: A service method.
@type method: I{service.Method}
@return: The XML content for the <body/>.
@rtype: [L{Element},...]
"""
content = []
wsse = self.options().wsse
if wsse is not None:
content.append(wsse.xml())
headers = self.options().soapheaders
if not isinstance(headers, (tuple, list, dict)):
headers = (headers,)
elif not headers:
return content
pts = self.headpart_types(method)
if isinstance(headers, (tuple, list)):
n = 0
for header in headers:
if isinstance(header, Element):
content.append(deepcopy(header))
continue
if len(pts) == n:
break
h = self.mkheader(method, pts[n], header)
ns = pts[n][1].namespace("ns0")
h.setPrefix(ns[0], ns[1])
content.append(h)
n += 1
else:
for pt in pts:
header = headers.get(pt[0])
if header is None:
continue
h = self.mkheader(method, pt, header)
ns = pt[1].namespace("ns0")
h.setPrefix(ns[0], ns[1])
content.append(h)
return content | python | def headercontent(self, method):
"""
Get the content for the SOAP I{Header} node.
@param method: A service method.
@type method: I{service.Method}
@return: The XML content for the <body/>.
@rtype: [L{Element},...]
"""
content = []
wsse = self.options().wsse
if wsse is not None:
content.append(wsse.xml())
headers = self.options().soapheaders
if not isinstance(headers, (tuple, list, dict)):
headers = (headers,)
elif not headers:
return content
pts = self.headpart_types(method)
if isinstance(headers, (tuple, list)):
n = 0
for header in headers:
if isinstance(header, Element):
content.append(deepcopy(header))
continue
if len(pts) == n:
break
h = self.mkheader(method, pts[n], header)
ns = pts[n][1].namespace("ns0")
h.setPrefix(ns[0], ns[1])
content.append(h)
n += 1
else:
for pt in pts:
header = headers.get(pt[0])
if header is None:
continue
h = self.mkheader(method, pt, header)
ns = pt[1].namespace("ns0")
h.setPrefix(ns[0], ns[1])
content.append(h)
return content | Get the content for the SOAP I{Header} node.
@param method: A service method.
@type method: I{service.Method}
@return: The XML content for the <body/>.
@rtype: [L{Element},...] | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/bindings/binding.py#L315-L357 |
suds-community/suds | suds/bindings/binding.py | Binding.bodypart_types | def bodypart_types(self, method, input=True):
"""
Get a list of I{parameter definitions} (pdefs) defined for the
specified method.
An input I{pdef} is a (I{name}, L{xsd.sxbase.SchemaObject}) tuple,
while an output I{pdef} is a L{xsd.sxbase.SchemaObject}.
@param method: A service method.
@type method: I{service.Method}
@param input: Defines input/output message.
@type input: boolean
@return: A list of parameter definitions
@rtype: [I{pdef},...]
"""
if input:
parts = method.soap.input.body.parts
else:
parts = method.soap.output.body.parts
return [self.__part_type(p, input) for p in parts] | python | def bodypart_types(self, method, input=True):
"""
Get a list of I{parameter definitions} (pdefs) defined for the
specified method.
An input I{pdef} is a (I{name}, L{xsd.sxbase.SchemaObject}) tuple,
while an output I{pdef} is a L{xsd.sxbase.SchemaObject}.
@param method: A service method.
@type method: I{service.Method}
@param input: Defines input/output message.
@type input: boolean
@return: A list of parameter definitions
@rtype: [I{pdef},...]
"""
if input:
parts = method.soap.input.body.parts
else:
parts = method.soap.output.body.parts
return [self.__part_type(p, input) for p in parts] | Get a list of I{parameter definitions} (pdefs) defined for the
specified method.
An input I{pdef} is a (I{name}, L{xsd.sxbase.SchemaObject}) tuple,
while an output I{pdef} is a L{xsd.sxbase.SchemaObject}.
@param method: A service method.
@type method: I{service.Method}
@param input: Defines input/output message.
@type input: boolean
@return: A list of parameter definitions
@rtype: [I{pdef},...] | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/bindings/binding.py#L387-L407 |
suds-community/suds | suds/bindings/binding.py | Binding.headpart_types | def headpart_types(self, method, input=True):
"""
Get a list of header I{parameter definitions} (pdefs) defined for the
specified method.
An input I{pdef} is a (I{name}, L{xsd.sxbase.SchemaObject}) tuple,
while an output I{pdef} is a L{xsd.sxbase.SchemaObject}.
@param method: A service method.
@type method: I{service.Method}
@param input: Defines input/output message.
@type input: boolean
@return: A list of parameter definitions
@rtype: [I{pdef},...]
"""
if input:
headers = method.soap.input.headers
else:
headers = method.soap.output.headers
return [self.__part_type(h.part, input) for h in headers] | python | def headpart_types(self, method, input=True):
"""
Get a list of header I{parameter definitions} (pdefs) defined for the
specified method.
An input I{pdef} is a (I{name}, L{xsd.sxbase.SchemaObject}) tuple,
while an output I{pdef} is a L{xsd.sxbase.SchemaObject}.
@param method: A service method.
@type method: I{service.Method}
@param input: Defines input/output message.
@type input: boolean
@return: A list of parameter definitions
@rtype: [I{pdef},...]
"""
if input:
headers = method.soap.input.headers
else:
headers = method.soap.output.headers
return [self.__part_type(h.part, input) for h in headers] | Get a list of header I{parameter definitions} (pdefs) defined for the
specified method.
An input I{pdef} is a (I{name}, L{xsd.sxbase.SchemaObject}) tuple,
while an output I{pdef} is a L{xsd.sxbase.SchemaObject}.
@param method: A service method.
@type method: I{service.Method}
@param input: Defines input/output message.
@type input: boolean
@return: A list of parameter definitions
@rtype: [I{pdef},...] | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/bindings/binding.py#L409-L429 |
suds-community/suds | suds/bindings/binding.py | Binding.__part_type | def __part_type(self, part, input):
"""
Get a I{parameter definition} (pdef) defined for a given body or header
message part.
An input I{pdef} is a (I{name}, L{xsd.sxbase.SchemaObject}) tuple,
while an output I{pdef} is a L{xsd.sxbase.SchemaObject}.
@param part: A service method input or output part.
@type part: I{suds.wsdl.Part}
@param input: Defines input/output message.
@type input: boolean
@return: A list of parameter definitions
@rtype: [I{pdef},...]
"""
if part.element is None:
query = TypeQuery(part.type)
else:
query = ElementQuery(part.element)
part_type = query.execute(self.schema())
if part_type is None:
raise TypeNotFound(query.ref)
if part.type is not None:
part_type = PartElement(part.name, part_type)
if not input:
return part_type
if part_type.name is None:
return part.name, part_type
return part_type.name, part_type | python | def __part_type(self, part, input):
"""
Get a I{parameter definition} (pdef) defined for a given body or header
message part.
An input I{pdef} is a (I{name}, L{xsd.sxbase.SchemaObject}) tuple,
while an output I{pdef} is a L{xsd.sxbase.SchemaObject}.
@param part: A service method input or output part.
@type part: I{suds.wsdl.Part}
@param input: Defines input/output message.
@type input: boolean
@return: A list of parameter definitions
@rtype: [I{pdef},...]
"""
if part.element is None:
query = TypeQuery(part.type)
else:
query = ElementQuery(part.element)
part_type = query.execute(self.schema())
if part_type is None:
raise TypeNotFound(query.ref)
if part.type is not None:
part_type = PartElement(part.name, part_type)
if not input:
return part_type
if part_type.name is None:
return part.name, part_type
return part_type.name, part_type | Get a I{parameter definition} (pdef) defined for a given body or header
message part.
An input I{pdef} is a (I{name}, L{xsd.sxbase.SchemaObject}) tuple,
while an output I{pdef} is a L{xsd.sxbase.SchemaObject}.
@param part: A service method input or output part.
@type part: I{suds.wsdl.Part}
@param input: Defines input/output message.
@type input: boolean
@return: A list of parameter definitions
@rtype: [I{pdef},...] | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/bindings/binding.py#L443-L472 |
suds-community/suds | suds/mx/typer.py | Typer.auto | def auto(cls, node, value=None):
"""
Automatically set the node's xsi:type attribute based on either
I{value}'s or the node text's class. When I{value} is an unmapped
class, the default type (xs:any) is set.
@param node: XML node.
@type node: L{sax.element.Element}
@param value: Object that is or would be the node's text.
@type value: I{any}
@return: Specified node.
@rtype: L{sax.element.Element}
"""
if value is None:
value = node.getText()
if isinstance(value, Object):
known = cls.known(value)
if known.name is None:
return node
tm = known.name, known.namespace()
else:
tm = cls.types.get(value.__class__, cls.types.get(str))
cls.manual(node, *tm)
return node | python | def auto(cls, node, value=None):
"""
Automatically set the node's xsi:type attribute based on either
I{value}'s or the node text's class. When I{value} is an unmapped
class, the default type (xs:any) is set.
@param node: XML node.
@type node: L{sax.element.Element}
@param value: Object that is or would be the node's text.
@type value: I{any}
@return: Specified node.
@rtype: L{sax.element.Element}
"""
if value is None:
value = node.getText()
if isinstance(value, Object):
known = cls.known(value)
if known.name is None:
return node
tm = known.name, known.namespace()
else:
tm = cls.types.get(value.__class__, cls.types.get(str))
cls.manual(node, *tm)
return node | Automatically set the node's xsi:type attribute based on either
I{value}'s or the node text's class. When I{value} is an unmapped
class, the default type (xs:any) is set.
@param node: XML node.
@type node: L{sax.element.Element}
@param value: Object that is or would be the node's text.
@type value: I{any}
@return: Specified node.
@rtype: L{sax.element.Element} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/mx/typer.py#L45-L69 |
suds-community/suds | suds/mx/typer.py | Typer.manual | def manual(cls, node, tval, ns=None):
"""
Set the node's xsi:type attribute based on either I{value}'s or the
node text's class. Then adds the referenced prefix(s) to the node's
prefix mapping.
@param node: XML node.
@type node: L{sax.element.Element}
@param tval: XSD schema type name.
@type tval: str
@param ns: I{tval} XML namespace.
@type ns: (prefix, URI)
@return: Specified node.
@rtype: L{sax.element.Element}
"""
xta = ":".join((Namespace.xsins[0], "type"))
node.addPrefix(Namespace.xsins[0], Namespace.xsins[1])
if ns is None:
node.set(xta, tval)
else:
ns = cls.genprefix(node, ns)
qname = ":".join((ns[0], tval))
node.set(xta, qname)
node.addPrefix(ns[0], ns[1])
return node | python | def manual(cls, node, tval, ns=None):
"""
Set the node's xsi:type attribute based on either I{value}'s or the
node text's class. Then adds the referenced prefix(s) to the node's
prefix mapping.
@param node: XML node.
@type node: L{sax.element.Element}
@param tval: XSD schema type name.
@type tval: str
@param ns: I{tval} XML namespace.
@type ns: (prefix, URI)
@return: Specified node.
@rtype: L{sax.element.Element}
"""
xta = ":".join((Namespace.xsins[0], "type"))
node.addPrefix(Namespace.xsins[0], Namespace.xsins[1])
if ns is None:
node.set(xta, tval)
else:
ns = cls.genprefix(node, ns)
qname = ":".join((ns[0], tval))
node.set(xta, qname)
node.addPrefix(ns[0], ns[1])
return node | Set the node's xsi:type attribute based on either I{value}'s or the
node text's class. Then adds the referenced prefix(s) to the node's
prefix mapping.
@param node: XML node.
@type node: L{sax.element.Element}
@param tval: XSD schema type name.
@type tval: str
@param ns: I{tval} XML namespace.
@type ns: (prefix, URI)
@return: Specified node.
@rtype: L{sax.element.Element} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/mx/typer.py#L72-L97 |
suds-community/suds | suds/mx/typer.py | Typer.genprefix | def genprefix(cls, node, ns):
"""
Generate a prefix.
@param node: XML node on which the prefix will be used.
@type node: L{sax.element.Element}
@param ns: Namespace needing a unique prefix.
@type ns: (prefix, URI)
@return: I{ns} with a new prefix.
@rtype: (prefix, URI)
"""
for i in range(1, 1024):
prefix = "ns%d" % (i,)
uri = node.resolvePrefix(prefix, default=None)
if uri in (None, ns[1]):
return prefix, ns[1]
raise Exception("auto prefix, exhausted") | python | def genprefix(cls, node, ns):
"""
Generate a prefix.
@param node: XML node on which the prefix will be used.
@type node: L{sax.element.Element}
@param ns: Namespace needing a unique prefix.
@type ns: (prefix, URI)
@return: I{ns} with a new prefix.
@rtype: (prefix, URI)
"""
for i in range(1, 1024):
prefix = "ns%d" % (i,)
uri = node.resolvePrefix(prefix, default=None)
if uri in (None, ns[1]):
return prefix, ns[1]
raise Exception("auto prefix, exhausted") | Generate a prefix.
@param node: XML node on which the prefix will be used.
@type node: L{sax.element.Element}
@param ns: Namespace needing a unique prefix.
@type ns: (prefix, URI)
@return: I{ns} with a new prefix.
@rtype: (prefix, URI) | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/mx/typer.py#L100-L117 |
suds-community/suds | suds/cache.py | FileCache._getf | def _getf(self, id):
"""Open a cached file with the given id for reading."""
try:
filename = self.__filename(id)
self.__remove_if_expired(filename)
return self.__open(filename, "rb")
except Exception:
pass | python | def _getf(self, id):
"""Open a cached file with the given id for reading."""
try:
filename = self.__filename(id)
self.__remove_if_expired(filename)
return self.__open(filename, "rb")
except Exception:
pass | Open a cached file with the given id for reading. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/cache.py#L182-L189 |
suds-community/suds | suds/cache.py | FileCache.__filename | def __filename(self, id):
"""Return the cache file name for an entry with a given id."""
suffix = self.fnsuffix()
filename = "%s-%s.%s" % (self.fnprefix, id, suffix)
return os.path.join(self.location, filename) | python | def __filename(self, id):
"""Return the cache file name for an entry with a given id."""
suffix = self.fnsuffix()
filename = "%s-%s.%s" % (self.fnprefix, id, suffix)
return os.path.join(self.location, filename) | Return the cache file name for an entry with a given id. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/cache.py#L209-L213 |
suds-community/suds | suds/cache.py | FileCache.__get_default_location | def __get_default_location():
"""
Returns the current process's default cache location folder.
The folder is determined lazily on first call.
"""
if not FileCache.__default_location:
tmp = tempfile.mkdtemp("suds-default-cache")
FileCache.__default_location = tmp
import atexit
atexit.register(FileCache.__remove_default_location)
return FileCache.__default_location | python | def __get_default_location():
"""
Returns the current process's default cache location folder.
The folder is determined lazily on first call.
"""
if not FileCache.__default_location:
tmp = tempfile.mkdtemp("suds-default-cache")
FileCache.__default_location = tmp
import atexit
atexit.register(FileCache.__remove_default_location)
return FileCache.__default_location | Returns the current process's default cache location folder.
The folder is determined lazily on first call. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/cache.py#L216-L228 |
suds-community/suds | suds/cache.py | FileCache.__mktmp | def __mktmp(self):
"""Create the I{location} folder if it does not already exist."""
try:
if not os.path.isdir(self.location):
os.makedirs(self.location)
except Exception:
log.debug(self.location, exc_info=1)
return self | python | def __mktmp(self):
"""Create the I{location} folder if it does not already exist."""
try:
if not os.path.isdir(self.location):
os.makedirs(self.location)
except Exception:
log.debug(self.location, exc_info=1)
return self | Create the I{location} folder if it does not already exist. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/cache.py#L230-L237 |
suds-community/suds | suds/cache.py | FileCache.__remove_if_expired | def __remove_if_expired(self, filename):
"""
Remove a cached file entry if it expired.
@param filename: The file name.
@type filename: str
"""
if not self.duration:
return
created = datetime.datetime.fromtimestamp(os.path.getctime(filename))
expired = created + self.duration
if expired < datetime.datetime.now():
os.remove(filename)
log.debug("%s expired, deleted", filename) | python | def __remove_if_expired(self, filename):
"""
Remove a cached file entry if it expired.
@param filename: The file name.
@type filename: str
"""
if not self.duration:
return
created = datetime.datetime.fromtimestamp(os.path.getctime(filename))
expired = created + self.duration
if expired < datetime.datetime.now():
os.remove(filename)
log.debug("%s expired, deleted", filename) | Remove a cached file entry if it expired.
@param filename: The file name.
@type filename: str | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/cache.py#L261-L275 |
suds-community/suds | suds/xsd/doctor.py | TnsFilter.match | def match(self, root, ns):
"""
Match by I{targetNamespace} excluding those that
are equal to the specified namespace to prevent
adding an import to itself.
@param root: A schema root.
@type root: L{Element}
"""
tns = root.get('targetNamespace')
if len(self.tns):
matched = ( tns in self.tns )
else:
matched = 1
itself = ( ns == tns )
return ( matched and not itself ) | python | def match(self, root, ns):
"""
Match by I{targetNamespace} excluding those that
are equal to the specified namespace to prevent
adding an import to itself.
@param root: A schema root.
@type root: L{Element}
"""
tns = root.get('targetNamespace')
if len(self.tns):
matched = ( tns in self.tns )
else:
matched = 1
itself = ( ns == tns )
return ( matched and not itself ) | Match by I{targetNamespace} excluding those that
are equal to the specified namespace to prevent
adding an import to itself.
@param root: A schema root.
@type root: L{Element} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/xsd/doctor.py#L90-L104 |
suds-community/suds | suds/transport/http.py | HttpTransport.u2opener | def u2opener(self):
"""
Create a urllib opener.
@return: An opener.
@rtype: I{OpenerDirector}
"""
if self.urlopener is None:
return urllib2.build_opener(*self.u2handlers())
return self.urlopener | python | def u2opener(self):
"""
Create a urllib opener.
@return: An opener.
@rtype: I{OpenerDirector}
"""
if self.urlopener is None:
return urllib2.build_opener(*self.u2handlers())
return self.urlopener | Create a urllib opener.
@return: An opener.
@rtype: I{OpenerDirector} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/transport/http.py#L130-L140 |
suds-community/suds | suds/transport/http.py | HttpTransport.u2ver | def u2ver(self):
"""
Get the major/minor version of the urllib2 lib.
@return: The urllib2 version.
@rtype: float
"""
try:
part = urllib2.__version__.split('.', 1)
return float('.'.join(part))
except Exception, e:
log.exception(e)
return 0 | python | def u2ver(self):
"""
Get the major/minor version of the urllib2 lib.
@return: The urllib2 version.
@rtype: float
"""
try:
part = urllib2.__version__.split('.', 1)
return float('.'.join(part))
except Exception, e:
log.exception(e)
return 0 | Get the major/minor version of the urllib2 lib.
@return: The urllib2 version.
@rtype: float | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/transport/http.py#L152-L165 |
suds-community/suds | tools/suds_devel/utility.py | any_contains_any | def any_contains_any(strings, candidates):
"""Whether any of the strings contains any of the candidates."""
for string in strings:
for c in candidates:
if c in string:
return True | python | def any_contains_any(strings, candidates):
"""Whether any of the strings contains any of the candidates."""
for string in strings:
for c in candidates:
if c in string:
return True | Whether any of the strings contains any of the candidates. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/suds_devel/utility.py#L32-L37 |
suds-community/suds | tools/suds_devel/utility.py | path_to_URL | def path_to_URL(path, escape=True):
"""Convert a local file path to a absolute path file protocol URL."""
# We do not use urllib's builtin pathname2url() function since:
# - it has been commented with 'not recommended for general use'
# - it does not seem to work the same on Windows and non-Windows platforms
# (result starts with /// on Windows but does not on others)
# - urllib implementation prior to Python 2.5 used to quote ':' characters
# as '|' which would confuse pip on Windows.
url = os.path.abspath(path)
for sep in (os.sep, os.altsep):
if sep and sep != "/":
url = url.replace(sep, "/")
if escape:
# Must not escape ':' or '/' or Python will not recognize those URLs
# correctly. Detected on Windows 7 SP1 x64 with Python 3.4.0, but doing
# this always does not hurt since both are valid ASCII characters.
no_protocol_URL = url_quote(url, safe=":/")
else:
no_protocol_URL = url
return "file:///%s" % (no_protocol_URL,) | python | def path_to_URL(path, escape=True):
"""Convert a local file path to a absolute path file protocol URL."""
# We do not use urllib's builtin pathname2url() function since:
# - it has been commented with 'not recommended for general use'
# - it does not seem to work the same on Windows and non-Windows platforms
# (result starts with /// on Windows but does not on others)
# - urllib implementation prior to Python 2.5 used to quote ':' characters
# as '|' which would confuse pip on Windows.
url = os.path.abspath(path)
for sep in (os.sep, os.altsep):
if sep and sep != "/":
url = url.replace(sep, "/")
if escape:
# Must not escape ':' or '/' or Python will not recognize those URLs
# correctly. Detected on Windows 7 SP1 x64 with Python 3.4.0, but doing
# this always does not hurt since both are valid ASCII characters.
no_protocol_URL = url_quote(url, safe=":/")
else:
no_protocol_URL = url
return "file:///%s" % (no_protocol_URL,) | Convert a local file path to a absolute path file protocol URL. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/suds_devel/utility.py#L67-L86 |
suds-community/suds | tools/suds_devel/utility.py | requirement_spec | def requirement_spec(package_name, *args):
"""Identifier used when specifying a requirement to pip or setuptools."""
if not args or args == (None,):
return package_name
version_specs = []
for version_spec in args:
if isinstance(version_spec, (list, tuple)):
operator, version = version_spec
else:
assert isinstance(version_spec, str)
operator = "=="
version = version_spec
version_specs.append("%s%s" % (operator, version))
return "%s%s" % (package_name, ",".join(version_specs)) | python | def requirement_spec(package_name, *args):
"""Identifier used when specifying a requirement to pip or setuptools."""
if not args or args == (None,):
return package_name
version_specs = []
for version_spec in args:
if isinstance(version_spec, (list, tuple)):
operator, version = version_spec
else:
assert isinstance(version_spec, str)
operator = "=="
version = version_spec
version_specs.append("%s%s" % (operator, version))
return "%s%s" % (package_name, ",".join(version_specs)) | Identifier used when specifying a requirement to pip or setuptools. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/suds_devel/utility.py#L93-L106 |
suds-community/suds | tools/suds_devel/utility.py | script_folder | def script_folder(script_path):
"""
Return the given script's folder or None if it can not be determined.
Script is identified by its __file__ attribute. If the given __file__
attribute value contains no path information, it is expected to identify an
existing file in the current working folder.
Returned folder may be specified relative to the current working folder
and, if determined, will never be an empty string.
Typical use case for calling this function is from a regular stand-alone
script and not a frozen module or a module imported from the disk, a
zip-file, an external database or any other such source. Such callers can
safely assume they have a valid __file__ attribute available.
"""
# There exist modules whose __file__ attribute does not correspond directly
# to a disk file, e.g. modules imported from inside zip archives.
if os.path.isfile(script_path):
return _rel_path(os.path.dirname(script_path)) or "." | python | def script_folder(script_path):
"""
Return the given script's folder or None if it can not be determined.
Script is identified by its __file__ attribute. If the given __file__
attribute value contains no path information, it is expected to identify an
existing file in the current working folder.
Returned folder may be specified relative to the current working folder
and, if determined, will never be an empty string.
Typical use case for calling this function is from a regular stand-alone
script and not a frozen module or a module imported from the disk, a
zip-file, an external database or any other such source. Such callers can
safely assume they have a valid __file__ attribute available.
"""
# There exist modules whose __file__ attribute does not correspond directly
# to a disk file, e.g. modules imported from inside zip archives.
if os.path.isfile(script_path):
return _rel_path(os.path.dirname(script_path)) or "." | Return the given script's folder or None if it can not be determined.
Script is identified by its __file__ attribute. If the given __file__
attribute value contains no path information, it is expected to identify an
existing file in the current working folder.
Returned folder may be specified relative to the current working folder
and, if determined, will never be an empty string.
Typical use case for calling this function is from a regular stand-alone
script and not a frozen module or a module imported from the disk, a
zip-file, an external database or any other such source. Such callers can
safely assume they have a valid __file__ attribute available. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/suds_devel/utility.py#L124-L144 |
suds-community/suds | tools/suds_devel/utility.py | path_iter | def path_iter(path):
"""Returns an iterator over all the file & folder names in a path."""
parts = []
while path:
path, item = os.path.split(path)
if item:
parts.append(item)
return reversed(parts) | python | def path_iter(path):
"""Returns an iterator over all the file & folder names in a path."""
parts = []
while path:
path, item = os.path.split(path)
if item:
parts.append(item)
return reversed(parts) | Returns an iterator over all the file & folder names in a path. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/suds_devel/utility.py#L147-L154 |
suds-community/suds | suds/bindings/document.py | Document.document | def document(self, wrapper):
"""
Get the document root. For I{document/literal}, this is the name of the
wrapper element qualified by the schema's target namespace.
@param wrapper: The method name.
@type wrapper: L{xsd.sxbase.SchemaObject}
@return: A root element.
@rtype: L{Element}
"""
tag = wrapper[1].name
ns = wrapper[1].namespace("ns0")
return Element(tag, ns=ns) | python | def document(self, wrapper):
"""
Get the document root. For I{document/literal}, this is the name of the
wrapper element qualified by the schema's target namespace.
@param wrapper: The method name.
@type wrapper: L{xsd.sxbase.SchemaObject}
@return: A root element.
@rtype: L{Element}
"""
tag = wrapper[1].name
ns = wrapper[1].namespace("ns0")
return Element(tag, ns=ns) | Get the document root. For I{document/literal}, this is the name of the
wrapper element qualified by the schema's target namespace.
@param wrapper: The method name.
@type wrapper: L{xsd.sxbase.SchemaObject}
@return: A root element.
@rtype: L{Element} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/bindings/document.py#L105-L118 |
suds-community/suds | suds/bindings/document.py | Document.mkparam | def mkparam(self, method, pdef, object):
"""
Expand list parameters into individual parameters each with the type
information. This is because in document arrays are simply
multi-occurrence elements.
"""
if isinstance(object, (list, tuple)):
return [self.mkparam(method, pdef, item) for item in object]
return super(Document, self).mkparam(method, pdef, object) | python | def mkparam(self, method, pdef, object):
"""
Expand list parameters into individual parameters each with the type
information. This is because in document arrays are simply
multi-occurrence elements.
"""
if isinstance(object, (list, tuple)):
return [self.mkparam(method, pdef, item) for item in object]
return super(Document, self).mkparam(method, pdef, object) | Expand list parameters into individual parameters each with the type
information. This is because in document arrays are simply
multi-occurrence elements. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/bindings/document.py#L120-L129 |
suds-community/suds | suds/bindings/document.py | Document.param_defs | def param_defs(self, method):
"""Get parameter definitions for document literal."""
pts = self.bodypart_types(method)
if not method.soap.input.body.wrapped:
return pts
pt = pts[0][1].resolve()
return [(c.name, c, a) for c, a in pt if not c.isattr()] | python | def param_defs(self, method):
"""Get parameter definitions for document literal."""
pts = self.bodypart_types(method)
if not method.soap.input.body.wrapped:
return pts
pt = pts[0][1].resolve()
return [(c.name, c, a) for c, a in pt if not c.isattr()] | Get parameter definitions for document literal. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/bindings/document.py#L131-L137 |
suds-community/suds | suds/__init__.py | byte_str | def byte_str(s="", encoding="utf-8", input_encoding="utf-8", errors="strict"):
"""
Returns a byte string version of 's', encoded as specified in 'encoding'.
Accepts str & unicode objects, interpreting non-unicode strings as byte
strings encoded using the given input encoding.
"""
assert isinstance(s, basestring)
if isinstance(s, unicode):
return s.encode(encoding, errors)
if s and encoding != input_encoding:
return s.decode(input_encoding, errors).encode(encoding, errors)
return s | python | def byte_str(s="", encoding="utf-8", input_encoding="utf-8", errors="strict"):
"""
Returns a byte string version of 's', encoded as specified in 'encoding'.
Accepts str & unicode objects, interpreting non-unicode strings as byte
strings encoded using the given input encoding.
"""
assert isinstance(s, basestring)
if isinstance(s, unicode):
return s.encode(encoding, errors)
if s and encoding != input_encoding:
return s.decode(input_encoding, errors).encode(encoding, errors)
return s | Returns a byte string version of 's', encoded as specified in 'encoding'.
Accepts str & unicode objects, interpreting non-unicode strings as byte
strings encoded using the given input encoding. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/__init__.py#L144-L157 |
suds-community/suds | suds/sax/date.py | _bump_up_time_by_microsecond | def _bump_up_time_by_microsecond(time):
"""
Helper function bumping up the given datetime.time by a microsecond,
cycling around silently to 00:00:00.0 in case of an overflow.
@param time: Time object.
@type time: B{datetime}.I{time}
@return: Time object.
@rtype: B{datetime}.I{time}
"""
dt = datetime.datetime(2000, 1, 1, time.hour, time.minute,
time.second, time.microsecond)
dt += datetime.timedelta(microseconds=1)
return dt.time() | python | def _bump_up_time_by_microsecond(time):
"""
Helper function bumping up the given datetime.time by a microsecond,
cycling around silently to 00:00:00.0 in case of an overflow.
@param time: Time object.
@type time: B{datetime}.I{time}
@return: Time object.
@rtype: B{datetime}.I{time}
"""
dt = datetime.datetime(2000, 1, 1, time.hour, time.minute,
time.second, time.microsecond)
dt += datetime.timedelta(microseconds=1)
return dt.time() | Helper function bumping up the given datetime.time by a microsecond,
cycling around silently to 00:00:00.0 in case of an overflow.
@param time: Time object.
@type time: B{datetime}.I{time}
@return: Time object.
@rtype: B{datetime}.I{time} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/date.py#L356-L370 |
suds-community/suds | suds/sax/date.py | _date_from_match | def _date_from_match(match_object):
"""
Create a date object from a regular expression match.
The regular expression match is expected to be from _RE_DATE or
_RE_DATETIME.
@param match_object: The regular expression match.
@type match_object: B{re}.I{MatchObject}
@return: A date object.
@rtype: B{datetime}.I{date}
"""
year = int(match_object.group("year"))
month = int(match_object.group("month"))
day = int(match_object.group("day"))
return datetime.date(year, month, day) | python | def _date_from_match(match_object):
"""
Create a date object from a regular expression match.
The regular expression match is expected to be from _RE_DATE or
_RE_DATETIME.
@param match_object: The regular expression match.
@type match_object: B{re}.I{MatchObject}
@return: A date object.
@rtype: B{datetime}.I{date}
"""
year = int(match_object.group("year"))
month = int(match_object.group("month"))
day = int(match_object.group("day"))
return datetime.date(year, month, day) | Create a date object from a regular expression match.
The regular expression match is expected to be from _RE_DATE or
_RE_DATETIME.
@param match_object: The regular expression match.
@type match_object: B{re}.I{MatchObject}
@return: A date object.
@rtype: B{datetime}.I{date} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/date.py#L373-L389 |
suds-community/suds | suds/sax/date.py | _time_from_match | def _time_from_match(match_object):
"""
Create a time object from a regular expression match.
Returns the time object and information whether the resulting time should
be bumped up by one microsecond due to microsecond rounding.
Subsecond information is rounded to microseconds due to a restriction in
the python datetime.datetime/time implementation.
The regular expression match is expected to be from _RE_DATETIME or
_RE_TIME.
@param match_object: The regular expression match.
@type match_object: B{re}.I{MatchObject}
@return: Time object + rounding flag.
@rtype: tuple of B{datetime}.I{time} and bool
"""
hour = int(match_object.group('hour'))
minute = int(match_object.group('minute'))
second = int(match_object.group('second'))
subsecond = match_object.group('subsecond')
round_up = False
microsecond = 0
if subsecond:
round_up = len(subsecond) > 6 and int(subsecond[6]) >= 5
subsecond = subsecond[:6]
microsecond = int(subsecond + "0" * (6 - len(subsecond)))
return datetime.time(hour, minute, second, microsecond), round_up | python | def _time_from_match(match_object):
"""
Create a time object from a regular expression match.
Returns the time object and information whether the resulting time should
be bumped up by one microsecond due to microsecond rounding.
Subsecond information is rounded to microseconds due to a restriction in
the python datetime.datetime/time implementation.
The regular expression match is expected to be from _RE_DATETIME or
_RE_TIME.
@param match_object: The regular expression match.
@type match_object: B{re}.I{MatchObject}
@return: Time object + rounding flag.
@rtype: tuple of B{datetime}.I{time} and bool
"""
hour = int(match_object.group('hour'))
minute = int(match_object.group('minute'))
second = int(match_object.group('second'))
subsecond = match_object.group('subsecond')
round_up = False
microsecond = 0
if subsecond:
round_up = len(subsecond) > 6 and int(subsecond[6]) >= 5
subsecond = subsecond[:6]
microsecond = int(subsecond + "0" * (6 - len(subsecond)))
return datetime.time(hour, minute, second, microsecond), round_up | Create a time object from a regular expression match.
Returns the time object and information whether the resulting time should
be bumped up by one microsecond due to microsecond rounding.
Subsecond information is rounded to microseconds due to a restriction in
the python datetime.datetime/time implementation.
The regular expression match is expected to be from _RE_DATETIME or
_RE_TIME.
@param match_object: The regular expression match.
@type match_object: B{re}.I{MatchObject}
@return: Time object + rounding flag.
@rtype: tuple of B{datetime}.I{time} and bool | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/date.py#L392-L422 |
suds-community/suds | suds/sax/date.py | _tzinfo_from_match | def _tzinfo_from_match(match_object):
"""
Create a timezone information object from a regular expression match.
The regular expression match is expected to be from _RE_DATE, _RE_DATETIME
or _RE_TIME.
@param match_object: The regular expression match.
@type match_object: B{re}.I{MatchObject}
@return: A timezone information object.
@rtype: B{datetime}.I{tzinfo}
"""
tz_utc = match_object.group("tz_utc")
if tz_utc:
return UtcTimezone()
tz_sign = match_object.group("tz_sign")
if not tz_sign:
return
h = int(match_object.group("tz_hour") or 0)
m = int(match_object.group("tz_minute") or 0)
if h == 0 and m == 0:
return UtcTimezone()
# Python limitation - timezone offsets larger than one day (in absolute)
# will cause operations depending on tzinfo.utcoffset() to fail, e.g.
# comparing two timezone aware datetime.datetime/time objects.
if h >= 24:
raise ValueError("timezone indicator too large")
tz_delta = datetime.timedelta(hours=h, minutes=m)
if tz_sign == "-":
tz_delta *= -1
return FixedOffsetTimezone(tz_delta) | python | def _tzinfo_from_match(match_object):
"""
Create a timezone information object from a regular expression match.
The regular expression match is expected to be from _RE_DATE, _RE_DATETIME
or _RE_TIME.
@param match_object: The regular expression match.
@type match_object: B{re}.I{MatchObject}
@return: A timezone information object.
@rtype: B{datetime}.I{tzinfo}
"""
tz_utc = match_object.group("tz_utc")
if tz_utc:
return UtcTimezone()
tz_sign = match_object.group("tz_sign")
if not tz_sign:
return
h = int(match_object.group("tz_hour") or 0)
m = int(match_object.group("tz_minute") or 0)
if h == 0 and m == 0:
return UtcTimezone()
# Python limitation - timezone offsets larger than one day (in absolute)
# will cause operations depending on tzinfo.utcoffset() to fail, e.g.
# comparing two timezone aware datetime.datetime/time objects.
if h >= 24:
raise ValueError("timezone indicator too large")
tz_delta = datetime.timedelta(hours=h, minutes=m)
if tz_sign == "-":
tz_delta *= -1
return FixedOffsetTimezone(tz_delta) | Create a timezone information object from a regular expression match.
The regular expression match is expected to be from _RE_DATE, _RE_DATETIME
or _RE_TIME.
@param match_object: The regular expression match.
@type match_object: B{re}.I{MatchObject}
@return: A timezone information object.
@rtype: B{datetime}.I{tzinfo} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/date.py#L425-L460 |
suds-community/suds | suds/sax/date.py | Date.__parse | def __parse(value):
"""
Parse the string date.
Supports the subset of ISO8601 used by xsd:date, but is lenient with
what is accepted, handling most reasonable syntax.
Any timezone is parsed but ignored because a) it is meaningless without
a time and b) B{datetime}.I{date} does not support timezone
information.
@param value: A date string.
@type value: str
@return: A date object.
@rtype: B{datetime}.I{date}
"""
match_result = _RE_DATE.match(value)
if match_result is None:
raise ValueError("date data has invalid format '%s'" % (value,))
return _date_from_match(match_result) | python | def __parse(value):
"""
Parse the string date.
Supports the subset of ISO8601 used by xsd:date, but is lenient with
what is accepted, handling most reasonable syntax.
Any timezone is parsed but ignored because a) it is meaningless without
a time and b) B{datetime}.I{date} does not support timezone
information.
@param value: A date string.
@type value: str
@return: A date object.
@rtype: B{datetime}.I{date}
"""
match_result = _RE_DATE.match(value)
if match_result is None:
raise ValueError("date data has invalid format '%s'" % (value,))
return _date_from_match(match_result) | Parse the string date.
Supports the subset of ISO8601 used by xsd:date, but is lenient with
what is accepted, handling most reasonable syntax.
Any timezone is parsed but ignored because a) it is meaningless without
a time and b) B{datetime}.I{date} does not support timezone
information.
@param value: A date string.
@type value: str
@return: A date object.
@rtype: B{datetime}.I{date} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/date.py#L76-L96 |
suds-community/suds | suds/sax/date.py | DateTime.__parse | def __parse(value):
"""
Parse the string datetime.
Supports the subset of ISO8601 used by xsd:dateTime, but is lenient
with what is accepted, handling most reasonable syntax.
Subsecond information is rounded to microseconds due to a restriction
in the python datetime.datetime/time implementation.
@param value: A datetime string.
@type value: str
@return: A datetime object.
@rtype: B{datetime}.I{datetime}
"""
match_result = _RE_DATETIME.match(value)
if match_result is None:
raise ValueError("date data has invalid format '%s'" % (value,))
date = _date_from_match(match_result)
time, round_up = _time_from_match(match_result)
tzinfo = _tzinfo_from_match(match_result)
value = datetime.datetime.combine(date, time)
value = value.replace(tzinfo=tzinfo)
if round_up:
value += datetime.timedelta(microseconds=1)
return value | python | def __parse(value):
"""
Parse the string datetime.
Supports the subset of ISO8601 used by xsd:dateTime, but is lenient
with what is accepted, handling most reasonable syntax.
Subsecond information is rounded to microseconds due to a restriction
in the python datetime.datetime/time implementation.
@param value: A datetime string.
@type value: str
@return: A datetime object.
@rtype: B{datetime}.I{datetime}
"""
match_result = _RE_DATETIME.match(value)
if match_result is None:
raise ValueError("date data has invalid format '%s'" % (value,))
date = _date_from_match(match_result)
time, round_up = _time_from_match(match_result)
tzinfo = _tzinfo_from_match(match_result)
value = datetime.datetime.combine(date, time)
value = value.replace(tzinfo=tzinfo)
if round_up:
value += datetime.timedelta(microseconds=1)
return value | Parse the string datetime.
Supports the subset of ISO8601 used by xsd:dateTime, but is lenient
with what is accepted, handling most reasonable syntax.
Subsecond information is rounded to microseconds due to a restriction
in the python datetime.datetime/time implementation.
@param value: A datetime string.
@type value: str
@return: A datetime object.
@rtype: B{datetime}.I{datetime} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/date.py#L126-L154 |
suds-community/suds | suds/sax/date.py | Time.__parse | def __parse(value):
"""
Parse the string date.
Supports the subset of ISO8601 used by xsd:time, but is lenient with
what is accepted, handling most reasonable syntax.
Subsecond information is rounded to microseconds due to a restriction
in the python datetime.time implementation.
@param value: A time string.
@type value: str
@return: A time object.
@rtype: B{datetime}.I{time}
"""
match_result = _RE_TIME.match(value)
if match_result is None:
raise ValueError("date data has invalid format '%s'" % (value,))
time, round_up = _time_from_match(match_result)
tzinfo = _tzinfo_from_match(match_result)
if round_up:
time = _bump_up_time_by_microsecond(time)
return time.replace(tzinfo=tzinfo) | python | def __parse(value):
"""
Parse the string date.
Supports the subset of ISO8601 used by xsd:time, but is lenient with
what is accepted, handling most reasonable syntax.
Subsecond information is rounded to microseconds due to a restriction
in the python datetime.time implementation.
@param value: A time string.
@type value: str
@return: A time object.
@rtype: B{datetime}.I{time}
"""
match_result = _RE_TIME.match(value)
if match_result is None:
raise ValueError("date data has invalid format '%s'" % (value,))
time, round_up = _time_from_match(match_result)
tzinfo = _tzinfo_from_match(match_result)
if round_up:
time = _bump_up_time_by_microsecond(time)
return time.replace(tzinfo=tzinfo) | Parse the string date.
Supports the subset of ISO8601 used by xsd:time, but is lenient with
what is accepted, handling most reasonable syntax.
Subsecond information is rounded to microseconds due to a restriction
in the python datetime.time implementation.
@param value: A time string.
@type value: str
@return: A time object.
@rtype: B{datetime}.I{time} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/date.py#L184-L208 |
suds-community/suds | suds/sax/date.py | FixedOffsetTimezone.tzname | def tzname(self, dt):
"""
http://docs.python.org/library/datetime.html#datetime.tzinfo.tzname
"""
# total_seconds was introduced in Python 2.7
if hasattr(self.__offset, "total_seconds"):
total_seconds = self.__offset.total_seconds()
else:
total_seconds = (self.__offset.days * 24 * 60 * 60) + \
(self.__offset.seconds)
hours = total_seconds // (60 * 60)
total_seconds -= hours * 60 * 60
minutes = total_seconds // 60
total_seconds -= minutes * 60
seconds = total_seconds // 1
total_seconds -= seconds
if seconds:
return "%+03d:%02d:%02d" % (hours, minutes, seconds)
return "%+03d:%02d" % (hours, minutes) | python | def tzname(self, dt):
"""
http://docs.python.org/library/datetime.html#datetime.tzinfo.tzname
"""
# total_seconds was introduced in Python 2.7
if hasattr(self.__offset, "total_seconds"):
total_seconds = self.__offset.total_seconds()
else:
total_seconds = (self.__offset.days * 24 * 60 * 60) + \
(self.__offset.seconds)
hours = total_seconds // (60 * 60)
total_seconds -= hours * 60 * 60
minutes = total_seconds // 60
total_seconds -= minutes * 60
seconds = total_seconds // 1
total_seconds -= seconds
if seconds:
return "%+03d:%02d:%02d" % (hours, minutes, seconds)
return "%+03d:%02d" % (hours, minutes) | http://docs.python.org/library/datetime.html#datetime.tzinfo.tzname | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/date.py#L251-L274 |
suds-community/suds | suds/umx/core.py | Core.postprocess | def postprocess(self, content):
"""
Perform final processing of the resulting data structure as follows:
- Mixed values (children and text) will have a result of the I{content.node}.
- Simi-simple values (attributes, no-children and text) will have a result of a
property object.
- Simple values (no-attributes, no-children with text nodes) will have a string
result equal to the value of the content.node.getText().
@param content: The current content being unmarshalled.
@type content: L{Content}
@return: The post-processed result.
@rtype: I{any}
"""
node = content.node
if len(node.children) and node.hasText():
return node
attributes = AttrList(node.attributes)
if attributes.rlen() and \
not len(node.children) and \
node.hasText():
p = Factory.property(node.name, node.getText())
return merge(content.data, p)
if len(content.data):
return content.data
lang = attributes.lang()
if content.node.isnil():
return None
if not len(node.children) and content.text is None:
if self.nillable(content):
return None
else:
return Text('', lang=lang)
if isinstance(content.text, basestring):
return Text(content.text, lang=lang)
else:
return content.text | python | def postprocess(self, content):
"""
Perform final processing of the resulting data structure as follows:
- Mixed values (children and text) will have a result of the I{content.node}.
- Simi-simple values (attributes, no-children and text) will have a result of a
property object.
- Simple values (no-attributes, no-children with text nodes) will have a string
result equal to the value of the content.node.getText().
@param content: The current content being unmarshalled.
@type content: L{Content}
@return: The post-processed result.
@rtype: I{any}
"""
node = content.node
if len(node.children) and node.hasText():
return node
attributes = AttrList(node.attributes)
if attributes.rlen() and \
not len(node.children) and \
node.hasText():
p = Factory.property(node.name, node.getText())
return merge(content.data, p)
if len(content.data):
return content.data
lang = attributes.lang()
if content.node.isnil():
return None
if not len(node.children) and content.text is None:
if self.nillable(content):
return None
else:
return Text('', lang=lang)
if isinstance(content.text, basestring):
return Text(content.text, lang=lang)
else:
return content.text | Perform final processing of the resulting data structure as follows:
- Mixed values (children and text) will have a result of the I{content.node}.
- Simi-simple values (attributes, no-children and text) will have a result of a
property object.
- Simple values (no-attributes, no-children with text nodes) will have a string
result equal to the value of the content.node.getText().
@param content: The current content being unmarshalled.
@type content: L{Content}
@return: The post-processed result.
@rtype: I{any} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/umx/core.py#L66-L101 |
suds-community/suds | suds/umx/core.py | Core.append_children | def append_children(self, content):
"""
Append child nodes into L{Content.data}
@param content: The current content being unmarshalled.
@type content: L{Content}
"""
for child in content.node:
cont = Content(child)
cval = self.append(cont)
key = reserved.get(child.name, child.name)
if key in content.data:
v = getattr(content.data, key)
if isinstance(v, list):
v.append(cval)
else:
setattr(content.data, key, [v, cval])
continue
if self.multi_occurrence(cont):
if cval is None:
setattr(content.data, key, [])
else:
setattr(content.data, key, [cval,])
else:
setattr(content.data, key, cval) | python | def append_children(self, content):
"""
Append child nodes into L{Content.data}
@param content: The current content being unmarshalled.
@type content: L{Content}
"""
for child in content.node:
cont = Content(child)
cval = self.append(cont)
key = reserved.get(child.name, child.name)
if key in content.data:
v = getattr(content.data, key)
if isinstance(v, list):
v.append(cval)
else:
setattr(content.data, key, [v, cval])
continue
if self.multi_occurrence(cont):
if cval is None:
setattr(content.data, key, [])
else:
setattr(content.data, key, [cval,])
else:
setattr(content.data, key, cval) | Append child nodes into L{Content.data}
@param content: The current content being unmarshalled.
@type content: L{Content} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/umx/core.py#L130-L153 |
suds-community/suds | suds/client.py | _parse | def _parse(string):
"""
Parses given XML document content.
Returns the resulting root XML element node or None if the given XML
content is empty.
@param string: XML document content to parse.
@type string: I{bytes}
@return: Resulting root XML element node or None.
@rtype: L{Element}|I{None}
"""
if string:
return suds.sax.parser.Parser().parse(string=string) | python | def _parse(string):
"""
Parses given XML document content.
Returns the resulting root XML element node or None if the given XML
content is empty.
@param string: XML document content to parse.
@type string: I{bytes}
@return: Resulting root XML element node or None.
@rtype: L{Element}|I{None}
"""
if string:
return suds.sax.parser.Parser().parse(string=string) | Parses given XML document content.
Returns the resulting root XML element node or None if the given XML
content is empty.
@param string: XML document content to parse.
@type string: I{bytes}
@return: Resulting root XML element node or None.
@rtype: L{Element}|I{None} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/client.py#L933-L947 |
suds-community/suds | suds/client.py | Factory.create | def create(self, name):
"""
Create a WSDL type by name.
@param name: The name of a type defined in the WSDL.
@type name: str
@return: The requested object.
@rtype: L{Object}
"""
timer = metrics.Timer()
timer.start()
type = self.resolver.find(name)
if type is None:
raise TypeNotFound(name)
if type.enum():
result = sudsobject.Factory.object(name)
for e, a in type.children():
setattr(result, e.name, e.name)
else:
try:
result = self.builder.build(type)
except Exception, e:
log.error("create '%s' failed", name, exc_info=True)
raise BuildError(name, e)
timer.stop()
metrics.log.debug("%s created: %s", name, timer)
return result | python | def create(self, name):
"""
Create a WSDL type by name.
@param name: The name of a type defined in the WSDL.
@type name: str
@return: The requested object.
@rtype: L{Object}
"""
timer = metrics.Timer()
timer.start()
type = self.resolver.find(name)
if type is None:
raise TypeNotFound(name)
if type.enum():
result = sudsobject.Factory.object(name)
for e, a in type.children():
setattr(result, e.name, e.name)
else:
try:
result = self.builder.build(type)
except Exception, e:
log.error("create '%s' failed", name, exc_info=True)
raise BuildError(name, e)
timer.stop()
metrics.log.debug("%s created: %s", name, timer)
return result | Create a WSDL type by name.
@param name: The name of a type defined in the WSDL.
@type name: str
@return: The requested object.
@rtype: L{Object} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/client.py#L220-L247 |
suds-community/suds | suds/client.py | ServiceSelector.__find | def __find(self, name):
"""
Find a I{service} by name (string) or index (integer).
@param name: The name (or index) of a service.
@type name: int|str
@return: A L{PortSelector} for the found service.
@rtype: L{PortSelector}.
"""
service = None
if not self.__services:
raise Exception, "No services defined"
if isinstance(name, int):
try:
service = self.__services[name]
name = service.name
except IndexError:
raise ServiceNotFound, "at [%d]" % (name,)
else:
for s in self.__services:
if name == s.name:
service = s
break
if service is None:
raise ServiceNotFound, name
return PortSelector(self.__client, service.ports, name) | python | def __find(self, name):
"""
Find a I{service} by name (string) or index (integer).
@param name: The name (or index) of a service.
@type name: int|str
@return: A L{PortSelector} for the found service.
@rtype: L{PortSelector}.
"""
service = None
if not self.__services:
raise Exception, "No services defined"
if isinstance(name, int):
try:
service = self.__services[name]
name = service.name
except IndexError:
raise ServiceNotFound, "at [%d]" % (name,)
else:
for s in self.__services:
if name == s.name:
service = s
break
if service is None:
raise ServiceNotFound, name
return PortSelector(self.__client, service.ports, name) | Find a I{service} by name (string) or index (integer).
@param name: The name (or index) of a service.
@type name: int|str
@return: A L{PortSelector} for the found service.
@rtype: L{PortSelector}. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/client.py#L331-L357 |
suds-community/suds | suds/client.py | ServiceSelector.__ds | def __ds(self):
"""
Get the I{default} service if defined in the I{options}.
@return: A L{PortSelector} for the I{default} service.
@rtype: L{PortSelector}.
"""
ds = self.__client.options.service
if ds is not None:
return self.__find(ds) | python | def __ds(self):
"""
Get the I{default} service if defined in the I{options}.
@return: A L{PortSelector} for the I{default} service.
@rtype: L{PortSelector}.
"""
ds = self.__client.options.service
if ds is not None:
return self.__find(ds) | Get the I{default} service if defined in the I{options}.
@return: A L{PortSelector} for the I{default} service.
@rtype: L{PortSelector}. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/client.py#L359-L369 |
suds-community/suds | suds/client.py | RequestContext.process_reply | def process_reply(self, reply, status=None, description=None):
"""
Re-entry for processing a successful reply.
Depending on how the ``retxml`` option is set, may return the SOAP
reply XML or process it and return the Python object representing the
returned value.
@param reply: The SOAP reply envelope.
@type reply: I{bytes}
@param status: The HTTP status code.
@type status: int
@param description: Additional status description.
@type description: I{bytes}
@return: The invoked web service operation return value.
@rtype: I{builtin}|I{subclass of} L{Object}|I{bytes}|I{None}
"""
return self.__process_reply(reply, status, description) | python | def process_reply(self, reply, status=None, description=None):
"""
Re-entry for processing a successful reply.
Depending on how the ``retxml`` option is set, may return the SOAP
reply XML or process it and return the Python object representing the
returned value.
@param reply: The SOAP reply envelope.
@type reply: I{bytes}
@param status: The HTTP status code.
@type status: int
@param description: Additional status description.
@type description: I{bytes}
@return: The invoked web service operation return value.
@rtype: I{builtin}|I{subclass of} L{Object}|I{bytes}|I{None}
"""
return self.__process_reply(reply, status, description) | Re-entry for processing a successful reply.
Depending on how the ``retxml`` option is set, may return the SOAP
reply XML or process it and return the Python object representing the
returned value.
@param reply: The SOAP reply envelope.
@type reply: I{bytes}
@param status: The HTTP status code.
@type status: int
@param description: Additional status description.
@type description: I{bytes}
@return: The invoked web service operation return value.
@rtype: I{builtin}|I{subclass of} L{Object}|I{bytes}|I{None} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/client.py#L607-L625 |
suds-community/suds | suds/client.py | _SoapClient.send | def send(self, soapenv):
"""
Send SOAP message.
Depending on how the ``nosend`` & ``retxml`` options are set, may do
one of the following:
* Return a constructed web service operation request without sending
it to the web service.
* Invoke the web service operation and return its SOAP reply XML.
* Invoke the web service operation, process its results and return
the Python object representing the returned value.
@param soapenv: A SOAP envelope to send.
@type soapenv: L{Document}
@return: SOAP request, SOAP reply or a web service return value.
@rtype: L{RequestContext}|I{builtin}|I{subclass of} L{Object}|I{bytes}|
I{None}
"""
location = self.__location()
log.debug("sending to (%s)\nmessage:\n%s", location, soapenv)
plugins = PluginContainer(self.options.plugins)
plugins.message.marshalled(envelope=soapenv.root())
if self.options.prettyxml:
soapenv = soapenv.str()
else:
soapenv = soapenv.plain()
soapenv = soapenv.encode("utf-8")
ctx = plugins.message.sending(envelope=soapenv)
soapenv = ctx.envelope
if self.options.nosend:
return RequestContext(self.process_reply, soapenv)
request = suds.transport.Request(location, soapenv)
request.headers = self.__headers()
try:
timer = metrics.Timer()
timer.start()
reply = self.options.transport.send(request)
timer.stop()
metrics.log.debug("waited %s on server reply", timer)
except suds.transport.TransportError, e:
content = e.fp and e.fp.read() or ""
return self.process_reply(content, e.httpcode, tostr(e))
return self.process_reply(reply.message, None, None) | python | def send(self, soapenv):
"""
Send SOAP message.
Depending on how the ``nosend`` & ``retxml`` options are set, may do
one of the following:
* Return a constructed web service operation request without sending
it to the web service.
* Invoke the web service operation and return its SOAP reply XML.
* Invoke the web service operation, process its results and return
the Python object representing the returned value.
@param soapenv: A SOAP envelope to send.
@type soapenv: L{Document}
@return: SOAP request, SOAP reply or a web service return value.
@rtype: L{RequestContext}|I{builtin}|I{subclass of} L{Object}|I{bytes}|
I{None}
"""
location = self.__location()
log.debug("sending to (%s)\nmessage:\n%s", location, soapenv)
plugins = PluginContainer(self.options.plugins)
plugins.message.marshalled(envelope=soapenv.root())
if self.options.prettyxml:
soapenv = soapenv.str()
else:
soapenv = soapenv.plain()
soapenv = soapenv.encode("utf-8")
ctx = plugins.message.sending(envelope=soapenv)
soapenv = ctx.envelope
if self.options.nosend:
return RequestContext(self.process_reply, soapenv)
request = suds.transport.Request(location, soapenv)
request.headers = self.__headers()
try:
timer = metrics.Timer()
timer.start()
reply = self.options.transport.send(request)
timer.stop()
metrics.log.debug("waited %s on server reply", timer)
except suds.transport.TransportError, e:
content = e.fp and e.fp.read() or ""
return self.process_reply(content, e.httpcode, tostr(e))
return self.process_reply(reply.message, None, None) | Send SOAP message.
Depending on how the ``nosend`` & ``retxml`` options are set, may do
one of the following:
* Return a constructed web service operation request without sending
it to the web service.
* Invoke the web service operation and return its SOAP reply XML.
* Invoke the web service operation, process its results and return
the Python object representing the returned value.
@param soapenv: A SOAP envelope to send.
@type soapenv: L{Document}
@return: SOAP request, SOAP reply or a web service return value.
@rtype: L{RequestContext}|I{builtin}|I{subclass of} L{Object}|I{bytes}|
I{None} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/client.py#L710-L753 |
suds-community/suds | suds/client.py | _SoapClient.process_reply | def process_reply(self, reply, status, description):
"""
Process a web service operation SOAP reply.
Depending on how the ``retxml`` option is set, may return the SOAP
reply XML or process it and return the Python object representing the
returned value.
@param reply: The SOAP reply envelope.
@type reply: I{bytes}
@param status: The HTTP status code (None indicates httplib.OK).
@type status: int|I{None}
@param description: Additional status description.
@type description: str
@return: The invoked web service operation return value.
@rtype: I{builtin}|I{subclass of} L{Object}|I{bytes}|I{None}
"""
if status is None:
status = httplib.OK
debug_message = "Reply HTTP status - %d" % (status,)
if status in (httplib.ACCEPTED, httplib.NO_CONTENT):
log.debug(debug_message)
return
#TODO: Consider whether and how to allow plugins to handle error,
# httplib.ACCEPTED & httplib.NO_CONTENT replies as well as successful
# ones.
if status == httplib.OK:
log.debug("%s\n%s", debug_message, reply)
else:
log.debug("%s - %s\n%s", debug_message, description, reply)
plugins = PluginContainer(self.options.plugins)
ctx = plugins.message.received(reply=reply)
reply = ctx.reply
# SOAP standard states that SOAP errors must be accompanied by HTTP
# status code 500 - internal server error:
#
# From SOAP 1.1 specification:
# In case of a SOAP error while processing the request, the SOAP HTTP
# server MUST issue an HTTP 500 "Internal Server Error" response and
# include a SOAP message in the response containing a SOAP Fault
# element (see section 4.4) indicating the SOAP processing error.
#
# From WS-I Basic profile:
# An INSTANCE MUST use a "500 Internal Server Error" HTTP status code
# if the response message is a SOAP Fault.
replyroot = None
if status in (httplib.OK, httplib.INTERNAL_SERVER_ERROR):
replyroot = _parse(reply)
plugins.message.parsed(reply=replyroot)
fault = self.__get_fault(replyroot)
if fault:
if status != httplib.INTERNAL_SERVER_ERROR:
log.warn("Web service reported a SOAP processing fault "
"using an unexpected HTTP status code %d. Reporting "
"as an internal server error.", status)
if self.options.faults:
raise WebFault(fault, replyroot)
return httplib.INTERNAL_SERVER_ERROR, fault
if status != httplib.OK:
if self.options.faults:
#TODO: Use a more specific exception class here.
raise Exception((status, description))
return status, description
if self.options.retxml:
return reply
result = replyroot and self.method.binding.output.get_reply(
self.method, replyroot)
ctx = plugins.message.unmarshalled(reply=result)
result = ctx.reply
if self.options.faults:
return result
return httplib.OK, result | python | def process_reply(self, reply, status, description):
"""
Process a web service operation SOAP reply.
Depending on how the ``retxml`` option is set, may return the SOAP
reply XML or process it and return the Python object representing the
returned value.
@param reply: The SOAP reply envelope.
@type reply: I{bytes}
@param status: The HTTP status code (None indicates httplib.OK).
@type status: int|I{None}
@param description: Additional status description.
@type description: str
@return: The invoked web service operation return value.
@rtype: I{builtin}|I{subclass of} L{Object}|I{bytes}|I{None}
"""
if status is None:
status = httplib.OK
debug_message = "Reply HTTP status - %d" % (status,)
if status in (httplib.ACCEPTED, httplib.NO_CONTENT):
log.debug(debug_message)
return
#TODO: Consider whether and how to allow plugins to handle error,
# httplib.ACCEPTED & httplib.NO_CONTENT replies as well as successful
# ones.
if status == httplib.OK:
log.debug("%s\n%s", debug_message, reply)
else:
log.debug("%s - %s\n%s", debug_message, description, reply)
plugins = PluginContainer(self.options.plugins)
ctx = plugins.message.received(reply=reply)
reply = ctx.reply
# SOAP standard states that SOAP errors must be accompanied by HTTP
# status code 500 - internal server error:
#
# From SOAP 1.1 specification:
# In case of a SOAP error while processing the request, the SOAP HTTP
# server MUST issue an HTTP 500 "Internal Server Error" response and
# include a SOAP message in the response containing a SOAP Fault
# element (see section 4.4) indicating the SOAP processing error.
#
# From WS-I Basic profile:
# An INSTANCE MUST use a "500 Internal Server Error" HTTP status code
# if the response message is a SOAP Fault.
replyroot = None
if status in (httplib.OK, httplib.INTERNAL_SERVER_ERROR):
replyroot = _parse(reply)
plugins.message.parsed(reply=replyroot)
fault = self.__get_fault(replyroot)
if fault:
if status != httplib.INTERNAL_SERVER_ERROR:
log.warn("Web service reported a SOAP processing fault "
"using an unexpected HTTP status code %d. Reporting "
"as an internal server error.", status)
if self.options.faults:
raise WebFault(fault, replyroot)
return httplib.INTERNAL_SERVER_ERROR, fault
if status != httplib.OK:
if self.options.faults:
#TODO: Use a more specific exception class here.
raise Exception((status, description))
return status, description
if self.options.retxml:
return reply
result = replyroot and self.method.binding.output.get_reply(
self.method, replyroot)
ctx = plugins.message.unmarshalled(reply=result)
result = ctx.reply
if self.options.faults:
return result
return httplib.OK, result | Process a web service operation SOAP reply.
Depending on how the ``retxml`` option is set, may return the SOAP
reply XML or process it and return the Python object representing the
returned value.
@param reply: The SOAP reply envelope.
@type reply: I{bytes}
@param status: The HTTP status code (None indicates httplib.OK).
@type status: int|I{None}
@param description: Additional status description.
@type description: str
@return: The invoked web service operation return value.
@rtype: I{builtin}|I{subclass of} L{Object}|I{bytes}|I{None} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/client.py#L755-L831 |
suds-community/suds | suds/client.py | _SoapClient.__get_fault | def __get_fault(self, replyroot):
"""
Extract fault information from a SOAP reply.
Returns an I{unmarshalled} fault L{Object} or None in case the given
XML document does not contain a SOAP <Fault> element.
@param replyroot: A SOAP reply message root XML element or None.
@type replyroot: L{Element}|I{None}
@return: A fault object.
@rtype: L{Object}
"""
envns = suds.bindings.binding.envns
soapenv = replyroot and replyroot.getChild("Envelope", envns)
soapbody = soapenv and soapenv.getChild("Body", envns)
fault = soapbody and soapbody.getChild("Fault", envns)
return fault is not None and UmxBasic().process(fault) | python | def __get_fault(self, replyroot):
"""
Extract fault information from a SOAP reply.
Returns an I{unmarshalled} fault L{Object} or None in case the given
XML document does not contain a SOAP <Fault> element.
@param replyroot: A SOAP reply message root XML element or None.
@type replyroot: L{Element}|I{None}
@return: A fault object.
@rtype: L{Object}
"""
envns = suds.bindings.binding.envns
soapenv = replyroot and replyroot.getChild("Envelope", envns)
soapbody = soapenv and soapenv.getChild("Body", envns)
fault = soapbody and soapbody.getChild("Fault", envns)
return fault is not None and UmxBasic().process(fault) | Extract fault information from a SOAP reply.
Returns an I{unmarshalled} fault L{Object} or None in case the given
XML document does not contain a SOAP <Fault> element.
@param replyroot: A SOAP reply message root XML element or None.
@type replyroot: L{Element}|I{None}
@return: A fault object.
@rtype: L{Object} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/client.py#L833-L850 |
suds-community/suds | suds/client.py | _SoapClient.__headers | def __headers(self):
"""
Get HTTP headers for a HTTP/HTTPS SOAP request.
@return: A dictionary of header/values.
@rtype: dict
"""
action = self.method.soap.action
if isinstance(action, unicode):
action = action.encode("utf-8")
result = {
"Content-Type": "text/xml; charset=utf-8",
"SOAPAction": action}
result.update(**self.options.headers)
log.debug("headers = %s", result)
return result | python | def __headers(self):
"""
Get HTTP headers for a HTTP/HTTPS SOAP request.
@return: A dictionary of header/values.
@rtype: dict
"""
action = self.method.soap.action
if isinstance(action, unicode):
action = action.encode("utf-8")
result = {
"Content-Type": "text/xml; charset=utf-8",
"SOAPAction": action}
result.update(**self.options.headers)
log.debug("headers = %s", result)
return result | Get HTTP headers for a HTTP/HTTPS SOAP request.
@return: A dictionary of header/values.
@rtype: dict | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/client.py#L852-L868 |
suds-community/suds | suds/client.py | _SimClient.invoke | def invoke(self, args, kwargs):
"""
Invoke a specified web service method.
Uses an injected SOAP request/response instead of a regularly
constructed/received one.
Depending on how the ``nosend`` & ``retxml`` options are set, may do
one of the following:
* Return a constructed web service operation request without sending
it to the web service.
* Invoke the web service operation and return its SOAP reply XML.
* Invoke the web service operation, process its results and return
the Python object representing the returned value.
@param args: Positional arguments for the method invoked.
@type args: list|tuple
@param kwargs: Keyword arguments for the method invoked.
@type kwargs: dict
@return: SOAP request, SOAP reply or a web service return value.
@rtype: L{RequestContext}|I{builtin}|I{subclass of} L{Object}|I{bytes}|
I{None}
"""
simulation = kwargs.pop(self.__injkey)
msg = simulation.get("msg")
if msg is not None:
assert msg.__class__ is suds.byte_str_class
return self.send(_parse(msg))
msg = self.method.binding.input.get_message(self.method, args, kwargs)
log.debug("inject (simulated) send message:\n%s", msg)
reply = simulation.get("reply")
if reply is not None:
assert reply.__class__ is suds.byte_str_class
status = simulation.get("status")
description = simulation.get("description")
if description is None:
description = "injected reply"
return self.process_reply(reply, status, description)
raise Exception("reply or msg injection parameter expected") | python | def invoke(self, args, kwargs):
"""
Invoke a specified web service method.
Uses an injected SOAP request/response instead of a regularly
constructed/received one.
Depending on how the ``nosend`` & ``retxml`` options are set, may do
one of the following:
* Return a constructed web service operation request without sending
it to the web service.
* Invoke the web service operation and return its SOAP reply XML.
* Invoke the web service operation, process its results and return
the Python object representing the returned value.
@param args: Positional arguments for the method invoked.
@type args: list|tuple
@param kwargs: Keyword arguments for the method invoked.
@type kwargs: dict
@return: SOAP request, SOAP reply or a web service return value.
@rtype: L{RequestContext}|I{builtin}|I{subclass of} L{Object}|I{bytes}|
I{None}
"""
simulation = kwargs.pop(self.__injkey)
msg = simulation.get("msg")
if msg is not None:
assert msg.__class__ is suds.byte_str_class
return self.send(_parse(msg))
msg = self.method.binding.input.get_message(self.method, args, kwargs)
log.debug("inject (simulated) send message:\n%s", msg)
reply = simulation.get("reply")
if reply is not None:
assert reply.__class__ is suds.byte_str_class
status = simulation.get("status")
description = simulation.get("description")
if description is None:
description = "injected reply"
return self.process_reply(reply, status, description)
raise Exception("reply or msg injection parameter expected") | Invoke a specified web service method.
Uses an injected SOAP request/response instead of a regularly
constructed/received one.
Depending on how the ``nosend`` & ``retxml`` options are set, may do
one of the following:
* Return a constructed web service operation request without sending
it to the web service.
* Invoke the web service operation and return its SOAP reply XML.
* Invoke the web service operation, process its results and return
the Python object representing the returned value.
@param args: Positional arguments for the method invoked.
@type args: list|tuple
@param kwargs: Keyword arguments for the method invoked.
@type kwargs: dict
@return: SOAP request, SOAP reply or a web service return value.
@rtype: L{RequestContext}|I{builtin}|I{subclass of} L{Object}|I{bytes}|
I{None} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/client.py#L891-L930 |
suds-community/suds | suds/transport/__init__.py | Request.__set_URL | def __set_URL(self, url):
"""
URL is stored as a str internally and must not contain ASCII chars.
Raised exception in case of detected non-ASCII URL characters may be
either UnicodeEncodeError or UnicodeDecodeError, depending on the used
Python version's str type and the exact value passed as URL input data.
"""
if isinstance(url, str):
url.encode("ascii") # Check for non-ASCII characters.
self.url = url
elif sys.version_info < (3, 0):
self.url = url.encode("ascii")
else:
self.url = url.decode("ascii") | python | def __set_URL(self, url):
"""
URL is stored as a str internally and must not contain ASCII chars.
Raised exception in case of detected non-ASCII URL characters may be
either UnicodeEncodeError or UnicodeDecodeError, depending on the used
Python version's str type and the exact value passed as URL input data.
"""
if isinstance(url, str):
url.encode("ascii") # Check for non-ASCII characters.
self.url = url
elif sys.version_info < (3, 0):
self.url = url.encode("ascii")
else:
self.url = url.decode("ascii") | URL is stored as a str internally and must not contain ASCII chars.
Raised exception in case of detected non-ASCII URL characters may be
either UnicodeEncodeError or UnicodeDecodeError, depending on the used
Python version's str type and the exact value passed as URL input data. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/transport/__init__.py#L75-L90 |
suds-community/suds | suds/mx/appender.py | ContentAppender.append | def append(self, parent, content):
"""
Select an appender and append the content to parent.
@param parent: A parent node.
@type parent: L{Element}
@param content: The content to append.
@type content: L{Content}
"""
appender = self.default
for matcher, candidate_appender in self.appenders:
if matcher == content.value:
appender = candidate_appender
break
appender.append(parent, content) | python | def append(self, parent, content):
"""
Select an appender and append the content to parent.
@param parent: A parent node.
@type parent: L{Element}
@param content: The content to append.
@type content: L{Content}
"""
appender = self.default
for matcher, candidate_appender in self.appenders:
if matcher == content.value:
appender = candidate_appender
break
appender.append(parent, content) | Select an appender and append the content to parent.
@param parent: A parent node.
@type parent: L{Element}
@param content: The content to append.
@type content: L{Content} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/mx/appender.py#L73-L86 |
suds-community/suds | suds/resolver.py | PathResolver.root | def root(self, parts):
"""
Find the path root.
@param parts: A list of path parts.
@type parts: [str,..]
@return: The root.
@rtype: L{xsd.sxbase.SchemaObject}
"""
result = None
name = parts[0]
log.debug('searching schema for (%s)', name)
qref = self.qualify(parts[0])
query = BlindQuery(qref)
result = query.execute(self.schema)
if result is None:
log.error('(%s) not-found', name)
raise PathResolver.BadPath(name)
log.debug('found (%s) as (%s)', name, Repr(result))
return result | python | def root(self, parts):
"""
Find the path root.
@param parts: A list of path parts.
@type parts: [str,..]
@return: The root.
@rtype: L{xsd.sxbase.SchemaObject}
"""
result = None
name = parts[0]
log.debug('searching schema for (%s)', name)
qref = self.qualify(parts[0])
query = BlindQuery(qref)
result = query.execute(self.schema)
if result is None:
log.error('(%s) not-found', name)
raise PathResolver.BadPath(name)
log.debug('found (%s) as (%s)', name, Repr(result))
return result | Find the path root.
@param parts: A list of path parts.
@type parts: [str,..]
@return: The root.
@rtype: L{xsd.sxbase.SchemaObject} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/resolver.py#L119-L137 |
suds-community/suds | suds/resolver.py | PathResolver.branch | def branch(self, root, parts):
"""
Traverse the path until a leaf is reached.
@param parts: A list of path parts.
@type parts: [str,..]
@param root: The root.
@type root: L{xsd.sxbase.SchemaObject}
@return: The end of the branch.
@rtype: L{xsd.sxbase.SchemaObject}
"""
result = root
for part in parts[1:-1]:
name = splitPrefix(part)[1]
log.debug('searching parent (%s) for (%s)', Repr(result), name)
result, ancestry = result.get_child(name)
if result is None:
log.error('(%s) not-found', name)
raise PathResolver.BadPath(name)
result = result.resolve(nobuiltin=True)
log.debug('found (%s) as (%s)', name, Repr(result))
return result | python | def branch(self, root, parts):
"""
Traverse the path until a leaf is reached.
@param parts: A list of path parts.
@type parts: [str,..]
@param root: The root.
@type root: L{xsd.sxbase.SchemaObject}
@return: The end of the branch.
@rtype: L{xsd.sxbase.SchemaObject}
"""
result = root
for part in parts[1:-1]:
name = splitPrefix(part)[1]
log.debug('searching parent (%s) for (%s)', Repr(result), name)
result, ancestry = result.get_child(name)
if result is None:
log.error('(%s) not-found', name)
raise PathResolver.BadPath(name)
result = result.resolve(nobuiltin=True)
log.debug('found (%s) as (%s)', name, Repr(result))
return result | Traverse the path until a leaf is reached.
@param parts: A list of path parts.
@type parts: [str,..]
@param root: The root.
@type root: L{xsd.sxbase.SchemaObject}
@return: The end of the branch.
@rtype: L{xsd.sxbase.SchemaObject} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/resolver.py#L139-L159 |
suds-community/suds | suds/resolver.py | TreeResolver.getchild | def getchild(self, name, parent):
"""Get a child by name."""
log.debug('searching parent (%s) for (%s)', Repr(parent), name)
if name.startswith('@'):
return parent.get_attribute(name[1:])
return parent.get_child(name) | python | def getchild(self, name, parent):
"""Get a child by name."""
log.debug('searching parent (%s) for (%s)', Repr(parent), name)
if name.startswith('@'):
return parent.get_attribute(name[1:])
return parent.get_child(name) | Get a child by name. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/resolver.py#L292-L297 |
suds-community/suds | tools/suds_devel/zip.py | _Archiver.__path_prefix | def __path_prefix(self, folder):
"""
Path prefix to be used when archiving any items from the given folder.
Expects the folder to be located under the base folder path and the
returned path prefix does not include the base folder information. This
makes sure we include just the base folder's content in the archive,
and not the base folder itself.
"""
path_parts = path_iter(folder)
_skip_expected(path_parts, self.__base_folder_parts)
result = "/".join(path_parts)
if result:
result += "/"
return result | python | def __path_prefix(self, folder):
"""
Path prefix to be used when archiving any items from the given folder.
Expects the folder to be located under the base folder path and the
returned path prefix does not include the base folder information. This
makes sure we include just the base folder's content in the archive,
and not the base folder itself.
"""
path_parts = path_iter(folder)
_skip_expected(path_parts, self.__base_folder_parts)
result = "/".join(path_parts)
if result:
result += "/"
return result | Path prefix to be used when archiving any items from the given folder.
Expects the folder to be located under the base folder path and the
returned path prefix does not include the base folder information. This
makes sure we include just the base folder's content in the archive,
and not the base folder itself. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/suds_devel/zip.py#L67-L82 |
suds-community/suds | suds/xsd/sxbuiltin.py | XDecimal._decimal_to_xsd_format | def _decimal_to_xsd_format(value):
"""
Converts a decimal.Decimal value to its XSD decimal type value.
Result is a string containing the XSD decimal type's lexical value
representation. The conversion is done without any precision loss.
Note that Python's native decimal.Decimal string representation will
not do here as the lexical representation desired here does not allow
representing decimal values using float-like `<mantissa>E<exponent>'
format, e.g. 12E+30 or 0.10006E-12.
"""
value = XDecimal._decimal_canonical(value)
negative, digits, exponent = value.as_tuple()
# The following implementation assumes the following tuple decimal
# encoding (part of the canonical decimal value encoding):
# - digits must contain at least one element
# - no leading integral 0 digits except a single one in 0 (if a non-0
# decimal value has leading integral 0 digits they must be encoded
# in its 'exponent' value and not included explicitly in its
# 'digits' tuple)
assert digits
assert digits[0] != 0 or len(digits) == 1
result = []
if negative:
result.append("-")
# No fractional digits.
if exponent >= 0:
result.extend(str(x) for x in digits)
result.extend("0" * exponent)
return "".join(result)
digit_count = len(digits)
# Decimal point offset from the given digit start.
point_offset = digit_count + exponent
# Trim trailing fractional 0 digits.
fractional_digit_count = min(digit_count, -exponent)
while fractional_digit_count and digits[digit_count - 1] == 0:
digit_count -= 1
fractional_digit_count -= 1
# No trailing fractional 0 digits and a decimal point coming not after
# the given digits, meaning there is no need to add additional trailing
# integral 0 digits.
if point_offset <= 0:
# No integral digits.
result.append("0")
if digit_count > 0:
result.append(".")
result.append("0" * -point_offset)
result.extend(str(x) for x in digits[:digit_count])
else:
# Have integral and possibly some fractional digits.
result.extend(str(x) for x in digits[:point_offset])
if point_offset < digit_count:
result.append(".")
result.extend(str(x) for x in digits[point_offset:digit_count])
return "".join(result) | python | def _decimal_to_xsd_format(value):
"""
Converts a decimal.Decimal value to its XSD decimal type value.
Result is a string containing the XSD decimal type's lexical value
representation. The conversion is done without any precision loss.
Note that Python's native decimal.Decimal string representation will
not do here as the lexical representation desired here does not allow
representing decimal values using float-like `<mantissa>E<exponent>'
format, e.g. 12E+30 or 0.10006E-12.
"""
value = XDecimal._decimal_canonical(value)
negative, digits, exponent = value.as_tuple()
# The following implementation assumes the following tuple decimal
# encoding (part of the canonical decimal value encoding):
# - digits must contain at least one element
# - no leading integral 0 digits except a single one in 0 (if a non-0
# decimal value has leading integral 0 digits they must be encoded
# in its 'exponent' value and not included explicitly in its
# 'digits' tuple)
assert digits
assert digits[0] != 0 or len(digits) == 1
result = []
if negative:
result.append("-")
# No fractional digits.
if exponent >= 0:
result.extend(str(x) for x in digits)
result.extend("0" * exponent)
return "".join(result)
digit_count = len(digits)
# Decimal point offset from the given digit start.
point_offset = digit_count + exponent
# Trim trailing fractional 0 digits.
fractional_digit_count = min(digit_count, -exponent)
while fractional_digit_count and digits[digit_count - 1] == 0:
digit_count -= 1
fractional_digit_count -= 1
# No trailing fractional 0 digits and a decimal point coming not after
# the given digits, meaning there is no need to add additional trailing
# integral 0 digits.
if point_offset <= 0:
# No integral digits.
result.append("0")
if digit_count > 0:
result.append(".")
result.append("0" * -point_offset)
result.extend(str(x) for x in digits[:digit_count])
else:
# Have integral and possibly some fractional digits.
result.extend(str(x) for x in digits[:point_offset])
if point_offset < digit_count:
result.append(".")
result.extend(str(x) for x in digits[point_offset:digit_count])
return "".join(result) | Converts a decimal.Decimal value to its XSD decimal type value.
Result is a string containing the XSD decimal type's lexical value
representation. The conversion is done without any precision loss.
Note that Python's native decimal.Decimal string representation will
not do here as the lexical representation desired here does not allow
representing decimal values using float-like `<mantissa>E<exponent>'
format, e.g. 12E+30 or 0.10006E-12. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/xsd/sxbuiltin.py#L129-L192 |
suds-community/suds | suds/xsd/sxbuiltin.py | Factory.create | def create(cls, schema, name):
"""
Create an object based on the root tag name.
@param schema: A schema object.
@type schema: L{schema.Schema}
@param name: The name.
@type name: str
@return: The created object.
@rtype: L{XBuiltin}
"""
fn = cls.tags.get(name, XBuiltin)
return fn(schema, name) | python | def create(cls, schema, name):
"""
Create an object based on the root tag name.
@param schema: A schema object.
@type schema: L{schema.Schema}
@param name: The name.
@type name: str
@return: The created object.
@rtype: L{XBuiltin}
"""
fn = cls.tags.get(name, XBuiltin)
return fn(schema, name) | Create an object based on the root tag name.
@param schema: A schema object.
@type schema: L{schema.Schema}
@param name: The name.
@type name: str
@return: The created object.
@rtype: L{XBuiltin} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/xsd/sxbuiltin.py#L334-L347 |
suds-community/suds | tools/setup_base_environments.py | _avoid_setuptools_zipped_egg_upgrade_issue | def _avoid_setuptools_zipped_egg_upgrade_issue(env, ez_setup):
"""
Avoid the setuptools self-upgrade issue.
setuptools versions prior to version 3.5.2 have a bug that can cause their
upgrade installations to fail when installing a new zipped egg distribution
over an existing zipped egg setuptools distribution with the same name.
The following Python versions are not affected by this issue:
Python 2.4 - use setuptools 1.4.2 - installs itself as a non-zipped egg
Python 2.6+ - use setuptools versions not affected by this issue
That just leaves Python versions 2.5.x to worry about.
This problem occurs because of an internal stale cache issue causing the
upgrade to read data from the new zip archive at a location calculated
based on the original zip archive's content, effectively causing such read
operations to either succeed (if read content had not changed its
location), fail with a 'bad local header' exception or even fail silently
and return incorrect data.
To avoid the issue, we explicitly uninstall the previously installed
setuptools distribution before installing its new version.
"""
if env.sys_version_info[:2] != (2, 5):
return # only Python 2.5.x affected by this
if not env.setuptools_zipped_egg:
return # setuptools not pre-installed as a zipped egg
pv_new = parse_version(ez_setup.setuptools_version())
if pv_new != parse_version(env.setuptools_version):
return # issue avoided since zipped egg archive names will not match
fixed_version = utility.lowest_version_string_with_prefix("3.5.2")
if pv_new >= parse_version(fixed_version):
return # issue fixed in setuptools
# We could check for pip and use it for a cleaner setuptools uninstall if
# available, but YAGNI since only Python 2.5.x environments are affected by
# the zipped egg upgrade issue.
os.remove(env.setuptools_zipped_egg) | python | def _avoid_setuptools_zipped_egg_upgrade_issue(env, ez_setup):
"""
Avoid the setuptools self-upgrade issue.
setuptools versions prior to version 3.5.2 have a bug that can cause their
upgrade installations to fail when installing a new zipped egg distribution
over an existing zipped egg setuptools distribution with the same name.
The following Python versions are not affected by this issue:
Python 2.4 - use setuptools 1.4.2 - installs itself as a non-zipped egg
Python 2.6+ - use setuptools versions not affected by this issue
That just leaves Python versions 2.5.x to worry about.
This problem occurs because of an internal stale cache issue causing the
upgrade to read data from the new zip archive at a location calculated
based on the original zip archive's content, effectively causing such read
operations to either succeed (if read content had not changed its
location), fail with a 'bad local header' exception or even fail silently
and return incorrect data.
To avoid the issue, we explicitly uninstall the previously installed
setuptools distribution before installing its new version.
"""
if env.sys_version_info[:2] != (2, 5):
return # only Python 2.5.x affected by this
if not env.setuptools_zipped_egg:
return # setuptools not pre-installed as a zipped egg
pv_new = parse_version(ez_setup.setuptools_version())
if pv_new != parse_version(env.setuptools_version):
return # issue avoided since zipped egg archive names will not match
fixed_version = utility.lowest_version_string_with_prefix("3.5.2")
if pv_new >= parse_version(fixed_version):
return # issue fixed in setuptools
# We could check for pip and use it for a cleaner setuptools uninstall if
# available, but YAGNI since only Python 2.5.x environments are affected by
# the zipped egg upgrade issue.
os.remove(env.setuptools_zipped_egg) | Avoid the setuptools self-upgrade issue.
setuptools versions prior to version 3.5.2 have a bug that can cause their
upgrade installations to fail when installing a new zipped egg distribution
over an existing zipped egg setuptools distribution with the same name.
The following Python versions are not affected by this issue:
Python 2.4 - use setuptools 1.4.2 - installs itself as a non-zipped egg
Python 2.6+ - use setuptools versions not affected by this issue
That just leaves Python versions 2.5.x to worry about.
This problem occurs because of an internal stale cache issue causing the
upgrade to read data from the new zip archive at a location calculated
based on the original zip archive's content, effectively causing such read
operations to either succeed (if read content had not changed its
location), fail with a 'bad local header' exception or even fail silently
and return incorrect data.
To avoid the issue, we explicitly uninstall the previously installed
setuptools distribution before installing its new version. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/setup_base_environments.py#L494-L531 |
suds-community/suds | tools/setup_base_environments.py | _reuse_pre_installed_setuptools | def _reuse_pre_installed_setuptools(env, installer):
"""
Return whether a pre-installed setuptools distribution should be reused.
"""
if not env.setuptools_version:
return # no prior setuptools ==> no reuse
reuse_old = config.reuse_old_setuptools
reuse_best = config.reuse_best_setuptools
reuse_future = config.reuse_future_setuptools
reuse_comment = None
if reuse_old or reuse_best or reuse_future:
pv_old = parse_version(env.setuptools_version)
pv_new = parse_version(installer.setuptools_version())
if pv_old < pv_new:
if reuse_old:
reuse_comment = "%s+ recommended" % (
installer.setuptools_version(),)
elif pv_old > pv_new:
if reuse_future:
reuse_comment = "%s+ required" % (
installer.setuptools_version(),)
elif reuse_best:
reuse_comment = ""
if reuse_comment is None:
return # reuse not allowed by configuration
if reuse_comment:
reuse_comment = " (%s)" % (reuse_comment,)
print("Reusing pre-installed setuptools %s distribution%s." % (
env.setuptools_version, reuse_comment))
return True | python | def _reuse_pre_installed_setuptools(env, installer):
"""
Return whether a pre-installed setuptools distribution should be reused.
"""
if not env.setuptools_version:
return # no prior setuptools ==> no reuse
reuse_old = config.reuse_old_setuptools
reuse_best = config.reuse_best_setuptools
reuse_future = config.reuse_future_setuptools
reuse_comment = None
if reuse_old or reuse_best or reuse_future:
pv_old = parse_version(env.setuptools_version)
pv_new = parse_version(installer.setuptools_version())
if pv_old < pv_new:
if reuse_old:
reuse_comment = "%s+ recommended" % (
installer.setuptools_version(),)
elif pv_old > pv_new:
if reuse_future:
reuse_comment = "%s+ required" % (
installer.setuptools_version(),)
elif reuse_best:
reuse_comment = ""
if reuse_comment is None:
return # reuse not allowed by configuration
if reuse_comment:
reuse_comment = " (%s)" % (reuse_comment,)
print("Reusing pre-installed setuptools %s distribution%s." % (
env.setuptools_version, reuse_comment))
return True | Return whether a pre-installed setuptools distribution should be reused. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/setup_base_environments.py#L534-L564 |
suds-community/suds | tools/setup_base_environments.py | download_pip | def download_pip(env, requirements):
"""Download pip and its requirements using setuptools."""
if config.installation_cache_folder() is None:
raise EnvironmentSetupError("Local installation cache folder not "
"defined but required for downloading a pip installation.")
# Installation cache folder needs to be explicitly created for setuptools
# to be able to copy its downloaded installation files into it. Seen using
# Python 2.4.4 & setuptools 1.4.
_create_installation_cache_folder_if_needed()
try:
env.execute(["-m", "easy_install", "--zip-ok", "--multi-version",
"--always-copy", "--exclude-scripts", "--install-dir",
config.installation_cache_folder()] + requirements)
zip_eggs_in_folder(config.installation_cache_folder())
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
raise EnvironmentSetupError("pip download failed.") | python | def download_pip(env, requirements):
"""Download pip and its requirements using setuptools."""
if config.installation_cache_folder() is None:
raise EnvironmentSetupError("Local installation cache folder not "
"defined but required for downloading a pip installation.")
# Installation cache folder needs to be explicitly created for setuptools
# to be able to copy its downloaded installation files into it. Seen using
# Python 2.4.4 & setuptools 1.4.
_create_installation_cache_folder_if_needed()
try:
env.execute(["-m", "easy_install", "--zip-ok", "--multi-version",
"--always-copy", "--exclude-scripts", "--install-dir",
config.installation_cache_folder()] + requirements)
zip_eggs_in_folder(config.installation_cache_folder())
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
raise EnvironmentSetupError("pip download failed.") | Download pip and its requirements using setuptools. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/setup_base_environments.py#L596-L613 |
suds-community/suds | tools/setup_base_environments.py | setuptools_install_options | def setuptools_install_options(local_storage_folder):
"""
Return options to make setuptools use installations from the given folder.
No other installation source is allowed.
"""
if local_storage_folder is None:
return []
# setuptools expects its find-links parameter to contain a list of link
# sources (either local paths, file: URLs pointing to folders or URLs
# pointing to a file containing HTML links) separated by spaces. That means
# that, when specifying such items, whether local paths or URLs, they must
# not contain spaces. The problem can be worked around by using a local
# file URL, since URLs can contain space characters encoded as '%20' (for
# more detailed information see below).
#
# Any URL referencing a folder needs to be specified with a trailing '/'
# character in order for setuptools to correctly recognize it as a folder.
#
# All this has been tested using Python 2.4.3/2.4.4 & setuptools 1.4/1.4.2
# as well as Python 3.4 & setuptools 3.3.
#
# Supporting paths with spaces - method 1:
# ----------------------------------------
# One way would be to prepare a link file and pass an URL referring to that
# link file. The link file needs to contain a list of HTML link tags
# (<a href="..."/>), one for every item stored inside the local storage
# folder. If a link file references a folder whose name matches the desired
# requirement name, it will be searched recursively (as described in method
# 2 below).
#
# Note that in order for setuptools to recognize a local link file URL
# correctly, the file needs to be named with the '.html' extension. That
# will cause the underlying urllib2.open() operation to return the link
# file's content type as 'text/html' which is required for setuptools to
# recognize a valid link file.
#
# Supporting paths with spaces - method 2:
# ----------------------------------------
# Another possible way is to use an URL referring to the local storage
# folder directly. This will cause setuptools to prepare and use a link
# file internally - with its content read from a 'index.html' file located
# in the given local storage folder, if it exists, or constructed so it
# contains HTML links to all top-level local storage folder items, as
# described for method 1 above.
if " " in local_storage_folder:
find_links_param = utility.path_to_URL(local_storage_folder)
if find_links_param[-1] != "/":
find_links_param += "/"
else:
find_links_param = local_storage_folder
return ["-f", find_links_param, "--allow-hosts=None"] | python | def setuptools_install_options(local_storage_folder):
"""
Return options to make setuptools use installations from the given folder.
No other installation source is allowed.
"""
if local_storage_folder is None:
return []
# setuptools expects its find-links parameter to contain a list of link
# sources (either local paths, file: URLs pointing to folders or URLs
# pointing to a file containing HTML links) separated by spaces. That means
# that, when specifying such items, whether local paths or URLs, they must
# not contain spaces. The problem can be worked around by using a local
# file URL, since URLs can contain space characters encoded as '%20' (for
# more detailed information see below).
#
# Any URL referencing a folder needs to be specified with a trailing '/'
# character in order for setuptools to correctly recognize it as a folder.
#
# All this has been tested using Python 2.4.3/2.4.4 & setuptools 1.4/1.4.2
# as well as Python 3.4 & setuptools 3.3.
#
# Supporting paths with spaces - method 1:
# ----------------------------------------
# One way would be to prepare a link file and pass an URL referring to that
# link file. The link file needs to contain a list of HTML link tags
# (<a href="..."/>), one for every item stored inside the local storage
# folder. If a link file references a folder whose name matches the desired
# requirement name, it will be searched recursively (as described in method
# 2 below).
#
# Note that in order for setuptools to recognize a local link file URL
# correctly, the file needs to be named with the '.html' extension. That
# will cause the underlying urllib2.open() operation to return the link
# file's content type as 'text/html' which is required for setuptools to
# recognize a valid link file.
#
# Supporting paths with spaces - method 2:
# ----------------------------------------
# Another possible way is to use an URL referring to the local storage
# folder directly. This will cause setuptools to prepare and use a link
# file internally - with its content read from a 'index.html' file located
# in the given local storage folder, if it exists, or constructed so it
# contains HTML links to all top-level local storage folder items, as
# described for method 1 above.
if " " in local_storage_folder:
find_links_param = utility.path_to_URL(local_storage_folder)
if find_links_param[-1] != "/":
find_links_param += "/"
else:
find_links_param = local_storage_folder
return ["-f", find_links_param, "--allow-hosts=None"] | Return options to make setuptools use installations from the given folder.
No other installation source is allowed. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/setup_base_environments.py#L616-L668 |
suds-community/suds | tools/setup_base_environments.py | install_pip | def install_pip(env, requirements):
"""Install pip and its requirements using setuptools."""
try:
installation_source_folder = config.installation_cache_folder()
options = setuptools_install_options(installation_source_folder)
if installation_source_folder is not None:
zip_eggs_in_folder(installation_source_folder)
env.execute(["-m", "easy_install"] + options + requirements)
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
raise EnvironmentSetupError("pip installation failed.") | python | def install_pip(env, requirements):
"""Install pip and its requirements using setuptools."""
try:
installation_source_folder = config.installation_cache_folder()
options = setuptools_install_options(installation_source_folder)
if installation_source_folder is not None:
zip_eggs_in_folder(installation_source_folder)
env.execute(["-m", "easy_install"] + options + requirements)
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
raise EnvironmentSetupError("pip installation failed.") | Install pip and its requirements using setuptools. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/setup_base_environments.py#L671-L682 |
suds-community/suds | tools/setup_base_environments.py | prepare_pip_requirements_file_if_needed | def prepare_pip_requirements_file_if_needed(requirements):
"""
Make requirements be passed to pip via a requirements file if needed.
We must be careful about how we pass shell operator characters (e.g. '<',
'>', '|' or '^') included in our command-line arguments or they might cause
problems if run through an intermediate shell interpreter. If our pip
requirement specifications contain such characters, we pass them using a
separate requirements file.
This problem has been encountered on Windows 7 SP1 x64 using Python 2.4.3,
2.4.4 & 2.5.4.
"""
if utility.any_contains_any(requirements, "<>|()&^"):
file_path, janitor = pip_requirements_file(requirements)
requirements[:] = ["-r", file_path]
return janitor | python | def prepare_pip_requirements_file_if_needed(requirements):
"""
Make requirements be passed to pip via a requirements file if needed.
We must be careful about how we pass shell operator characters (e.g. '<',
'>', '|' or '^') included in our command-line arguments or they might cause
problems if run through an intermediate shell interpreter. If our pip
requirement specifications contain such characters, we pass them using a
separate requirements file.
This problem has been encountered on Windows 7 SP1 x64 using Python 2.4.3,
2.4.4 & 2.5.4.
"""
if utility.any_contains_any(requirements, "<>|()&^"):
file_path, janitor = pip_requirements_file(requirements)
requirements[:] = ["-r", file_path]
return janitor | Make requirements be passed to pip via a requirements file if needed.
We must be careful about how we pass shell operator characters (e.g. '<',
'>', '|' or '^') included in our command-line arguments or they might cause
problems if run through an intermediate shell interpreter. If our pip
requirement specifications contain such characters, we pass them using a
separate requirements file.
This problem has been encountered on Windows 7 SP1 x64 using Python 2.4.3,
2.4.4 & 2.5.4. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/setup_base_environments.py#L743-L760 |
suds-community/suds | tools/setup_base_environments.py | download_pip_based_installations | def download_pip_based_installations(env, pip_invocation, requirements,
download_cache_folder):
"""Download requirements for pip based installation."""
if config.installation_cache_folder() is None:
raise EnvironmentSetupError("Local installation cache folder not "
"defined but required for downloading pip based installations.")
# Installation cache folder needs to be explicitly created for pip to be
# able to copy its downloaded installation files into it. The same does not
# hold for pip's download cache folder which gets created by pip on-demand.
# Seen using Python 3.4.0 & pip 1.5.4.
_create_installation_cache_folder_if_needed()
try:
pip_options = ["install", "-d", config.installation_cache_folder(),
"--exists-action=i"]
pip_options.extend(pip_download_cache_options(download_cache_folder))
# Running pip based installations on Python 2.5.
# * Python 2.5 does not come with SSL support enabled by default and
# so pip can not use SSL certified downloads from PyPI.
# * To work around this either install the
# https://pypi.python.org/pypi/ssl package or run pip using the
# '--insecure' command-line options.
# * Installing the ssl package seems ridden with problems on
# Python 2.5 so this workaround has not been tested.
if (2, 5) <= env.sys_version_info < (2, 6):
# There are some potential cases where we do not need to use
# "--insecure", e.g. if the target Python environment already has
# the 'ssl' module installed. However, detecting whether this is so
# does not seem to be worth the effort. The only way to detect
# whether secure download is supported would be to scan the target
# environment for this information, e.g. setuptools has this
# information in its pip.backwardcompat.ssl variable - if it is
# None, the necessary SSL support is not available. But then we
# would have to be careful:
# - not to run the scan if we already know this information from
# some previous scan
# - to track all actions that could have invalidated our previous
# scan results, etc.
# It just does not seem to be worth the hassle so for now - YAGNI.
pip_options.append("--insecure")
env.execute(pip_invocation + pip_options + requirements)
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
raise EnvironmentSetupError("pip based download failed.") | python | def download_pip_based_installations(env, pip_invocation, requirements,
download_cache_folder):
"""Download requirements for pip based installation."""
if config.installation_cache_folder() is None:
raise EnvironmentSetupError("Local installation cache folder not "
"defined but required for downloading pip based installations.")
# Installation cache folder needs to be explicitly created for pip to be
# able to copy its downloaded installation files into it. The same does not
# hold for pip's download cache folder which gets created by pip on-demand.
# Seen using Python 3.4.0 & pip 1.5.4.
_create_installation_cache_folder_if_needed()
try:
pip_options = ["install", "-d", config.installation_cache_folder(),
"--exists-action=i"]
pip_options.extend(pip_download_cache_options(download_cache_folder))
# Running pip based installations on Python 2.5.
# * Python 2.5 does not come with SSL support enabled by default and
# so pip can not use SSL certified downloads from PyPI.
# * To work around this either install the
# https://pypi.python.org/pypi/ssl package or run pip using the
# '--insecure' command-line options.
# * Installing the ssl package seems ridden with problems on
# Python 2.5 so this workaround has not been tested.
if (2, 5) <= env.sys_version_info < (2, 6):
# There are some potential cases where we do not need to use
# "--insecure", e.g. if the target Python environment already has
# the 'ssl' module installed. However, detecting whether this is so
# does not seem to be worth the effort. The only way to detect
# whether secure download is supported would be to scan the target
# environment for this information, e.g. setuptools has this
# information in its pip.backwardcompat.ssl variable - if it is
# None, the necessary SSL support is not available. But then we
# would have to be careful:
# - not to run the scan if we already know this information from
# some previous scan
# - to track all actions that could have invalidated our previous
# scan results, etc.
# It just does not seem to be worth the hassle so for now - YAGNI.
pip_options.append("--insecure")
env.execute(pip_invocation + pip_options + requirements)
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
raise EnvironmentSetupError("pip based download failed.") | Download requirements for pip based installation. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/setup_base_environments.py#L778-L821 |
suds-community/suds | tools/setup_base_environments.py | enabled_actions_for_env | def enabled_actions_for_env(env):
"""Returns actions to perform when processing the given environment."""
def enabled(config_value, required):
if config_value is Config.TriBool.No:
return False
if config_value is Config.TriBool.Yes:
return True
assert config_value is Config.TriBool.IfNeeded
return bool(required)
# Some old Python versions do not support HTTPS downloads and therefore can
# not download installation packages from PyPI. To run setuptools or pip
# based installations on such Python versions, all the required
# installation packages need to be downloaded locally first using a
# compatible Python version (e.g. Python 2.4.4 for Python 2.4.3) and then
# installed locally.
download_supported = not ((2, 4, 3) <= env.sys_version_info < (2, 4, 4))
local_install = config.installation_cache_folder() is not None
actions = set()
pip_required = False
run_pip_based_installations = enabled(config.install_environments, True)
if run_pip_based_installations:
actions.add("run pip based installations")
pip_required = True
if download_supported and enabled(config.download_installations,
local_install and run_pip_based_installations):
actions.add("download pip based installations")
pip_required = True
setuptools_required = False
run_pip_installation = enabled(config.install_environments, pip_required)
if run_pip_installation:
actions.add("run pip installation")
setuptools_required = True
if download_supported and enabled(config.download_installations,
local_install and run_pip_installation):
actions.add("download pip installation")
setuptools_required = True
if enabled(config.setup_setuptools, setuptools_required):
actions.add("setup setuptools")
return actions | python | def enabled_actions_for_env(env):
"""Returns actions to perform when processing the given environment."""
def enabled(config_value, required):
if config_value is Config.TriBool.No:
return False
if config_value is Config.TriBool.Yes:
return True
assert config_value is Config.TriBool.IfNeeded
return bool(required)
# Some old Python versions do not support HTTPS downloads and therefore can
# not download installation packages from PyPI. To run setuptools or pip
# based installations on such Python versions, all the required
# installation packages need to be downloaded locally first using a
# compatible Python version (e.g. Python 2.4.4 for Python 2.4.3) and then
# installed locally.
download_supported = not ((2, 4, 3) <= env.sys_version_info < (2, 4, 4))
local_install = config.installation_cache_folder() is not None
actions = set()
pip_required = False
run_pip_based_installations = enabled(config.install_environments, True)
if run_pip_based_installations:
actions.add("run pip based installations")
pip_required = True
if download_supported and enabled(config.download_installations,
local_install and run_pip_based_installations):
actions.add("download pip based installations")
pip_required = True
setuptools_required = False
run_pip_installation = enabled(config.install_environments, pip_required)
if run_pip_installation:
actions.add("run pip installation")
setuptools_required = True
if download_supported and enabled(config.download_installations,
local_install and run_pip_installation):
actions.add("download pip installation")
setuptools_required = True
if enabled(config.setup_setuptools, setuptools_required):
actions.add("setup setuptools")
return actions | Returns actions to perform when processing the given environment. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/setup_base_environments.py#L891-L936 |
suds-community/suds | tools/setup_base_environments.py | _ez_setup_script.__setuptools_version | def __setuptools_version(self):
"""Read setuptools version from the underlying ez_setup script."""
# Read the script directly as a file instead of importing it as a
# Python module and reading the value from the loaded module's global
# DEFAULT_VERSION variable. Not all ez_setup scripts are compatible
# with all Python environments and so importing them would require
# doing so using a separate process run in the target Python
# environment instead of the current one.
f = open(self.script_path(), "r")
try:
matcher = re.compile(r'\s*DEFAULT_VERSION\s*=\s*"([^"]*)"\s*$')
for i, line in enumerate(f):
if i > 50:
break
match = matcher.match(line)
if match:
return match.group(1)
finally:
f.close()
self.__error("error parsing setuptools installation script '%s'" % (
self.script_path(),)) | python | def __setuptools_version(self):
"""Read setuptools version from the underlying ez_setup script."""
# Read the script directly as a file instead of importing it as a
# Python module and reading the value from the loaded module's global
# DEFAULT_VERSION variable. Not all ez_setup scripts are compatible
# with all Python environments and so importing them would require
# doing so using a separate process run in the target Python
# environment instead of the current one.
f = open(self.script_path(), "r")
try:
matcher = re.compile(r'\s*DEFAULT_VERSION\s*=\s*"([^"]*)"\s*$')
for i, line in enumerate(f):
if i > 50:
break
match = matcher.match(line)
if match:
return match.group(1)
finally:
f.close()
self.__error("error parsing setuptools installation script '%s'" % (
self.script_path(),)) | Read setuptools version from the underlying ez_setup script. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/setup_base_environments.py#L471-L491 |
suds-community/suds | suds/sax/element.py | Element.rename | def rename(self, name):
"""
Rename the element.
@param name: A new name for the element.
@type name: basestring
"""
if name is None:
raise Exception("name (%s) not-valid" % (name,))
self.prefix, self.name = splitPrefix(name) | python | def rename(self, name):
"""
Rename the element.
@param name: A new name for the element.
@type name: basestring
"""
if name is None:
raise Exception("name (%s) not-valid" % (name,))
self.prefix, self.name = splitPrefix(name) | Rename the element.
@param name: A new name for the element.
@type name: basestring | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/element.py#L104-L114 |
suds-community/suds | suds/sax/element.py | Element.clone | def clone(self, parent=None):
"""
Deep clone of this element and children.
@param parent: An optional parent for the copied fragment.
@type parent: I{Element}
@return: A deep copy parented by I{parent}
@rtype: I{Element}
"""
root = Element(self.qname(), parent, self.namespace())
for a in self.attributes:
root.append(a.clone(self))
for c in self.children:
root.append(c.clone(self))
for ns in self.nsprefixes.items():
root.addPrefix(ns[0], ns[1])
return root | python | def clone(self, parent=None):
"""
Deep clone of this element and children.
@param parent: An optional parent for the copied fragment.
@type parent: I{Element}
@return: A deep copy parented by I{parent}
@rtype: I{Element}
"""
root = Element(self.qname(), parent, self.namespace())
for a in self.attributes:
root.append(a.clone(self))
for c in self.children:
root.append(c.clone(self))
for ns in self.nsprefixes.items():
root.addPrefix(ns[0], ns[1])
return root | Deep clone of this element and children.
@param parent: An optional parent for the copied fragment.
@type parent: I{Element}
@return: A deep copy parented by I{parent}
@rtype: I{Element} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/element.py#L158-L175 |
suds-community/suds | suds/sax/element.py | Element.unset | def unset(self, name):
"""
Unset (remove) an attribute.
@param name: The attribute name.
@type name: str
@return: self
@rtype: L{Element}
"""
try:
attr = self.getAttribute(name)
self.attributes.remove(attr)
except Exception:
pass
return self | python | def unset(self, name):
"""
Unset (remove) an attribute.
@param name: The attribute name.
@type name: str
@return: self
@rtype: L{Element}
"""
try:
attr = self.getAttribute(name)
self.attributes.remove(attr)
except Exception:
pass
return self | Unset (remove) an attribute.
@param name: The attribute name.
@type name: str
@return: self
@rtype: L{Element} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/element.py#L210-L225 |
suds-community/suds | suds/sax/element.py | Element.get | def get(self, name, ns=None, default=None):
"""
Get the value of an attribute by name.
@param name: The name of the attribute.
@type name: basestring
@param ns: The optional attribute's namespace.
@type ns: (I{prefix}, I{name})
@param default: An optional value to be returned when either the
attribute does not exist or has no value.
@type default: basestring
@return: The attribute's value or I{default}.
@rtype: basestring
@see: __getitem__()
"""
attr = self.getAttribute(name, ns)
if attr is None or attr.value is None:
return default
return attr.getValue() | python | def get(self, name, ns=None, default=None):
"""
Get the value of an attribute by name.
@param name: The name of the attribute.
@type name: basestring
@param ns: The optional attribute's namespace.
@type ns: (I{prefix}, I{name})
@param default: An optional value to be returned when either the
attribute does not exist or has no value.
@type default: basestring
@return: The attribute's value or I{default}.
@rtype: basestring
@see: __getitem__()
"""
attr = self.getAttribute(name, ns)
if attr is None or attr.value is None:
return default
return attr.getValue() | Get the value of an attribute by name.
@param name: The name of the attribute.
@type name: basestring
@param ns: The optional attribute's namespace.
@type ns: (I{prefix}, I{name})
@param default: An optional value to be returned when either the
attribute does not exist or has no value.
@type default: basestring
@return: The attribute's value or I{default}.
@rtype: basestring
@see: __getitem__() | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/element.py#L227-L246 |
suds-community/suds | suds/sax/element.py | Element.namespace | def namespace(self):
"""
Get the element's namespace.
@return: The element's namespace by resolving the prefix, the explicit
namespace or the inherited namespace.
@rtype: (I{prefix}, I{name})
"""
if self.prefix is None:
return self.defaultNamespace()
return self.resolvePrefix(self.prefix) | python | def namespace(self):
"""
Get the element's namespace.
@return: The element's namespace by resolving the prefix, the explicit
namespace or the inherited namespace.
@rtype: (I{prefix}, I{name})
"""
if self.prefix is None:
return self.defaultNamespace()
return self.resolvePrefix(self.prefix) | Get the element's namespace.
@return: The element's namespace by resolving the prefix, the explicit
namespace or the inherited namespace.
@rtype: (I{prefix}, I{name}) | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/element.py#L299-L310 |
suds-community/suds | suds/sax/element.py | Element.defaultNamespace | def defaultNamespace(self):
"""
Get the default (unqualified namespace).
This is the expns of the first node (looking up the tree) that has it
set.
@return: The namespace of a node when not qualified.
@rtype: (I{prefix}, I{name})
"""
p = self
while p is not None:
if p.expns is not None:
return None, p.expns
p = p.parent
return Namespace.default | python | def defaultNamespace(self):
"""
Get the default (unqualified namespace).
This is the expns of the first node (looking up the tree) that has it
set.
@return: The namespace of a node when not qualified.
@rtype: (I{prefix}, I{name})
"""
p = self
while p is not None:
if p.expns is not None:
return None, p.expns
p = p.parent
return Namespace.default | Get the default (unqualified namespace).
This is the expns of the first node (looking up the tree) that has it
set.
@return: The namespace of a node when not qualified.
@rtype: (I{prefix}, I{name}) | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/element.py#L312-L328 |
suds-community/suds | suds/sax/element.py | Element.append | def append(self, objects):
"""
Append the specified child based on whether it is an element or an
attribute.
@param objects: A (single|collection) of attribute(s) or element(s) to
be added as children.
@type objects: (L{Element}|L{Attribute})
@return: self
@rtype: L{Element}
"""
if not isinstance(objects, (list, tuple)):
objects = (objects,)
for child in objects:
if isinstance(child, Element):
self.children.append(child)
child.parent = self
continue
if isinstance(child, Attribute):
self.attributes.append(child)
child.parent = self
continue
raise Exception("append %s not-valid" %
(child.__class__.__name__,))
return self | python | def append(self, objects):
"""
Append the specified child based on whether it is an element or an
attribute.
@param objects: A (single|collection) of attribute(s) or element(s) to
be added as children.
@type objects: (L{Element}|L{Attribute})
@return: self
@rtype: L{Element}
"""
if not isinstance(objects, (list, tuple)):
objects = (objects,)
for child in objects:
if isinstance(child, Element):
self.children.append(child)
child.parent = self
continue
if isinstance(child, Attribute):
self.attributes.append(child)
child.parent = self
continue
raise Exception("append %s not-valid" %
(child.__class__.__name__,))
return self | Append the specified child based on whether it is an element or an
attribute.
@param objects: A (single|collection) of attribute(s) or element(s) to
be added as children.
@type objects: (L{Element}|L{Attribute})
@return: self
@rtype: L{Element} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/element.py#L330-L355 |
suds-community/suds | suds/sax/element.py | Element.insert | def insert(self, objects, index=0):
"""
Insert an L{Element} content at the specified index.
@param objects: A (single|collection) of attribute(s) or element(s) to
be added as children.
@type objects: (L{Element}|L{Attribute})
@param index: The position in the list of children to insert.
@type index: int
@return: self
@rtype: L{Element}
"""
objects = (objects,)
for child in objects:
if not isinstance(child, Element):
raise Exception("append %s not-valid" %
(child.__class__.__name__,))
self.children.insert(index, child)
child.parent = self
return self | python | def insert(self, objects, index=0):
"""
Insert an L{Element} content at the specified index.
@param objects: A (single|collection) of attribute(s) or element(s) to
be added as children.
@type objects: (L{Element}|L{Attribute})
@param index: The position in the list of children to insert.
@type index: int
@return: self
@rtype: L{Element}
"""
objects = (objects,)
for child in objects:
if not isinstance(child, Element):
raise Exception("append %s not-valid" %
(child.__class__.__name__,))
self.children.insert(index, child)
child.parent = self
return self | Insert an L{Element} content at the specified index.
@param objects: A (single|collection) of attribute(s) or element(s) to
be added as children.
@type objects: (L{Element}|L{Attribute})
@param index: The position in the list of children to insert.
@type index: int
@return: self
@rtype: L{Element} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/element.py#L357-L377 |
suds-community/suds | suds/sax/element.py | Element.getChild | def getChild(self, name, ns=None, default=None):
"""
Get a child by (optional) name and/or (optional) namespace.
@param name: The name of a child element (may contain prefix).
@type name: basestring
@param ns: An optional namespace used to match the child.
@type ns: (I{prefix}, I{name})
@param default: Returned when child not-found.
@type default: L{Element}
@return: The requested child, or I{default} when not-found.
@rtype: L{Element}
"""
if ns is None:
prefix, name = splitPrefix(name)
if prefix is not None:
ns = self.resolvePrefix(prefix)
for c in self.children:
if c.match(name, ns):
return c
return default | python | def getChild(self, name, ns=None, default=None):
"""
Get a child by (optional) name and/or (optional) namespace.
@param name: The name of a child element (may contain prefix).
@type name: basestring
@param ns: An optional namespace used to match the child.
@type ns: (I{prefix}, I{name})
@param default: Returned when child not-found.
@type default: L{Element}
@return: The requested child, or I{default} when not-found.
@rtype: L{Element}
"""
if ns is None:
prefix, name = splitPrefix(name)
if prefix is not None:
ns = self.resolvePrefix(prefix)
for c in self.children:
if c.match(name, ns):
return c
return default | Get a child by (optional) name and/or (optional) namespace.
@param name: The name of a child element (may contain prefix).
@type name: basestring
@param ns: An optional namespace used to match the child.
@type ns: (I{prefix}, I{name})
@param default: Returned when child not-found.
@type default: L{Element}
@return: The requested child, or I{default} when not-found.
@rtype: L{Element} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/element.py#L438-L459 |
suds-community/suds | suds/sax/element.py | Element.childAtPath | def childAtPath(self, path):
"""
Get a child at I{path} where I{path} is a (/) separated list of element
names that are expected to be children.
@param path: A (/) separated list of element names.
@type path: basestring
@return: The leaf node at the end of I{path}.
@rtype: L{Element}
"""
result = None
node = self
for name in path.split("/"):
if not name:
continue
ns = None
prefix, name = splitPrefix(name)
if prefix is not None:
ns = node.resolvePrefix(prefix)
result = node.getChild(name, ns)
if result is None:
return
node = result
return result | python | def childAtPath(self, path):
"""
Get a child at I{path} where I{path} is a (/) separated list of element
names that are expected to be children.
@param path: A (/) separated list of element names.
@type path: basestring
@return: The leaf node at the end of I{path}.
@rtype: L{Element}
"""
result = None
node = self
for name in path.split("/"):
if not name:
continue
ns = None
prefix, name = splitPrefix(name)
if prefix is not None:
ns = node.resolvePrefix(prefix)
result = node.getChild(name, ns)
if result is None:
return
node = result
return result | Get a child at I{path} where I{path} is a (/) separated list of element
names that are expected to be children.
@param path: A (/) separated list of element names.
@type path: basestring
@return: The leaf node at the end of I{path}.
@rtype: L{Element} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/element.py#L461-L485 |
suds-community/suds | suds/sax/element.py | Element.childrenAtPath | def childrenAtPath(self, path):
"""
Get a list of children at I{path} where I{path} is a (/) separated list
of element names expected to be children.
@param path: A (/) separated list of element names.
@type path: basestring
@return: The collection leaf nodes at the end of I{path}.
@rtype: [L{Element},...]
"""
parts = [p for p in path.split("/") if p]
if len(parts) == 1:
return self.getChildren(path)
return self.__childrenAtPath(parts) | python | def childrenAtPath(self, path):
"""
Get a list of children at I{path} where I{path} is a (/) separated list
of element names expected to be children.
@param path: A (/) separated list of element names.
@type path: basestring
@return: The collection leaf nodes at the end of I{path}.
@rtype: [L{Element},...]
"""
parts = [p for p in path.split("/") if p]
if len(parts) == 1:
return self.getChildren(path)
return self.__childrenAtPath(parts) | Get a list of children at I{path} where I{path} is a (/) separated list
of element names expected to be children.
@param path: A (/) separated list of element names.
@type path: basestring
@return: The collection leaf nodes at the end of I{path}.
@rtype: [L{Element},...] | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/element.py#L487-L501 |
suds-community/suds | suds/sax/element.py | Element.getChildren | def getChildren(self, name=None, ns=None):
"""
Get a list of children by (optional) name and/or (optional) namespace.
@param name: The name of a child element (may contain a prefix).
@type name: basestring
@param ns: An optional namespace used to match the child.
@type ns: (I{prefix}, I{name})
@return: The list of matching children.
@rtype: [L{Element},...]
"""
if ns is None:
if name is None:
return self.children
prefix, name = splitPrefix(name)
if prefix is not None:
ns = self.resolvePrefix(prefix)
return [c for c in self.children if c.match(name, ns)] | python | def getChildren(self, name=None, ns=None):
"""
Get a list of children by (optional) name and/or (optional) namespace.
@param name: The name of a child element (may contain a prefix).
@type name: basestring
@param ns: An optional namespace used to match the child.
@type ns: (I{prefix}, I{name})
@return: The list of matching children.
@rtype: [L{Element},...]
"""
if ns is None:
if name is None:
return self.children
prefix, name = splitPrefix(name)
if prefix is not None:
ns = self.resolvePrefix(prefix)
return [c for c in self.children if c.match(name, ns)] | Get a list of children by (optional) name and/or (optional) namespace.
@param name: The name of a child element (may contain a prefix).
@type name: basestring
@param ns: An optional namespace used to match the child.
@type ns: (I{prefix}, I{name})
@return: The list of matching children.
@rtype: [L{Element},...] | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/element.py#L503-L521 |
suds-community/suds | suds/sax/element.py | Element.promotePrefixes | def promotePrefixes(self):
"""
Push prefix declarations up the tree as far as possible.
Prefix mapping are pushed to its parent unless the parent has the
prefix mapped to another URI or the parent has the prefix. This is
propagated up the tree until the top is reached.
@return: self
@rtype: L{Element}
"""
for c in self.children:
c.promotePrefixes()
if self.parent is None:
return
for p, u in self.nsprefixes.items():
if p in self.parent.nsprefixes:
pu = self.parent.nsprefixes[p]
if pu == u:
del self.nsprefixes[p]
continue
if p != self.parent.prefix:
self.parent.nsprefixes[p] = u
del self.nsprefixes[p]
return self | python | def promotePrefixes(self):
"""
Push prefix declarations up the tree as far as possible.
Prefix mapping are pushed to its parent unless the parent has the
prefix mapped to another URI or the parent has the prefix. This is
propagated up the tree until the top is reached.
@return: self
@rtype: L{Element}
"""
for c in self.children:
c.promotePrefixes()
if self.parent is None:
return
for p, u in self.nsprefixes.items():
if p in self.parent.nsprefixes:
pu = self.parent.nsprefixes[p]
if pu == u:
del self.nsprefixes[p]
continue
if p != self.parent.prefix:
self.parent.nsprefixes[p] = u
del self.nsprefixes[p]
return self | Push prefix declarations up the tree as far as possible.
Prefix mapping are pushed to its parent unless the parent has the
prefix mapped to another URI or the parent has the prefix. This is
propagated up the tree until the top is reached.
@return: self
@rtype: L{Element} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/element.py#L662-L687 |
suds-community/suds | suds/sax/element.py | Element.isempty | def isempty(self, content=True):
"""
Get whether the element has no children.
@param content: Test content (children & text) only.
@type content: boolean
@return: True when element has not children.
@rtype: boolean
"""
nochildren = not self.children
notext = self.text is None
nocontent = nochildren and notext
if content:
return nocontent
noattrs = not len(self.attributes)
return nocontent and noattrs | python | def isempty(self, content=True):
"""
Get whether the element has no children.
@param content: Test content (children & text) only.
@type content: boolean
@return: True when element has not children.
@rtype: boolean
"""
nochildren = not self.children
notext = self.text is None
nocontent = nochildren and notext
if content:
return nocontent
noattrs = not len(self.attributes)
return nocontent and noattrs | Get whether the element has no children.
@param content: Test content (children & text) only.
@type content: boolean
@return: True when element has not children.
@rtype: boolean | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/element.py#L723-L739 |
suds-community/suds | suds/sax/element.py | Element.isnil | def isnil(self):
"""
Get whether the element is I{nil} as defined by having an
I{xsi:nil="true"} attribute.
@return: True if I{nil}, else False
@rtype: boolean
"""
nilattr = self.getAttribute("nil", ns=Namespace.xsins)
return nilattr is not None and (nilattr.getValue().lower() == "true") | python | def isnil(self):
"""
Get whether the element is I{nil} as defined by having an
I{xsi:nil="true"} attribute.
@return: True if I{nil}, else False
@rtype: boolean
"""
nilattr = self.getAttribute("nil", ns=Namespace.xsins)
return nilattr is not None and (nilattr.getValue().lower() == "true") | Get whether the element is I{nil} as defined by having an
I{xsi:nil="true"} attribute.
@return: True if I{nil}, else False
@rtype: boolean | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/element.py#L741-L751 |
suds-community/suds | suds/sax/element.py | Element.setnil | def setnil(self, flag=True):
"""
Set this node to I{nil} as defined by having an I{xsi:nil}=I{flag}
attribute.
@param flag: A flag indicating how I{xsi:nil} will be set.
@type flag: boolean
@return: self
@rtype: L{Element}
"""
p, u = Namespace.xsins
name = ":".join((p, "nil"))
self.set(name, str(flag).lower())
self.addPrefix(p, u)
if flag:
self.text = None
return self | python | def setnil(self, flag=True):
"""
Set this node to I{nil} as defined by having an I{xsi:nil}=I{flag}
attribute.
@param flag: A flag indicating how I{xsi:nil} will be set.
@type flag: boolean
@return: self
@rtype: L{Element}
"""
p, u = Namespace.xsins
name = ":".join((p, "nil"))
self.set(name, str(flag).lower())
self.addPrefix(p, u)
if flag:
self.text = None
return self | Set this node to I{nil} as defined by having an I{xsi:nil}=I{flag}
attribute.
@param flag: A flag indicating how I{xsi:nil} will be set.
@type flag: boolean
@return: self
@rtype: L{Element} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/element.py#L753-L770 |
suds-community/suds | suds/sax/element.py | Element.applyns | def applyns(self, ns):
"""
Apply the namespace to this node.
If the prefix is I{None} then this element's explicit namespace
I{expns} is set to the URI defined by I{ns}. Otherwise, the I{ns} is
simply mapped.
@param ns: A namespace.
@type ns: (I{prefix}, I{URI})
"""
if ns is None:
return
if not isinstance(ns, (list, tuple)):
raise Exception("namespace must be a list or a tuple")
if ns[0] is None:
self.expns = ns[1]
else:
self.prefix = ns[0]
self.nsprefixes[ns[0]] = ns[1] | python | def applyns(self, ns):
"""
Apply the namespace to this node.
If the prefix is I{None} then this element's explicit namespace
I{expns} is set to the URI defined by I{ns}. Otherwise, the I{ns} is
simply mapped.
@param ns: A namespace.
@type ns: (I{prefix}, I{URI})
"""
if ns is None:
return
if not isinstance(ns, (list, tuple)):
raise Exception("namespace must be a list or a tuple")
if ns[0] is None:
self.expns = ns[1]
else:
self.prefix = ns[0]
self.nsprefixes[ns[0]] = ns[1] | Apply the namespace to this node.
If the prefix is I{None} then this element's explicit namespace
I{expns} is set to the URI defined by I{ns}. Otherwise, the I{ns} is
simply mapped.
@param ns: A namespace.
@type ns: (I{prefix}, I{URI}) | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/element.py#L772-L792 |
suds-community/suds | suds/sax/element.py | Element.str | def str(self, indent=0):
"""
Get a string representation of this XML fragment.
@param indent: The indent to be used in formatting the output.
@type indent: int
@return: A I{pretty} string.
@rtype: basestring
"""
tab = "%*s" % (indent * 3, "")
result = []
result.append("%s<%s" % (tab, self.qname()))
result.append(self.nsdeclarations())
for a in self.attributes:
result.append(" %s" % (unicode(a),))
if self.isempty():
result.append("/>")
return "".join(result)
result.append(">")
if self.hasText():
result.append(self.text.escape())
for c in self.children:
result.append("\n")
result.append(c.str(indent + 1))
if len(self.children):
result.append("\n%s" % (tab,))
result.append("</%s>" % (self.qname(),))
return "".join(result) | python | def str(self, indent=0):
"""
Get a string representation of this XML fragment.
@param indent: The indent to be used in formatting the output.
@type indent: int
@return: A I{pretty} string.
@rtype: basestring
"""
tab = "%*s" % (indent * 3, "")
result = []
result.append("%s<%s" % (tab, self.qname()))
result.append(self.nsdeclarations())
for a in self.attributes:
result.append(" %s" % (unicode(a),))
if self.isempty():
result.append("/>")
return "".join(result)
result.append(">")
if self.hasText():
result.append(self.text.escape())
for c in self.children:
result.append("\n")
result.append(c.str(indent + 1))
if len(self.children):
result.append("\n%s" % (tab,))
result.append("</%s>" % (self.qname(),))
return "".join(result) | Get a string representation of this XML fragment.
@param indent: The indent to be used in formatting the output.
@type indent: int
@return: A I{pretty} string.
@rtype: basestring | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/element.py#L794-L822 |
suds-community/suds | suds/sax/element.py | Element.plain | def plain(self):
"""
Get a string representation of this XML fragment.
@return: A I{plain} string.
@rtype: basestring
"""
result = ["<%s" % (self.qname(),), self.nsdeclarations()]
for a in self.attributes:
result.append(" %s" % (unicode(a),))
if self.isempty():
result.append("/>")
return "".join(result)
result.append(">")
if self.hasText():
result.append(self.text.escape())
for c in self.children:
result.append(c.plain())
result.append("</%s>" % (self.qname(),))
return "".join(result) | python | def plain(self):
"""
Get a string representation of this XML fragment.
@return: A I{plain} string.
@rtype: basestring
"""
result = ["<%s" % (self.qname(),), self.nsdeclarations()]
for a in self.attributes:
result.append(" %s" % (unicode(a),))
if self.isempty():
result.append("/>")
return "".join(result)
result.append(">")
if self.hasText():
result.append(self.text.escape())
for c in self.children:
result.append(c.plain())
result.append("</%s>" % (self.qname(),))
return "".join(result) | Get a string representation of this XML fragment.
@return: A I{plain} string.
@rtype: basestring | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/element.py#L824-L844 |
suds-community/suds | suds/sax/element.py | Element.nsdeclarations | def nsdeclarations(self):
"""
Get a string representation for all namespace declarations as xmlns=""
and xmlns:p="".
@return: A separated list of declarations.
@rtype: basestring
"""
s = []
myns = None, self.expns
if self.parent is None:
pns = Namespace.default
else:
pns = None, self.parent.expns
if myns[1] != pns[1]:
if self.expns is not None:
s.append(' xmlns="%s"' % (self.expns,))
for item in self.nsprefixes.items():
p, u = item
if self.parent is not None:
ns = self.parent.resolvePrefix(p)
if ns[1] == u:
continue
s.append(' xmlns:%s="%s"' % (p, u))
return "".join(s) | python | def nsdeclarations(self):
"""
Get a string representation for all namespace declarations as xmlns=""
and xmlns:p="".
@return: A separated list of declarations.
@rtype: basestring
"""
s = []
myns = None, self.expns
if self.parent is None:
pns = Namespace.default
else:
pns = None, self.parent.expns
if myns[1] != pns[1]:
if self.expns is not None:
s.append(' xmlns="%s"' % (self.expns,))
for item in self.nsprefixes.items():
p, u = item
if self.parent is not None:
ns = self.parent.resolvePrefix(p)
if ns[1] == u:
continue
s.append(' xmlns:%s="%s"' % (p, u))
return "".join(s) | Get a string representation for all namespace declarations as xmlns=""
and xmlns:p="".
@return: A separated list of declarations.
@rtype: basestring | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/element.py#L846-L871 |
suds-community/suds | suds/reader.py | DefinitionsReader.open | def open(self, url):
"""
Open a WSDL schema at the specified I{URL}.
First, the WSDL schema is looked up in the I{object cache}. If not
found, a new one constructed using the I{fn} factory function and the
result is cached for the next open().
@param url: A WSDL URL.
@type url: str.
@return: The WSDL object.
@rtype: I{Definitions}
"""
cache = self.__cache()
id = self.mangle(url, "wsdl")
wsdl = cache.get(id)
if wsdl is None:
wsdl = self.fn(url, self.options)
cache.put(id, wsdl)
else:
# Cached WSDL Definitions objects may have been created with
# different options so we update them here with our current ones.
wsdl.options = self.options
for imp in wsdl.imports:
imp.imported.options = self.options
return wsdl | python | def open(self, url):
"""
Open a WSDL schema at the specified I{URL}.
First, the WSDL schema is looked up in the I{object cache}. If not
found, a new one constructed using the I{fn} factory function and the
result is cached for the next open().
@param url: A WSDL URL.
@type url: str.
@return: The WSDL object.
@rtype: I{Definitions}
"""
cache = self.__cache()
id = self.mangle(url, "wsdl")
wsdl = cache.get(id)
if wsdl is None:
wsdl = self.fn(url, self.options)
cache.put(id, wsdl)
else:
# Cached WSDL Definitions objects may have been created with
# different options so we update them here with our current ones.
wsdl.options = self.options
for imp in wsdl.imports:
imp.imported.options = self.options
return wsdl | Open a WSDL schema at the specified I{URL}.
First, the WSDL schema is looked up in the I{object cache}. If not
found, a new one constructed using the I{fn} factory function and the
result is cached for the next open().
@param url: A WSDL URL.
@type url: str.
@return: The WSDL object.
@rtype: I{Definitions} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/reader.py#L86-L112 |
suds-community/suds | suds/reader.py | DefinitionsReader.__cache | def __cache(self):
"""
Get the I{object cache}.
@return: The I{cache} when I{cachingpolicy} = B{1}.
@rtype: L{Cache}
"""
if self.options.cachingpolicy == 1:
return self.options.cache
return suds.cache.NoCache() | python | def __cache(self):
"""
Get the I{object cache}.
@return: The I{cache} when I{cachingpolicy} = B{1}.
@rtype: L{Cache}
"""
if self.options.cachingpolicy == 1:
return self.options.cache
return suds.cache.NoCache() | Get the I{object cache}.
@return: The I{cache} when I{cachingpolicy} = B{1}.
@rtype: L{Cache} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/reader.py#L114-L124 |
suds-community/suds | suds/reader.py | DocumentReader.open | def open(self, url):
"""
Open an XML document at the specified I{URL}.
First, a preparsed document is looked up in the I{object cache}. If not
found, its content is fetched from an external source and parsed using
the SAX parser. The result is cached for the next open().
@param url: A document URL.
@type url: str.
@return: The specified XML document.
@rtype: I{Document}
"""
cache = self.__cache()
id = self.mangle(url, "document")
xml = cache.get(id)
if xml is None:
xml = self.__fetch(url)
cache.put(id, xml)
self.plugins.document.parsed(url=url, document=xml.root())
return xml | python | def open(self, url):
"""
Open an XML document at the specified I{URL}.
First, a preparsed document is looked up in the I{object cache}. If not
found, its content is fetched from an external source and parsed using
the SAX parser. The result is cached for the next open().
@param url: A document URL.
@type url: str.
@return: The specified XML document.
@rtype: I{Document}
"""
cache = self.__cache()
id = self.mangle(url, "document")
xml = cache.get(id)
if xml is None:
xml = self.__fetch(url)
cache.put(id, xml)
self.plugins.document.parsed(url=url, document=xml.root())
return xml | Open an XML document at the specified I{URL}.
First, a preparsed document is looked up in the I{object cache}. If not
found, its content is fetched from an external source and parsed using
the SAX parser. The result is cached for the next open().
@param url: A document URL.
@type url: str.
@return: The specified XML document.
@rtype: I{Document} | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/reader.py#L130-L151 |
suds-community/suds | suds/reader.py | DocumentReader.__fetch | def __fetch(self, url):
"""
Fetch document content from an external source.
The document content will first be looked up in the registered document
store, and if not found there, downloaded using the registered
transport system.
Before being returned, the fetched document content first gets
processed by all the registered 'loaded' plugins.
@param url: A document URL.
@type url: str.
@return: A file pointer to the fetched document content.
@rtype: file-like
"""
content = None
store = self.options.documentStore
if store is not None:
content = store.open(url)
if content is None:
request = suds.transport.Request(url)
fp = self.options.transport.open(request)
try:
content = fp.read()
finally:
fp.close()
ctx = self.plugins.document.loaded(url=url, document=content)
content = ctx.document
sax = suds.sax.parser.Parser()
return sax.parse(string=content) | python | def __fetch(self, url):
"""
Fetch document content from an external source.
The document content will first be looked up in the registered document
store, and if not found there, downloaded using the registered
transport system.
Before being returned, the fetched document content first gets
processed by all the registered 'loaded' plugins.
@param url: A document URL.
@type url: str.
@return: A file pointer to the fetched document content.
@rtype: file-like
"""
content = None
store = self.options.documentStore
if store is not None:
content = store.open(url)
if content is None:
request = suds.transport.Request(url)
fp = self.options.transport.open(request)
try:
content = fp.read()
finally:
fp.close()
ctx = self.plugins.document.loaded(url=url, document=content)
content = ctx.document
sax = suds.sax.parser.Parser()
return sax.parse(string=content) | Fetch document content from an external source.
The document content will first be looked up in the registered document
store, and if not found there, downloaded using the registered
transport system.
Before being returned, the fetched document content first gets
processed by all the registered 'loaded' plugins.
@param url: A document URL.
@type url: str.
@return: A file pointer to the fetched document content.
@rtype: file-like | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/reader.py#L165-L196 |
suds-community/suds | suds/sax/enc.py | Encoder.encode | def encode(self, s):
"""
Encode special characters found in string I{s}.
@param s: A string to encode.
@type s: str
@return: The encoded string.
@rtype: str
"""
if isinstance(s, basestring) and self.__needs_encoding(s):
for x in self.encodings:
s = re.sub(x[0], x[1], s)
return s | python | def encode(self, s):
"""
Encode special characters found in string I{s}.
@param s: A string to encode.
@type s: str
@return: The encoded string.
@rtype: str
"""
if isinstance(s, basestring) and self.__needs_encoding(s):
for x in self.encodings:
s = re.sub(x[0], x[1], s)
return s | Encode special characters found in string I{s}.
@param s: A string to encode.
@type s: str
@return: The encoded string.
@rtype: str | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/enc.py#L51-L64 |
suds-community/suds | suds/sax/enc.py | Encoder.__needs_encoding | def __needs_encoding(self, s):
"""
Get whether string I{s} contains special characters.
@param s: A string to check.
@type s: str
@return: True if needs encoding.
@rtype: boolean
"""
if isinstance(s, basestring):
for c in self.special:
if c in s:
return True | python | def __needs_encoding(self, s):
"""
Get whether string I{s} contains special characters.
@param s: A string to check.
@type s: str
@return: True if needs encoding.
@rtype: boolean
"""
if isinstance(s, basestring):
for c in self.special:
if c in s:
return True | Get whether string I{s} contains special characters.
@param s: A string to check.
@type s: str
@return: True if needs encoding.
@rtype: boolean | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/enc.py#L81-L94 |
suds-community/suds | tools/suds_devel/requirements.py | virtualenv_requirements | def virtualenv_requirements(version_info=sys.version_info):
"""
Generate Python version specific virtualenv package requirements.
The requirements are returned as setuptools/pip compatible requirement
specification strings.
"""
if version_info < (2, 5):
# 'virtualenv' release 1.8 dropped Python 2.4.x compatibility.
yield requirement_spec("virtualenv",
("<", lowest_version_string_with_prefix("1.8")))
elif version_info < (2, 6):
# 'virtualenv' release 1.10 dropped Python 2.5.x compatibility.
yield requirement_spec("virtualenv",
("<", lowest_version_string_with_prefix("1.10")))
else:
yield requirement_spec("virtualenv") | python | def virtualenv_requirements(version_info=sys.version_info):
"""
Generate Python version specific virtualenv package requirements.
The requirements are returned as setuptools/pip compatible requirement
specification strings.
"""
if version_info < (2, 5):
# 'virtualenv' release 1.8 dropped Python 2.4.x compatibility.
yield requirement_spec("virtualenv",
("<", lowest_version_string_with_prefix("1.8")))
elif version_info < (2, 6):
# 'virtualenv' release 1.10 dropped Python 2.5.x compatibility.
yield requirement_spec("virtualenv",
("<", lowest_version_string_with_prefix("1.10")))
else:
yield requirement_spec("virtualenv") | Generate Python version specific virtualenv package requirements.
The requirements are returned as setuptools/pip compatible requirement
specification strings. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/suds_devel/requirements.py#L267-L284 |
suds-community/suds | tools/suds_devel/environment.py | Environment.__construct_python_version | def __construct_python_version(self):
"""
Construct a setuptools compatible Python version string.
Constructed based on the environment's reported sys.version_info.
"""
major, minor, micro, release_level, serial = self.sys_version_info
assert release_level in ("alfa", "beta", "candidate", "final")
assert release_level != "final" or serial == 0
parts = [str(major), ".", str(minor), ".", str(micro)]
if release_level != "final":
parts.append(release_level[0])
parts.append(str(serial))
self.python_version = "".join(parts) | python | def __construct_python_version(self):
"""
Construct a setuptools compatible Python version string.
Constructed based on the environment's reported sys.version_info.
"""
major, minor, micro, release_level, serial = self.sys_version_info
assert release_level in ("alfa", "beta", "candidate", "final")
assert release_level != "final" or serial == 0
parts = [str(major), ".", str(minor), ".", str(micro)]
if release_level != "final":
parts.append(release_level[0])
parts.append(str(serial))
self.python_version = "".join(parts) | Construct a setuptools compatible Python version string.
Constructed based on the environment's reported sys.version_info. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/suds_devel/environment.py#L164-L178 |
suds-community/suds | tools/suds_devel/environment.py | Environment.__parse_scanned_version_info | def __parse_scanned_version_info(self):
"""Parses the environment's formatted version info string."""
string = self.sys_version_info_formatted
try:
major, minor, micro, release_level, serial = string.split(",")
if (release_level in ("alfa", "beta", "candidate", "final") and
(release_level != "final" or serial == "0") and
major.isdigit() and # --- --- --- --- --- --- --- --- ---
minor.isdigit() and # Explicit isdigit() checks to detect
micro.isdigit() and # leading/trailing whitespace.
serial.isdigit()): # --- --- --- --- --- --- --- --- ---
self.sys_version_info = (int(major), int(minor), int(micro),
release_level, int(serial))
self.__construct_python_version()
return
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
pass
raise BadEnvironment("Unsupported Python version (%s)" % (string,)) | python | def __parse_scanned_version_info(self):
"""Parses the environment's formatted version info string."""
string = self.sys_version_info_formatted
try:
major, minor, micro, release_level, serial = string.split(",")
if (release_level in ("alfa", "beta", "candidate", "final") and
(release_level != "final" or serial == "0") and
major.isdigit() and # --- --- --- --- --- --- --- --- ---
minor.isdigit() and # Explicit isdigit() checks to detect
micro.isdigit() and # leading/trailing whitespace.
serial.isdigit()): # --- --- --- --- --- --- --- --- ---
self.sys_version_info = (int(major), int(minor), int(micro),
release_level, int(serial))
self.__construct_python_version()
return
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
pass
raise BadEnvironment("Unsupported Python version (%s)" % (string,)) | Parses the environment's formatted version info string. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/tools/suds_devel/environment.py#L233-L252 |
suds-community/suds | suds/sudsobject.py | Printer.print_dictionary | def print_dictionary(self, d, h, n, nl=False):
"""Print complex using the specified indent (n) and newline (nl)."""
if d in h:
return "{}..."
h.append(d)
s = []
if nl:
s.append("\n")
s.append(self.indent(n))
s.append("{")
for item in d.items():
s.append("\n")
s.append(self.indent(n+1))
if isinstance(item[1], (list,tuple)):
s.append(tostr(item[0]))
s.append("[]")
else:
s.append(tostr(item[0]))
s.append(" = ")
s.append(self.process(item[1], h, n, True))
s.append("\n")
s.append(self.indent(n))
s.append("}")
h.pop()
return "".join(s) | python | def print_dictionary(self, d, h, n, nl=False):
"""Print complex using the specified indent (n) and newline (nl)."""
if d in h:
return "{}..."
h.append(d)
s = []
if nl:
s.append("\n")
s.append(self.indent(n))
s.append("{")
for item in d.items():
s.append("\n")
s.append(self.indent(n+1))
if isinstance(item[1], (list,tuple)):
s.append(tostr(item[0]))
s.append("[]")
else:
s.append(tostr(item[0]))
s.append(" = ")
s.append(self.process(item[1], h, n, True))
s.append("\n")
s.append(self.indent(n))
s.append("}")
h.pop()
return "".join(s) | Print complex using the specified indent (n) and newline (nl). | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sudsobject.py#L326-L350 |
suds-community/suds | suds/sudsobject.py | Printer.print_collection | def print_collection(self, c, h, n):
"""Print collection using the specified indent (n) and newline (nl)."""
if c in h:
return "[]..."
h.append(c)
s = []
for item in c:
s.append("\n")
s.append(self.indent(n))
s.append(self.process(item, h, n - 2))
s.append(",")
h.pop()
return "".join(s) | python | def print_collection(self, c, h, n):
"""Print collection using the specified indent (n) and newline (nl)."""
if c in h:
return "[]..."
h.append(c)
s = []
for item in c:
s.append("\n")
s.append(self.indent(n))
s.append(self.process(item, h, n - 2))
s.append(",")
h.pop()
return "".join(s) | Print collection using the specified indent (n) and newline (nl). | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sudsobject.py#L352-L364 |
suds-community/suds | suds/mx/literal.py | Typed.node | def node(self, content):
"""
Create an XML node.
The XML node is namespace qualified as defined by the corresponding
schema element.
"""
ns = content.type.namespace()
if content.type.form_qualified:
node = Element(content.tag, ns=ns)
if ns[0]:
node.addPrefix(ns[0], ns[1])
else:
node = Element(content.tag)
self.encode(node, content)
log.debug("created - node:\n%s", node)
return node | python | def node(self, content):
"""
Create an XML node.
The XML node is namespace qualified as defined by the corresponding
schema element.
"""
ns = content.type.namespace()
if content.type.form_qualified:
node = Element(content.tag, ns=ns)
if ns[0]:
node.addPrefix(ns[0], ns[1])
else:
node = Element(content.tag)
self.encode(node, content)
log.debug("created - node:\n%s", node)
return node | Create an XML node.
The XML node is namespace qualified as defined by the corresponding
schema element. | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/mx/literal.py#L143-L160 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.