Browse Source

removing print

main
Julien Iguchi-Cartigny 10 years ago
parent
commit
bc8598c2e6
3 changed files with 87 additions and 45 deletions
  1. +2
    -1
      wstools/UserTuple.py
  2. +81
    -40
      wstools/Utility.py
  3. +4
    -4
      wstools/WSDLTools.py

+ 2
- 1
wstools/UserTuple.py View File

@@ -3,7 +3,8 @@ A more or less complete user-defined wrapper around tuple objects.
Adapted version of the standard library's UserList. Adapted version of the standard library's UserList.


Taken from Stefan Schwarzer's ftputil library, available at Taken from Stefan Schwarzer's ftputil library, available at
<http://www.ndh.net/home/sschwarzer/python/python_software.html>, and used under this license: <http://www.ndh.net/home/sschwarzer/python/python_software.html>,
and used under this license:








+ 81
- 40
wstools/Utility.py View File

@@ -91,28 +91,35 @@ if sys.version_info[0:2] < (2, 4, 0, 'final', 0)[0:2]:




class NamespaceError(Exception): class NamespaceError(Exception):

"""Used to indicate a Namespace Error.""" """Used to indicate a Namespace Error."""




class RecursionError(Exception): class RecursionError(Exception):

"""Used to indicate a HTTP redirect recursion.""" """Used to indicate a HTTP redirect recursion."""




class ParseError(Exception): class ParseError(Exception):

"""Used to indicate a XML parsing error.""" """Used to indicate a XML parsing error."""




class DOMException(Exception): class DOMException(Exception):

"""Used to indicate a problem processing DOM.""" """Used to indicate a problem processing DOM."""




class Base: class Base:

"""Base class for instance level Logging""" """Base class for instance level Logging"""
def __init__(self, logger = None): def __init__(self, logger=None):
self.logger = logger or logging.getLogger(__name__) self.logger = logger or logging.getLogger(__name__)




class HTTPResponse: class HTTPResponse:

"""Captures the information in an HTTP response message.""" """Captures the information in an HTTP response message."""


def __init__(self, response): def __init__(self, response):
@@ -124,7 +131,9 @@ class HTTPResponse:




class TimeoutHTTP(HTTPConnection): class TimeoutHTTP(HTTPConnection):

"""A custom http connection object that supports socket timeout.""" """A custom http connection object that supports socket timeout."""

def __init__(self, host, port=None, timeout=20): def __init__(self, host, port=None, timeout=20):
HTTPConnection.__init__(self, host, port) HTTPConnection.__init__(self, host, port)
self.timeout = timeout self.timeout = timeout
@@ -135,12 +144,14 @@ class TimeoutHTTP(HTTPConnection):




class TimeoutHTTPS(HTTPSConnection): class TimeoutHTTPS(HTTPSConnection):

"""A custom https object that supports socket timeout. Note that this """A custom https object that supports socket timeout. Note that this
is not really complete. The builtin SSL support in the Python socket is not really complete. The builtin SSL support in the Python socket
module requires a real socket (type) to be passed in to be hooked to module requires a real socket (type) to be passed in to be hooked to
SSL. That means our fake socket won't work and our timeout hacks are SSL. That means our fake socket won't work and our timeout hacks are
bypassed for send and recv calls. Since our hack _is_ in place at bypassed for send and recv calls. Since our hack _is_ in place at
connect() time, it should at least provide some timeout protection.""" connect() time, it should at least provide some timeout protection."""

def __init__(self, host, port=None, timeout=20, **kwargs): def __init__(self, host, port=None, timeout=20, **kwargs):
HTTPSConnection.__init__(self, str(host), port, **kwargs) HTTPSConnection.__init__(self, str(host), port, **kwargs)
self.timeout = timeout self.timeout = timeout
@@ -224,15 +235,16 @@ def urlopen(url, timeout=20, redirects=None):




class DOM: class DOM:

"""The DOM singleton defines a number of XML related constants and """The DOM singleton defines a number of XML related constants and
provides a number of utility methods for DOM related tasks. It provides a number of utility methods for DOM related tasks. It
also provides some basic abstractions so that the rest of the also provides some basic abstractions so that the rest of the
package need not care about actual DOM implementation in use.""" package need not care about actual DOM implementation in use."""


looseNamespaces = False # if can't find a referenced namespace, try the default one # if can't find a referenced namespace, try the default one
looseNamespaces = False


# Namespace stuff related to the SOAP specification. # Namespace stuff related to the SOAP specification.

NS_SOAP_ENV_1_1 = 'http://schemas.xmlsoap.org/soap/envelope/' NS_SOAP_ENV_1_1 = 'http://schemas.xmlsoap.org/soap/envelope/'
NS_SOAP_ENC_1_1 = 'http://schemas.xmlsoap.org/soap/encoding/' NS_SOAP_ENC_1_1 = 'http://schemas.xmlsoap.org/soap/encoding/'


@@ -419,7 +431,7 @@ class DOM:
if node.nodeType != node.ELEMENT_NODE: if node.nodeType != node.ELEMENT_NODE:
return 0 return 0
return node.localName == name and \ return node.localName == name and \
(nsuri is None or self.nsUriMatch(node.namespaceURI, nsuri)) (nsuri is None or self.nsUriMatch(node.namespaceURI, nsuri))


def getElement(self, node, name, nsuri=None, default=join): def getElement(self, node, name, nsuri=None, default=join):
"""Return the first child of node with a matching name and """Return the first child of node with a matching name and
@@ -429,8 +441,7 @@ class DOM:
for child in node.childNodes: for child in node.childNodes:
if child.nodeType == ELEMENT_NODE: if child.nodeType == ELEMENT_NODE:
if ((child.localName == name or name is None) and if ((child.localName == name or name is None) and
(nsuri is None or nsmatch(child.namespaceURI, nsuri)) (nsuri is None or nsmatch(child.namespaceURI, nsuri))):
):
return child return child
if default is not join: if default is not join:
return default return default
@@ -555,7 +566,8 @@ class DOM:
if DOM.looseNamespaces: if DOM.looseNamespaces:
return self.findTargetNS(orig_node) return self.findTargetNS(orig_node)
else: else:
raise DOMException('Value for prefix %s not found.' % prefix) raise DOMException('Value for prefix %s not found.'
% prefix)


def findDefaultNS(self, node): def findDefaultNS(self, node):
"""Return the current default namespace uri for the given node.""" """Return the current default namespace uri for the given node."""
@@ -664,9 +676,11 @@ DOM = DOM()




class MessageInterface: class MessageInterface:

'''Higher Level Interface, delegates to DOM singleton, must '''Higher Level Interface, delegates to DOM singleton, must
be subclassed and implement all methods that throw NotImplementedError. be subclassed and implement all methods that throw NotImplementedError.
''' '''

def __init__(self, sw): def __init__(self, sw):
'''Constructor, May be extended, do not override. '''Constructor, May be extended, do not override.
sw -- soapWriter instance sw -- soapWriter instance
@@ -725,8 +739,7 @@ class MessageInterface:




class ElementProxy(Base, MessageInterface): class ElementProxy(Base, MessageInterface):
'''
'''
_soap_env_prefix = 'SOAP-ENV' _soap_env_prefix = 'SOAP-ENV'
_soap_enc_prefix = 'SOAP-ENC' _soap_enc_prefix = 'SOAP-ENC'
_zsi_prefix = 'ZSI' _zsi_prefix = 'ZSI'
@@ -743,11 +756,11 @@ class ElementProxy(Base, MessageInterface):
_xml_nsuri = XMLNS.XML _xml_nsuri = XMLNS.XML
_xmlns_nsuri = XMLNS.BASE _xmlns_nsuri = XMLNS.BASE


standard_ns = {\ standard_ns = {
_xml_prefix: _xml_nsuri, _xml_prefix: _xml_nsuri,
_xmlns_prefix: _xmlns_nsuri _xmlns_prefix: _xmlns_nsuri
} }
reserved_ns = {\ reserved_ns = {
_soap_env_prefix: _soap_env_nsuri, _soap_env_prefix: _soap_env_nsuri,
_soap_enc_prefix: _soap_enc_nsuri, _soap_enc_prefix: _soap_enc_nsuri,
_zsi_prefix: _zsi_nsuri, _zsi_prefix: _zsi_nsuri,
@@ -783,9 +796,11 @@ class ElementProxy(Base, MessageInterface):
''' '''
from Ft.Xml import XPath from Ft.Xml import XPath
if not processorNss: if not processorNss:
context = XPath.Context.Context(self.node, processorNss=self.processorNss) context = XPath.Context.Context(self.node,
processorNss=self.processorNss)
else: else:
context = XPath.Context.Context(self.node, processorNss=processorNss) context = XPath.Context.Context(self.node,
processorNss=processorNss)
nodes = expression.evaluate(context) nodes = expression.evaluate(context)
return map(lambda node: ElementProxy(self.sw, node), nodes) return map(lambda node: ElementProxy(self.sw, node), nodes)


@@ -804,7 +819,8 @@ class ElementProxy(Base, MessageInterface):
if localName and self.node: if localName and self.node:
check = self._dom.isElement(self.node, localName, namespaceURI) check = self._dom.isElement(self.node, localName, namespaceURI)
if not check: if not check:
raise NamespaceError('unexpected node type %s, expecting %s' % (self.node, localName)) raise NamespaceError('unexpected node type %s, expecting %s'
% (self.node, localName))


def setNode(self, node=None): def setNode(self, node=None):
if node: if node:
@@ -813,13 +829,15 @@ class ElementProxy(Base, MessageInterface):
else: else:
self.node = node self.node = node
elif self.node: elif self.node:
node = self._dom.getElement(self.node, self.name, self.namespaceURI, default=None) node = self._dom.getElement(self.node, self.name,
self.namespaceURI, default=None)
if not node: if not node:
raise NamespaceError('cant find element (%s, %s)' % (self.namespaceURI, self.name)) raise NamespaceError('cant find element (%s, %s)' %
(self.namespaceURI, self.name))
self.node = node self.node = node
else: else:
#self.node = self._dom.create(self.node, self.name, self.namespaceURI, default=None) self.createDocument(self.namespaceURI, localName=self.name,
self.createDocument(self.namespaceURI, localName=self.name, doctype=None) doctype=None)


self.checkNode() self.checkNode()


@@ -857,7 +875,7 @@ class ElementProxy(Base, MessageInterface):
''' '''
try: try:
if node and (node.nodeType == node.ELEMENT_NODE) and \ if node and (node.nodeType == node.ELEMENT_NODE) and \
(nsuri == self._dom.findDefaultNS(node)): (nsuri == self._dom.findDefaultNS(node)):
return None return None
except DOMException, ex: except DOMException, ex:
pass pass
@@ -942,7 +960,8 @@ class ElementProxy(Base, MessageInterface):
return self.canonicalize() return self.canonicalize()


def createDocument(self, namespaceURI, localName, doctype=None): def createDocument(self, namespaceURI, localName, doctype=None):
'''If specified must be a SOAP envelope, else may contruct an empty document. '''If specified must be a SOAP envelope, else may contruct an empty
document.
''' '''
prefix = self._soap_env_prefix prefix = self._soap_env_prefix


@@ -952,22 +971,27 @@ class ElementProxy(Base, MessageInterface):
self.node = self._dom.createDocument(None, None, None) self.node = self._dom.createDocument(None, None, None)
return return
else: else:
raise KeyError('only support creation of document in %s' % self.reserved_ns[prefix]) raise KeyError('only support creation of document in %s' %
self.reserved_ns[prefix])


document = self._dom.createDocument(nsuri=namespaceURI, qname=qualifiedName, doctype=doctype) document = self._dom.createDocument(nsuri=namespaceURI,
qname=qualifiedName,
doctype=doctype)
self.node = document.childNodes[0] self.node = document.childNodes[0]


#set up reserved namespace attributes #set up reserved namespace attributes
for prefix, nsuri in self.reserved_ns.items(): for prefix, nsuri in self.reserved_ns.items():
self._setAttributeNS(namespaceURI=self._xmlns_nsuri, self._setAttributeNS(namespaceURI=self._xmlns_nsuri,
qualifiedName='%s:%s' % (self._xmlns_prefix, prefix), qualifiedName='%s:%s' % (self._xmlns_prefix,
value=nsuri) prefix),
value=nsuri)


############################################# #############################################
#Methods for attributes #Methods for attributes
############################################# #############################################
def hasAttribute(self, namespaceURI, localName): def hasAttribute(self, namespaceURI, localName):
return self._dom.hasAttr(self._getNode(), name=localName, nsuri=namespaceURI) return self._dom.hasAttr(self._getNode(), name=localName,
nsuri=namespaceURI)


def setAttributeType(self, namespaceURI, localName): def setAttributeType(self, namespaceURI, localName):
'''set xsi:type '''set xsi:type
@@ -1074,7 +1098,8 @@ class ElementProxy(Base, MessageInterface):
if prefix: if prefix:
qualifiedName = '%s:%s' % (prefix, localName) qualifiedName = '%s:%s' % (prefix, localName)
node = self.createElementNS(namespaceURI, qualifiedName) node = self.createElementNS(namespaceURI, qualifiedName)
self._insertBefore(newChild=node._getNode(), refChild=refChild._getNode()) self._insertBefore(newChild=node._getNode(),
refChild=refChild._getNode())
return node return node


def getElement(self, namespaceURI, localName): def getElement(self, namespaceURI, localName):
@@ -1083,7 +1108,8 @@ class ElementProxy(Base, MessageInterface):
namespaceURI -- namespace of element namespaceURI -- namespace of element
localName -- local name of element localName -- local name of element
''' '''
node = self._dom.getElement(self.node, localName, namespaceURI, default=None) node = self._dom.getElement(self.node, localName, namespaceURI,
default=None)
if node: if node:
return ElementProxy(self.sw, node) return ElementProxy(self.sw, node)
return None return None
@@ -1137,6 +1163,7 @@ class ElementProxy(Base, MessageInterface):




class Collection(UserDict): class Collection(UserDict):

"""Helper class for maintaining ordered named collections.""" """Helper class for maintaining ordered named collections."""
default = lambda self, k: k.name default = lambda self, k: k.name


@@ -1147,7 +1174,8 @@ class Collection(UserDict):
self._func = key or self.default self._func = key or self.default


def __getitem__(self, key): def __getitem__(self, key):
NumberTypes = (types.IntType, types.LongType, types.FloatType, types.ComplexType) NumberTypes = (types.IntType, types.LongType, types.FloatType,
types.ComplexType)
if isinstance(key, NumberTypes): if isinstance(key, NumberTypes):
return self.list[key] return self.list[key]
return self.data[key] return self.data[key]
@@ -1168,7 +1196,9 @@ class Collection(UserDict):




class CollectionNS(UserDict): class CollectionNS(UserDict):

"""Helper class for maintaining ordered named collections.""" """Helper class for maintaining ordered named collections."""

default = lambda self, k: k.name default = lambda self, k: k.name


def __init__(self, parent, key=None): def __init__(self, parent, key=None):
@@ -1190,18 +1220,21 @@ class CollectionNS(UserDict):
def __setitem__(self, key, item): def __setitem__(self, key, item):
item.parent = weakref.ref(self) item.parent = weakref.ref(self)
self.list.append(item) self.list.append(item)
targetNamespace = getattr(item, 'targetNamespace', self.parent().targetNamespace) targetNamespace = getattr(item, 'targetNamespace',
self.parent().targetNamespace)
if not targetNamespace in self.data: if not targetNamespace in self.data:
self.data[targetNamespace] = {} self.data[targetNamespace] = {}
self.data[targetNamespace][key] = item self.data[targetNamespace][key] = item


def __isSequence(self, key): def __isSequence(self, key):
return (type(key) in (types.TupleType, types.ListType) and len(key) == 2) return (type(key) in (types.TupleType, types.ListType)
and len(key) == 2)


def keys(self): def keys(self):
keys = [] keys = []
for tns in self.data.keys(): for tns in self.data.keys():
keys.append(map(lambda i: (tns, self._func(i)), self.data[tns].values())) keys.append(map(lambda i: (tns, self._func(i)),
self.data[tns].values()))
return keys return keys


def items(self): def items(self):
@@ -1294,8 +1327,10 @@ if 1:
# prefixed attribute names during cloning. # prefixed attribute names during cloning.
# #
# key (attr.namespaceURI, tag) # key (attr.namespaceURI, tag)
# ('http://www.w3.org/2000/xmlns/', u'xsd') <xml.dom.minidom.Attr instance at 0x82227c4> # ('http://www.w3.org/2000/xmlns/', u'xsd')
# ('http://www.w3.org/2000/xmlns/', 'xmlns') <xml.dom.minidom.Attr instance at 0x8414b3c> # <xml.dom.minidom.Attr instance at 0x82227c4>
# ('http://www.w3.org/2000/xmlns/', 'xmlns')
# <xml.dom.minidom.Attr instance at 0x8414b3c>
# #
# xml.dom.minidom.Attr.nodeName = xmlns:xsd # xml.dom.minidom.Attr.nodeName = xmlns:xsd
# xml.dom.minidom.Attr.value = = http://www.w3.org/2001/XMLSchema # xml.dom.minidom.Attr.value = = http://www.w3.org/2001/XMLSchema
@@ -1314,7 +1349,8 @@ if 1:
clone = newOwnerDocument.createElementNS(node.namespaceURI, clone = newOwnerDocument.createElementNS(node.namespaceURI,
node.nodeName) node.nodeName)
for attr in node.attributes.values(): for attr in node.attributes.values():
clone.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value) clone.setAttributeNS(attr.namespaceURI, attr.nodeName,
attr.value)


prefix, tag = xml.dom.minidom._nssplit(attr.nodeName) prefix, tag = xml.dom.minidom._nssplit(attr.nodeName)
if prefix == 'xmlns': if prefix == 'xmlns':
@@ -1322,18 +1358,21 @@ if 1:
elif prefix: elif prefix:
a = clone.getAttributeNodeNS(attr.namespaceURI, tag) a = clone.getAttributeNodeNS(attr.namespaceURI, tag)
else: else:
a = clone.getAttributeNodeNS(attr.namespaceURI, attr.nodeName) a = clone.getAttributeNodeNS(attr.namespaceURI,
attr.nodeName)
a.specified = attr.specified a.specified = attr.specified


if deep: if deep:
for child in node.childNodes: for child in node.childNodes:
c = xml.dom.minidom._clone_node(child, deep, newOwnerDocument) c = xml.dom.minidom._clone_node(child, deep,
newOwnerDocument)
clone.appendChild(c) clone.appendChild(c)
elif node.nodeType == xml.dom.minidom.Node.DOCUMENT_FRAGMENT_NODE: elif node.nodeType == xml.dom.minidom.Node.DOCUMENT_FRAGMENT_NODE:
clone = newOwnerDocument.createDocumentFragment() clone = newOwnerDocument.createDocumentFragment()
if deep: if deep:
for child in node.childNodes: for child in node.childNodes:
c = xml.dom.minidom._clone_node(child, deep, newOwnerDocument) c = xml.dom.minidom._clone_node(child, deep,
newOwnerDocument)
clone.appendChild(c) clone.appendChild(c)


elif node.nodeType == xml.dom.minidom.Node.TEXT_NODE: elif node.nodeType == xml.dom.minidom.Node.TEXT_NODE:
@@ -1360,14 +1399,16 @@ if 1:
clone.entities._seq = [] clone.entities._seq = []
clone.notations._seq = [] clone.notations._seq = []
for n in node.notations._seq: for n in node.notations._seq:
notation = xml.dom.minidom.Notation(n.nodeName, n.publicId, n.systemId) notation = xml.dom.minidom.Notation(n.nodeName, n.publicId,
n.systemId)
notation.ownerDocument = newOwnerDocument notation.ownerDocument = newOwnerDocument
clone.notations._seq.append(notation) clone.notations._seq.append(notation)
if hasattr(n, '_call_user_data_handler'): if hasattr(n, '_call_user_data_handler'):
n._call_user_data_handler(operation, n, notation) n._call_user_data_handler(operation, n, notation)
for e in node.entities._seq: for e in node.entities._seq:
entity = xml.dom.minidom.Entity(e.nodeName, e.publicId, e.systemId, entity = xml.dom.minidom.Entity(e.nodeName, e.publicId,
e.notationName) e.systemId,
e.notationName)
entity.actualEncoding = e.actualEncoding entity.actualEncoding = e.actualEncoding
entity.encoding = e.encoding entity.encoding = e.encoding
entity.version = e.version entity.version = e.version


+ 4
- 4
wstools/WSDLTools.py View File

@@ -1567,6 +1567,7 @@ class HeaderInfo(ParameterInfo):




def callInfoFromWSDL(port, name): def callInfoFromWSDL(port, name):
logger = logging.getLogger(__name__)
"""Return a SOAPCallInfo given a WSDL port and operation name.""" """Return a SOAPCallInfo given a WSDL port and operation name."""
wsdl = port.getService().getWSDL() wsdl = port.getService().getWSDL()
binding = port.getBinding() binding = port.getBinding()
@@ -1643,10 +1644,9 @@ def callInfoFromWSDL(port, name):
operation.output.message) operation.output.message)
else: else:
message = wsdl.addMessage(operation.output.message) message = wsdl.addMessage(operation.output.message)
print "Warning:", \ logger.warning("Warning: Received message not defined in the "
"Recieved message not defined in the WSDL schema.", \ "WSDL schema. Adding it.")
"Adding it." logger.warning("Message:", operation.output.message)
print "Message:", operation.output.message


msgrole = opbinding.output msgrole = opbinding.output




||||||
x
 
000:0
Loading…
Cancel
Save