Web Services for Python

Brian Lloyd

Brian Lloyd, http://www.zope.com
E-mail:

Release 1.0
Oct 29, 2001

COPYRIGHT
This software is Copyright © Zope Corporation (tm) and Contributors. All rights reserved. This license has been certified as open source. It has also been designated as GPL compatible by the Free Software Foundation (FSF). Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
  1. Redistributions in source code must retain the above copyright notice, this list of conditions, and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions, and the following disclaimer in the documentation and/or other materials provided with the distribution.
  3. The name Zope Corporation (tm) must not be used to endorse or promote products derived from this software without prior written permission from Zope Corporation.
  4. The right to distribute this software or to use it for any purpose does not give you the right to use Servicemarks (sm) or Trademarks (tm) of Zope Corporation. Use of them is covered in a separate agreement (see http://www.zope.com/Marks).
  5. If any files are modified, you must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
THIS SOFTWARE IS PROVIDED BY ZOPE CORPORATION ``AS IS''AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ZOPE CORPORATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

1. Web Services for Python

1.1 Introduction

Web services are packages of functionality that are published to the network using Internet standards such as XML and HTTP. These services can be used as building blocks for other software. They can be thought of in some ways like a network-wide, cross platform system of reusable components. The IBM developerWorks Web Services site is a good starting point for learning more about web services. It contains some good beginner material as well as a number of articles on the benefits (and challenges) of the web services model. The documentation for this package assumes that you are familiar with the general web services landscape and the underlying technologies (SOAP, WSDL, XML Schema, etc.), though you do not need to be an expert in the details of these to use the package. The WebService package is a toolkit for building and using web services in Python. It supports the SOAP 1.1 specification, SOAP messages with attachments and WSDL 1.1. Future enhancements will probably include some form of UDDI support. The WebService package requires Python 2.0 or later. To support secure HTTP connections, you will need to have compiled your Python with SSL support.

See Also:

The SOAP 1.1 specification
The SOAP specification defines the protocol that web services use to communicate.
WSDL 1.1: Web Services Description Language
The WSDL specification defines the WSDL object model in detail and may be helpful in better understanding the element-level classes in the WSDLTools module and how they should be used.
XML Schema Part 0: Primer
The XML Schema primer is an introduction to XML Schema, a facility for describing content structures used for data serialization and interface discovery in web services.
UDDI: Universal Discovery, Description and Integration
UDDI is an initiative to enable businesses to quickly, easily and dynamically transact business with one another using (among other things) web services.

1.2 Getting Started

The WebService package provides some high-level tools that make it easy to get started using and implementing web services. Perhaps more importantly, the package provides a number of lower-level tools for dealing with the various technologies involved with web services. This toolkit approach makes it possible to implement alternate high-level tools without having to ``start from scratch''. The package tries hard to provide clear interfaces that make it relatively easy to adapt to different client and server environments . This section focuses on getting started using the high-level tools in the package. For more information on using the lower level objects, see the examples in the package documentation (or look at the implementation for the high-level tools, which are themselves built using the low level tools).

1.2.1 Using Web Services

The WebService package provides two high-level client-side tools for working with remote web services. The ServiceProxy class acts as a proxy for a service that has a WSDL description, and exposes methods that reflect the methods of the remote service. ServiceProxy objects are very straightforward - you initialize a proxy from a WSDL URL, then call methods on the proxy corresponding to the methods of the remote service.
from WebService.ServiceProxy import ServiceProxy

service = ServiceProxy('http://www.xmethods.net/sd/BabelFishService.wsdl')
value = service.BabelFish('en_de', 'This is a test!')
The methods of ServiceProxy instances can be called with positional arguments (where the argument positions match the message descriptions in the associated WSDL) or keyword arguments (where the arguments match the message descriptions by name). Arguments to ServiceProxy methods must be compatible with the types required by the WSDL description. The return value from a proxy method depends on the SOAP signature. If the remote service returns a single value, that value will be returned. If the remote service returns multiple ``out'' parameters, the return value of the proxy method will be a dictionary containing the out parameters indexed by name. Not all web services have WSDL descriptions - which is where the second high-level tool comes in. The SOAPMethod class can be used to make SOAP calls to services that do not have WSDL descriptions. To use a SOAPMethod, you initialize it with information about the SOAP call such as the method name, endpoint URL, SOAPAction, etc., then call it.
from WebService.ServiceProxy import SOAPMethod

method = SOAPMethod('EchoString',
                    url='http://www.example.com/EchoService',
                    namespace='urn:EchoService',
                    soapAction=''urn:EchoService#EchoString'
                    )

result = method(data='Echo this string!')
Note that SOAPMethod objects take a ``do what I mean'' approach to calling remote service methods. If no type information is provided, argument serialization is done using defaults based on the Python types of the arguments. TODO: finish this section.

1.2.2 Implementing Web Services

Show some examples of web service implementations in common server environments. TODO: finish this section.

1.3 WebService.ServiceProxy

The ServiceProxy module provides a convenient way to call remote web services that are described with WSDL. Service proxies expose methods that reflect the methods of the remote web service.
class ServiceProxy(wsdl,[, service[, port]])
The ServiceProxy class provides a high-level Pythonic way to call remote web services. A WSDL description must be available for the remote service. The wsdl argument may be either the URL of the service description or an existing WSDL instance. The optional service and port name the service and port within the WSDL description that should be used. If not specified, the first defined service and port will be used.

1.3.1 ServiceProxy Objects

A ServiceProxy instance, once instantiated, exposes callable methods that reflect the methods of the remote web service it represents. These methods may be called like normal methods, using *either* positional or keyword arguments (but not both). When a method of a ServiceProxy is called with positional arguments, the arguments are mapped to the SOAP request based on the parameter order defined in the WSDL description. If keyword arguments are passed, the arguments will be mapped based on their names.

1.3.2 ServiceProxy Example

This example demonstrates instantiating a ServiceProxy object from a WSDL description to call a remote web service method.
from WebService.ServiceProxy import ServiceProxy

service = ServiceProxy('http://www.xmethods.net/sd/BabelFishService.wsdl')
value = service.BabelFish('en_de', 'This is a test!')

1.4 WebService.SOAPMessage

The SOAPMessage module provides a high-level interface for working with SOAP messages. The SOAPMessage model provides a layer of abstraction that simplifies client and server applications by taking care of most of the details of SOAP message serialization. At the same time, SOAPMessage objects still providing a good deal of control and convenient ways to customize message processing.
class SOAPMessage([, message_body])
The SOAPMessage class represents a single SOAP message. It can be used by both clients and servers, both to build new request or response messages or to interpret a recieved message. The message may be instantiated with a message_body in order to deserialize and work with a recieved message (such as a request recieved from a client or a response recieved from a server). The message_body should be a string containing the body of the message. The message body may be XML text or the body of a MIME multipart message. If the message_body is not specified, then the message object is used to build and serialize a new SOAP message (such as a request to a server or a response to a client). In this case, you will use the APIs of the SOAPMessage to populate and serialize the new message.
exception InvalidMessage
This exception is raised when errors occur in the parsing or building of SOAP messages, usually indicating invalid usage or message input.

1.4.1 SOAPMessage Objects

serializer
The Serializer instance that will be used to perform data serialization and deserialization for this message. The default serializer for SOAPMessage objects supports the standard SOAP and XML Schema simple types. You should not load schema into the default serializer. To support custom types, set this attribute to a different Serializer instance loaded with the appropriate schema.
soapAction
The SOAP action associated with the message, or None if undefined.
methodName
The method name that will be used in the SOAP RPC struct for RPC-style messages. This value must be set before an RPC-style message can be serialized. This attribute is not used for document-style messages.
namespace
The namespace URI value to use for the SOAP RPC struct for RPC-style messages. A namespace value must be set before an RPC-style message can be serialized. This attribute is not used for document-style messages.
version
The SOAP protocol version to use for this message (the default is 1.1. For new messages, this should be set before the serialize() method is called to have an effect. If the message is loaded from an existing message body, this attribute will reflect the protocol version of the message after the deserialize() method is called.
style
A string value indicating the SOAP message style. Valid values are 'document' and 'rpc'. The default is 'rpc'.
getContentType()
Return the content type of the serialized message body. For SOAPMessage instances that are not initialized with a message body, the content type is not available until after the serialize() method is called. The value returned is suitable for sending as the Content-Type header value when sending the message over transports that support MIME headers.
getMessageBody()
Return the serialized XML or MIME body of the message, or None if the message body is not yet available. Note that for SOAPMessage instances that are not initialized with a message body, the message body is not available until after the serialize() method is called.
getMimeParts()
Return a sequence containing MIMEPart instances representing any MIME parts associated with the message. Note that the MIME parts of a message are not available until the message has been deserialized.
getMimePart(name)
Return the named MIME part associated with the message, or None if the named part is not found.
getSOAPHeaders()
Return a sequence containing SOAPHeader instances representing the SOAP headers that appear in the message. The SOAP headers are not available until the message has been deserialized.
getSOAPHeader(name)
Return the named SOAP header associated with the message, or None if the named header is not found.
addSOAPHeader(name, namespace, value, type [, actor[, mustUnderstand]])
Add a SOAP header with the given name, namespace, value and type to the message. The type should be a QName tuple of the form (namespaceURI, typeName). If the actor or mustUnderstand attributes are specified, the corresponding header attributes will appear in the SOAP message.
getMustUnderstandHeaders()
Return a sequence of those headers in the SOAP message with true values for their SOAP 'mustUnderstand' attributes.
getHeadersForActor(actorURI)
Return a sequence of those headers in the SOAP message whose actor attributes match the given actorURI.
getParameters()
Return a sequence of the parameters in the SOAP message. The members of the sequence will be either Parameter or MIMEPart objects. For RPC-style SOAP messages, the parameters represent the elements of the RPC struct of the message. For document-style messages, they represent the immediate child elements found in the SOAP body. Note that the parameters are not available until the message has been deserialized.
getParameter(name)
Return the named parameter of the message, or None if the named parameter is not found. The return value will be either a Parameter or MIMEPart object.
getReturnValue()
Return the *value* of the first parameter that appears in the message (which represents the 'return' value in a reply from a service). This method will return codeNone if the message contains no parameters.
addParameter( name, value, type[, namespace])
Add a parameter with the given values to the message. The type should be a QName tuple of the form (namespaceURI, typeName). The namespace should only be passed when adding parameters to a SOAP document-style message. Note that parameters are serialized in the order that they are added to the message.
addMimeParam( name, content_type, data )
Add a MIMEPart parameter to the message with the given name, content_type and data. The data may be either a string or a file-like object containing the MIME data. Note that adding a MIME parameter to a message will cause it to be serialized as a MIME multipart/related message.
getFault()
Return the fault associated with the SOAP message as a SOAPFault instance, or None if no fault is present in the message. Note that fault information is not available until the message has been deserialized.
isFault()
Return a true value if the SOAP message contains a fault.
serialize()
Serialize the message data into a valid XML or MIME string. After the serialize() method has been called, the serialized message is available as the XXX attribute of the SOAPMessage. This method will call the beforeSerialize() before beginning serialization and afterSerialize() afterward, making it easy for subclasses to provide custom message processing.
deserialize()
Deserialize the message, making parameter and other data available. This should only be called on instances initialized from existing SOAP message data. This method will call the beforeDeserialize() before beginning deserialization and afterDeserialize() afterward, making it easy for subclasses to provide custom message processing.
beforeSerialize()
This method is called before serialization starts. Derived classes can implement this method to customize message processing.
afterSerialize()
This method is called after serialization is complete. Derived classes can implement this method to customize message processing.
beforeDeserialize()
This method is called before deserialization starts. Derived classes can implement this method to customize message processing.
afterDeserialize()
This method is called after deserialization is complete. Derived classes can implement this method to customize message processing.

1.4.2 SOAPMessage Examples

This example uses a SOAPMessage object to build a SOAP request, sends it to the remote service using an HTTPTransport and uses another SOAPMessage instance to interpret the response.
from WebService.SOAPMessage import SOAPMessage
from WebService.Transports import HTTPTransport

# Build the outgoing SOAP request message.
message = SOAPMessage()
message.soapAction = 'urn:xmethodsBabelFish#BabelFish'
message.methodName = 'BabelFish'
message.namespace = 'urn:xmethodsBabelFish'
message.addParameter('translationmode', 'en_de', (DOM.NS_XSD, 'string'))
message.addParameter('sourcedata', 'This is a test!', (DOM.NS_XSD, 'string'))
message.serialize()

# Send the message to the remote web service.
transport = HTTPTransport()
response = transport.send(
    'http://services.xmethods.net:80/perl/soaplite.cgi',
    'urn:xmethodsBabelFish#BabelFish',
    message.getMessageBody(),
    message.getContentType()
    )

# Create a new SOAPMessage for the response.
reply_msg = SOAPMessage(response.body)
reply_msg.deserialize()

result = reply_msg.getReturnValue()

1.5 WebService.WSDLTools

The WSDLTools module provides classes for reading and building WSDL service descriptions. The WSDLTools module supports the WSDL 1.1 specification, including document import and support for the binding types defined in the spec. The most important classes and exceptions provided by this module are:
class WSDLReader()
The WSDLReader class provides methods for loading WSDL service descriptions from URLs or XML data. It also provides a basic mechanism that developers can use to ensure that a service description matches the one that was coded against.
class WSDLWriter([targetNamespace])
The WSDLWriter class provides a simplified high-level interface for producing WSDL service descriptions. It allows you to avoid most of details involved in using the low-level object model to produce WSDL descriptions for common cases. The optional targetNamespace allows you to specify the target namespace URI of the service description document. If this is not specified, a target namespace URI will be generated.
class WSDL([targetNamespace])
WSDL instances represent WSDL service descriptions and provide an object model for building and working with those descriptions. A targetNamespace may be specified for the service description. If no targetNamspace is specified, one will be generated.
exception WSDLError
This exception is raised when errors occur in the parsing or building of WSDL objects, usually indicating invalid structure or usage.
Note that there are quite a few other classes defined in this module that implement the WSDL object model. Instances of those classes are generally accessed and created through container objects rather than instantiated directly. Most of them simply implement a straightforward representation of the WSDL elements they represent. The interfaces of these objects are described in the following sections.

1.5.1 WSDLReader Objects

WSDLReader instances are used to load WSDL service descriptions from URLs, XML files or XML string data. The reader is implemented as a separate class to make it easy to create custom readers that implement caching policies or other optimizations.
loadFromStream(file[, checksum])
Return a WSDL instance representing the service description contained in file. The file argument must be a file-like object. If specified, the optional checksum argument will be compared with the md5 checksum of the loaded service description. If the checksum does not match the given value, an WSDLError will be raised. Note that the checksum is based on the entire content of a service description, including imported content.
loadFromString(data[, checksum])
Returns a WSDL instance loaded from the XML string data.
loadFromFile(filename[, checksum])
Returns a WSDL instance loaded from the file named by filename.
loadFromURL(url[, checksum])
Returns a WSDL instance loaded from the given url.

1.5.2 WSDLReader Example

This example uses a WSDLReader to load a WSDL service description from a URL and print the names of the services it defines.
from WebService.WSDLTools import WSDLReader

reader = WSDLReader()
wsdl = reader.loadFromURL('http://www.xmethods.net/sd/BabelFishService.wsdl')
for service in wsdl.services.values():
    print service.name

1.5.3 WSDLWriter Objects

The WSDLWriter class provides a simplified interface for building WSDL descriptions dynamically. You can often use a WSDLWriter to produce SOAP service descriptions without worrying about most of the details of the WSDL object model. This simplified interface will produce a WSDL description for a one or more services, using standard SOAP bindings. It is possible to write descriptions for both RPC and document style services. In addition to generating basic SOAP service descriptions, this class is useful as an example of how to implement higher-level interfaces over the WSDL object model. The same approach could be used to implement a tool that supports other bindings (such as the WSDL-defined HTTP GET/POST binding).
startService(name, address [, documentation[, style]])
Start a service description in the WSDL document. The name is the name of the service. The address is the URL of the actual service implementation. If the optional documentation is specified it will be included in the service description. The optional style argument indicates the messaging style for the service. This should be a string with a value of either 'document' or 'rpc'. The default is 'rpc' if a style is not specified.
endService()
End the current service description in the WSDL document.
writeMethod(callinfo[, documentation])
Add a method definition to the service description. The startService() method must have been called prior to calling writeMethod(). The callinfo argument should be a SOAPCallInfo instance that provides the SOAP binding and parameter information for the service method. The SOAPCallInfo instance must at least define the parameters of the operation - reasonable defaults for other binding information will be generated if it is not specified in the call info.
toXML()
Return the completed WSDL XML document as a string.

1.5.4 WSDLWriter Example

The following is a simple example of generating a WSDL description document using WSDLWriter. It generates a WSDL document describing a service named 'EchoService' with three methods to echo values of various types.
from WebService.SOAPCallInfo import SOAPCallInfo
from WebService.WSDLTools import WSDLWriter
from WebService.Utility import DOM

writer = WSDLWriter('http://www.example.com/services/EchoService.wsdl')

writer.startService('EchoService',
                    'http://www.example.com/services/EchoService.cgi',
                    'A simple echoing service.',
                    )

callinfo = SOAPCallInfo('echoString')
callinfo.documentation = 'Echo a string argument.'
callinfo.addInParameter('data', (DOM.NS_XSD_01, 'string'))
callinfo.setReturnParameter('return', (DOM.NS_XSD_01, 'string'))
writer.writeMethod(callinfo)

callinfo = SOAPCallInfo('echoInteger')
callinfo.documentation = 'Echo an integer argument.'
callinfo.addInParameter('data', (DOM.NS_XSD_01, 'int'))
callinfo.setReturnParameter('return', (DOM.NS_XSD_01, 'int'))
writer.writeMethod(callinfo)

callinfo = SOAPCallInfo('echoFloat')
callinfo.documentation = 'Echo a float argument.'
callinfo.addInParameter('data', (DOM.NS_XSD_01, 'float'))
callinfo.setReturnParameter('return', (DOM.NS_XSD_01, 'float'))
writer.writeMethod(callinfo)

writer.endService()

wsdl =  writer.toXML()

1.5.5 WSDL Objects

WSDL instances implement the WSDL object model. They are most often created by loading an XML source into a WSDLReader. You can also create a WSDL instance and use the object model to build a service description dynamically (though it will often be easier to use a WSDLWriter or some other higher-level tool). A WSDL object provides access to all of the structures that make up a web service description. The various ``collections'' in the WSDL object model (services, bindings, portTypes, etc.) are implemented as Collection objects that behave like ordered mappings.
name
The name of the service description (associated with the definitions element), or None if not specified.
targetNamespace
The target namespace associated with the service description, or None if not specified.
documentation
The documentation associated with the definitions element of the service description, or the empty string if not specified.
location
The URL from which the service description was loaded, or None if the description was not loaded from a URL.
services
A collection that contains Service objects that represent the services that appear in the service description. The items of this collection may be indexed by name or ordinal.
messages
A collection that contains Message objects that represent the messages that appear in the service description. The items of this collection may be indexed by name or ordinal.
portTypes
A collection that contains PortType objects that represent the portTypes that appear in the service description. The items of this collection may be indexed by name or ordinal.
bindings
A collection that contains Binding objects that represent the bindings that appear in the service description. The items of this collection may be indexed by name or ordinal.
imports
A collection that contains ImportElement objects that represent the import elements that appear in the service description. The items of this collection may be indexed by ordinal or the target namespace URI of the import element.
types
A Types instance that contains XMLSchema objects that represent the schemas defined or imported by the WSDL description. The Types object may be indexed by ordinal or by targetNamespace to lookup schema objects.
extensions
A sequence of objects that represent WSDL extension elements. These objects may be instances of classes that represent WSDL-defined extensions (SoapBinding, SoapBodyBinding, etc.), or DOM Element objects for unknown extensions.
getMd5Hash()
Return an md5 hash based on the content of the service description. This hash may be passed as the checksum argument to a WSDLReader. Note that the hash returned is based on the entirety of the logical WSDL description, including any imported elements of the description.
addService(name[, documentation])
Add a new Service to the services collection, with the given name and documentation. Returns the Service that was added.
addMessage(name[, documentation])
Add a new Message to the messages collection, with the given name and documentation. Returns the Message that was added.
addPortType(name[, documentation])
Add a new PortType to the portTypes collection, with the given name and documentation. Returns the PortType that was added.
addBinding(name, type[, documentation])
Add a new Binding to the bindings collection, with the given name and documentation. The type should be the name of the PortType associated with the binding. Returns the Binding that was added.
addImport(namespace, location)
Add a new ImportElement to the imports collection, with the given namespace and location attributes. Returns the ImportElement that was added.
toXML()
Return an XML string representation of the service description. Note that for WSDL instances loaded from existing XML data, this method returns an XML representation of the entire logical WSDL document, including any imported information.

1.5.6 Service Objects

A Service object represents a WSDL <service> element.
name
The name of the service.
documentation
The documentation associated with the element, or an empty string.
ports
A collection that contains Port objects that represent the ports defined by the service. The items of this collection may be indexed by name or ordinal.
extensions
A sequence of any contained WSDL extensions.
getWSDL()
Return the parent WSDL instance of the object.
addPort(name, binding[, documentation])
Add a new Port to the ports collection, with the given name, binding and documentation. Returns the Port that was added.

1.5.7 Port Objects

A Port object represents a WSDL <port> element.
name
The name of the port.
documentation
The documentation associated with the element, or an empty string.
binding
The name of the binding associated with the port.
extensions
A sequence of any contained WSDL extensions.
getAddressBinding()
A convenience method that returns the address binding extension for the port, either a SoapAddressBinding or HttpAddressBinding. Raises WSDLError if no address binding is found.
getService()
Return the parent Service instance of the object.
getBinding()
Return the Binding instance associated with the port.
getPortType()
Return the PortType instance associated with the port.

1.5.8 PortType Objects

A PortType object represents a WSDL <portType> element.
name
The name of the portType.
documentation
The documentation associated with the element, or an empty string.
operations
A collection that contains Operation objects that represent the operations in the portType. The items of this collection may be indexed by name or ordinal.
getWSDL()
Return the parent WSDL instance of the object.
addOperation( name[, documentation[, parameterOrder]])
Add a new Operation to the operations collection, with the given name, documentation and optional parameterOrder. Returns the Operation that was added.

1.5.9 Operation Objects

A Operation object represents a WSDL <operation> element within a portType.
name
The name of the operation.
documentation
The documentation associated with the element, or an empty string.
parameterOrder
A string representing the parameterOrder attribute of the operation, or None if the attribute is not defined.
input
A MessageRole instance representing the <input> element of the operation binding, or None if no input element is present.
output
A MessageRole instance representing the <output> element of the operation, or None if no output element is present.
faults
A collection of MessageRole instances representing the <fault> elements of the operation.
getPortType()
Return the parent PortType instance of the object.
getInputMessage()
Return Message object associated with the input to the operation.
getOutputMessage()
Return Message object associated with the output of the operation.
getFaultMessage(name)
Return Message object associated with the named fault.
setInput( message[, name[, documentation]])
Associate the named message with the operation input.
setOutput( message[, name[, documentation]])
Associate the named message with the operation output.
addFault( name, message[, documentation])
Add a new fault with the given name, linked to the named message.

1.5.10 MessageRole Objects

MessageRole objects represent WSDL <input>, <output> and <fault> elements within an operation.
name
The name attribute of the element.
type
The type of the element, one of 'input', 'output' or 'fault'.
message
The name of the message associated with the object.
documentation
The documentation associated with the element, or an empty string.

1.5.11 Binding Objects

A Binding object represents a WSDL <binding> element.
name
The name of the binding.
documentation
The documentation associated with the element, or an empty string.
type
The name of the portType the binding is associated with.
operations
A collection that contains OperationBinding objects that represent the contained operation bindings.
extensions
A sequence of any contained WSDL extensions.
getWSDL()
Return the parent WSDL instance of the object.
getPortType()
Return the PortType object associated with the binding.
addOperationBinding( name[, documentation])
Add a new OperationBinding to the binding, with the given name and documentation. Returns the OperationBinding that was added.
findBinding(kind)
Find a binding extension in the binding. The kind can be a class object if the wanted extension is one of the WSDL-defined types (such as SoapBinding or HttpBinding). If the extension not one of the supported types, kind can be a QName tuple of the form (namespaceURI, typeName), which will be used to try to find a matching DOM Element.
findBindings(kind)
The same as findBinding(), but will return multiple values of the given kind.

1.5.12 OperationBinding Objects

A OperationBinding object represents a WSDL <operation> element within a binding element.
name
The name of the operation binding.
documentation
The documentation associated with the element, or an empty string.
input
A MessageRoleBinding instance representing the <input> element of the operation binding, or None if no input element is present.
output
A MessageRoleBinding instance representing the <output> element of the operation binding, or None if no output element is present.
faults
A collection of MessageRoleBinding instances representing the <fault> elements of the operation binding.
extensions
A sequence of any contained WSDL extensions.
getBinding()
Return the parent Binding instance of the operation binding.
getOperation()
Return the abstract Operation associated with the operation binding.
findBinding(kind)
Find a binding extension in the operation binding. The kind can be a class object if the wanted extension is one of the WSDL-defined types (such as SoapOperationsBinding or HttpOperationBinding). If the extension not one of the supported types, kind can be a QName tuple of the form (namespaceURI, typeName), which will be used to try to find a matching DOM Element.
findBindings(kind)
The same as findBinding(), but will return multiple values of the given kind.
addInputBinding(binding)
Add the given binding to the <input> of the operation binding. The binding may be an instance of a supported binding class or a DOM Element.
addOutputBinding(binding)
Add the given binding to the <output> of the operation binding. The binding may be an instance of a supported binding class or a DOM Element.
addFaultBinding(name, binding)
Add the given binding to the <fault> of the operation binding named by name. The binding may be an instance of a supported binding class or a DOM Element.

1.5.13 MessageRoleBinding Objects

MessageRoleBinding objects represent WSDL <input>, <output> and <fault> elements within an operation binding.
name
The name attribute of the element, for fault elements. This is always None for input and output elements.
type
The type of the element, one of 'input', 'output' or 'fault'.
documentation
The documentation associated with the element, or an empty string.
extensions
A sequence of any contained WSDL extensions.
findBinding(kind)
Find a binding extension in the message role binding. The kind can be a class object if the wanted extension is one of the WSDL-defined types. If the extension not one of the supported types, kind can be a QName tuple of the form (namespaceURI, typeName), which will be used to try to find a matching DOM Element.
findBindings(kind)
The same as findBinding(), but will return multiple values of the given kind.

1.5.14 Message Objects

A Message object represents a WSDL <message> element.
name
The name of the message.
documentation
The documentation associated with the element, or an empty string.
parts
A collection that contains MessagePart objects that represent the parts of the message. The items of this collection may be indexed by name or ordinal.
addPart(name[, type[, element]])
Add a MessagePart with the given name and type or element to the message. The type or element should be a QName tuple of the form (namespaceURI, typeName).

1.5.15 MessagePart Objects

A MessagePart object represents a WSDL <part> element.
name
The name of the message part.
documentation
The documentation associated with the element, or an empty string.
type
A QName tuple of the form (namespaceURI, typeName), or None if the type attribute is not defined.
element
A QName tuple of the form (namespaceURI, typeName), or None if the element attribute is not defined.

1.5.16 Types Objects

A Types object represents a WSDL <types> element. It acts as an ordered collection containing XMLSchema instances associated with the service description (either directly defined in a <types> element, or included via import). The Types object can be indexed by ordinal or by the targetNamespace of the contained schemas.
documentation
The documentation associated with the element, or an empty string.
extensions
A sequence of any contained WSDL extensions.
getWSDL()
Return the parent WSDL instance of the object.
addSchema(schema)
Add the given XMLSchema instance to the Types collection.

1.5.17 ImportElement Objects

A ImportElement object represents a WSDL <import> element.
namespace
The namespace attribute of the import element.
location
The location attribute of the import element.

1.5.18 Binding Classes

The WSDLTools module contains a number of classes that represent the binding extensions defined in the WSDL specification. These classes are straightforward, reflecting the attributes of the corresponding XML elements, so they are not documented exhaustively here.
class SoapBinding(transport[, style])
Represents a <soap:binding> element.
class SoapAddressBinding(location)
Represents a <soap:address> element.
class SoapOperationBinding([soapAction[, style]])
Represents a <soap:operation> element.
class SoapBodyBinding( use[, namespace[, encodingStyle[, parts]]])
Represents a <soap:body> element.
class SoapFaultBinding( message, part, use[, namespace[, encodingStyle]])
Represents a <soap:fault> element.
class SoapHeaderBinding( message, part, use[, namespace[, encodingStyle]])
Represents a <soap:header> element.
class SoapHeaderFaultBinding( message, part, use[, namespace[, encodingStyle]])
Represents a <soap:headerfault> element.
class HttpBinding(verb)
Represents a <http:binding> element.
class HttpAddressBinding(location)
Represents a <http:address> element.
class HttpOperationBinding(location)
Represents a <http:operation> element.
class HttpUrlReplacementBinding()
Represents a <http:urlReplacement> element.
class HttpUrlEncodedBinding()
Represents a <http:urlEncoded> element.
class MimeMultipartRelatedBinding()
Represents a <mime:multipartRelated> element.
class MimePartBinding()
Represents a <mime:part> element.
class MimeContentBinding([part[, type]])
Represents a <mime:content> element.
class MimeXmlBinding([part])
Represents a <mime:mimeXml> element.

1.6 WebService.SOAPCallInfo

The SOAPCallInfo module provides tools for describing and inspecting the binding and parameter information needed to invoke operations on SOAP web services. WSDL provides a flexible and extensible way of describing a SOAP method invokation in great detail. As a result, the WSDL object model is fairly complex and it can be quite cumbersome to use that object model directly to find all of the information you need to know in order to call a SOAP service. The SOAPCallInfo class defined in this module provides a more compact representation of call metadata that is often easier to work with than raw WSDL structures. SOAPCallInfo instances can be created from WSDL information, or can built dynamically (for example, to use as input to a WSDLWriter).
callInfoFromWSDL(port, name)
Return a new SOAPCallInfo instance intitialized from WSDL data. The port should be a Port instance from a WSDL object, and name should be the name of the operation within that port.
class SOAPCallInfo(methodName)
A SOAPCallInfo instance represents the important metadata related to a SOAP operation invokation, such as the name of the operation, address, parameters, types and other binding information. The methodName argument indicates the name of the SOAP operation.

1.6.1 SOAPCallInfo Objects

SOAPCallInfo objects support attributes and methods to represent and manipulate the various metadata associated with a SOAP operation invokation. Note that unless otherwise specified, the various public attributes of SOAPCallInfo instances have a default value of None. For SOAPCallInfo objects loaded from WSDL, a value of None indicates that the WSDL did not define a value for the attribute.
documentation
A string containing documentation for the web service operation. This defaults to an empty string.
encodingStyle
A string indicating the URIs of one or more encoding styles to be used when calling the operation. The URIs are separated by single spaces if more than one encoding is applicable. The default value for this attribute is the standard SOAP 1.1 encoding URI.
soapAction
The SOAP action associated with the operation, usually sent to remote service implementations as a MIME header value.
location
The address of the service implementation. This is the target URL for requests to the web service operation.
methodName
The name of the operation, used as the element name of the RPC struct in RPC-style SOAP messages.
namespace
The namespace of the operation, used as the namespace URI of the RPC struct in RPC-style SOAP messages.
transport
A namespace URI indicating the transport to be used to communicate with the operation. This value should be one of the URIs defined by the WSDL specification for this purpose.
style
The SOAP message style to be used when calling the operation. Valid values for this attribute are 'document' and 'rpc'. The default value for this attribute is 'rpc'.
use
This attribute indicates encoding usage for calling the operation. Valid values for this attribute are 'literal' and 'encoded', per the WSDL specification. The default value for this attribute is 'encoded'.
addInParameter(name, type, [, namespace[, element_type]])
Add an input parameter description to the call info object. The name indicates the name of the parameter. The type should be a QName tuple of the form (namespaceURI, typeName) that indicates an XSD simpleType, complexType or element associated with the parameter. The optional namespace, if specified, indicates a namespace URI to be used for element serialization. A true value may be passed for the optional element_type to indicate that type is a reference to an XSD element rather than a simpleType or complexType.
addOutParameter(name, type, [, namespace[, element_type]])
Add an output parameter description to the call info object. Arguments and usage is the same as for addInParameter().
setReturnParameter(name, type, [, namespace[, element_type]])
Set the return parameter description for the call info object.
addInHeaderInfo( name, type, namespace[, element_type[, mustUnderstand]])
Similar to addInParameter(), this method may be called to define an input SOAP header associated with a service operation. The arguments are the same except that the namespace is required for headers and you may pass an optional true value for mustUnderstand to indicate that support for the header is required.
addOutHeaderInfo( name, type, namespace[, element_type[, mustUnderstand]])
The same as addInHeaderInfo(), but defines an output SOAP header associated with a service operation.
getInParameters()
Return a sequence of ParameterInfo instances representing the input parameters of the operation.
getOutParameters()
Return a sequence of ParameterInfo instances representing the output parameters of the operation.
getReturnParameter()
Return a ParameterInfo instance representing the return parameter of the operation. Note that it possible for SOAP operations to not define a return value, in which case this returns None.
getInHeaders()
The same as getInParameters(), but returns a sequence of HeaderInfo instances.
getOutHeaders()
The same as getOutParameters(), but returns a sequence of HeaderInfo instances.

1.6.2 ParameterInfo Objects

A ParameterInfo object describes a parameter to a web service operation.
name
The name of the parameter.
type
A QName tuple of the form (namespaceURI, typeName) that indicates an XSD simpleType, complexType or element associated with the parameter.
element_type
A boolean value that indicates whether the type attribute of the parameter is a reference to an XSD element rather than a simpleType or complexType. The default for this attribute is 0.
namespace
A namespace URI that is associated with the parameter. The default for this attribute is None.

1.6.3 HeaderInfo Objects

A HeaderInfo object is similar to a ParameterInfo object, but describes a SOAP header associated with a web service operation. The members of HeaderInfo objects are the same as those of ParameterInfo, except that the namespace attribute must have a non-null value and there is an added mustUnderstand attribute indicating whether or not the header is a ``must understand'' SOAP header.

1.6.4 SOAPCallInfo Example

This example demonstrates using a SOAPCallInfo object loaded from WSDL to print out calling information for the methods defined by the WSDL.
from WebService.SOAPCallInfo import callInfoFromWSDL
from WebService.WSDLTools import WSDLReader

wsdl = WSDLReader.loadFromURL('http://www.mssoapinterop.org/asmx/typed.asmx?WSDL')
service = wsdl.services[0]
port = service.ports[0]
binding = port.getBinding()
for item in binding.getOperations():
    callinfo = callInfoFromWSDL(port, item.name)
    print 'Method ' + callinfo.methodName + ' takes arguments: ',
    for param in callinfo.getInParameters():
        print param.name + ' ',
    print

1.7 WebService.SOAPReader

The SOAPReader module provides a relatively simple interface for working with the low-level DOM structures of a SOAP XML message.
class SOAPReader(xmldata)
The SOAPReader class provides methods to simplify traversal of the element structure of a SOAP XML message. It provides quick access to the main structures of a message like the envelope, headers and fault information that would otherwise require a lot of tedious DOM code. The xmldata argument is either a string or a file-like object containing the XML data of a SOAP message.

1.7.1 SOAPReader Objects

document
The DOM document object that underlies the SOAPReader. You can use this to work with the DOM document directly if needed. Note that due to cleanup issues the lifetime of the document is bound to that of the SOAPReader.
version
A string indicating the SOAP protocol version of the message (such as '1.1').
NS_SOAP_ENV
The value of the SOAP envelope namespace corresponding to the SOAP protocol version of the message.
NS_SOAP_ENC
The value of the SOAP encoding namespace corresponding to the SOAP protocol version of the message.
getEnvelope()
Return the SOAP envelope element of the message as a DOM Element.
getHeader()
Return the SOAP header element of the message as a DOM Element, or None if the message does not contain a header.
getHeaderElements()
Return a sequence of the child attributes of the SOAP header element.
getMustUnderstandHeaders()
Return a sequence of the child elements of the SOAP header element that have true mustUnderstand attributes.
getHeaderElement(name[, namespaceURI])
Return the SOAP header entry element with the given name and optional namespaceURI.
getBody()
Return the SOAP body element of the message as a DOM Element.
getBodyElements()
Return a sequence of the child elements of the SOAP body element.
getBodyElement(name[, namespaceURI])
Return the SOAP body entry element with the given name and optional namespaceURI.
getRPCStruct()
Return the RPC struct element of the SOAP message (first child of the SOAP body element), or None if the body has no child elements.
getRPCParams()
Return a sequence of the child elements of the RPC struct of the SOAP message. The return value may be an empty sequence if the RPC struct has no child elements.
getRPCParam(name[, namespaceURI])
Return the RPC parameter element matching the given name and optional namespaceURI.
getRPCResult()
Return the first child element of the RPC struct of the SOAP message, or None if the RPC struct has no child elements.
getElementByRef(reference)
Return the element indicated by the given element href reference.
getElementById(element_id)
Return the element indicated by the given element id.
derefElement(element)
Dereference the given element returning the target element of any href attribute of the element. If element does not have an href attribute, the input element is returned.
getEncodingStyle(element)
Return the active encoding style in the context of the given element.
isFaultMessage()
Return true if the SOAP message contains a fault.
getFault()
Return the SOAP fault element of the message as a DOM Element, or None if the message does not contain a fault.
getFaultString()
Return the *value* of the SOAP faultstring sub-element of the fault element, or None if the message does not contain a fault.
getFaultCode()
Return the *value* of the SOAP faultcode sub-element of the fault element (not including any namespace URI prefix), or None if the message does not contain it.
getFaultCodeNS()
Return the *value* of the namespace URI of the SOAP faultcode sub-element of the fault element, or None if the message does not contain it.
getFaultActor()
Return the *value* of the SOAP faultactor sub-element of the fault element, or None if the message does not contain it.
getFaultDetail()
Return the detail sub-element of the fault element, or None if the message does not contain it.

1.7.2 SOAPReader Example

This example uses a SOAPReader object to read a SOAP message and print the number of RPC parameters it contains.
from WebService.SOAPReader import SOAPReader
from WebService.Utility import DOM

xmldata = '''<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
 SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SOAP-ENV:Body>
  <m:SomeMethodName xmlns:m="Some-URI">
  <param1 xsi:type=''xsd:int''>1</param1>
  <param2 xsi:type=''xsd:int''>2</param2>
  <param3 xsi:type=''xsd:int''>3</param3>
  </m:SomeMethodName>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>'''

reader = SOAPReader(xmldata)
params = reader.getRPCParams()

print 'The number of parameters is ' + str(len(params))

1.8 WebService.SOAPWriter

The SOAPWriter module provides a simplified interface for writing SOAP XML messages.
class SOAPWriter([, version[, encoding]])
The SOAPWriter class is a specialized XMLWriter that provides convenience methods for writing the major structures of a SOAP message. The optional version indicates the SOAP protocol version of the message (which affects the namespaces to be used). The version must be a string indicating a supported SOAP version. The default is '1.1'. If the optional encoding is specified, that encoding will be used for the resulting XML document. The default encoding is UTF-8.

1.8.1 SOAPWriter Objects

SOAPWriter objects extend the XMLWriter interface with methods that simplify the process of writing SOAP XML messages. In particular, the SOAPWriter interface makes it easy to write non-linear constructs, such as RPC parameters that reference data that is actually located in ``trailer'' elements (elements that follow the SOAP body part of the message). For example, you can call startElement() to begin an RPC parameter element, then call startTrailerElement() to write the data element that the RPC element refers to. The trailer element started with startTrailerElement() will be become the active element until it is ended, at which point the original RPC element will once again be the active element. SOAPWriter objects support the following attributes and methods in addition to those inherited from XMLWriter.
NS_SOAP_ENV
The value of the SOAP envelope namespace to be used for this message, based on the version passed in the constructor.
NS_SOAP_ENC
The value of the SOAP encoding namespace to be used for this message, based on the version passed in the constructor.
version
A string representing the SOAP protocol version of this message. This attribute should be considered read-only. It reflects the protocol version passed in the constructor (or the default version if none was given). The default version is '1.1'.
startEnvelope([, encodingStyle])
Begin the SOAP envelope element of the message. If the optional encodingStyle (string) is specified, that value will be written as the encodingStyle attribute of the element.
endEnvelope()
End the SOAP envelope element of the message.
startHeader([, encodingStyle])
Begin the SOAP header element of the message. If the optional encodingStyle (string) is specified, that value will be written as the encodingStyle attribute of the element.
endHeader()
End the SOAP header element of the message.
startHeaderElement( name, namespaceURI, [, mustUnderstand[, actor]])
Begin a header entry element in the SOAP header of the message with the given name and namespaceURI. If the optional mustUnderstand or actor are specified, the corresponding attributes will be written to the header entry element.
endHeaderElement()
End the last started header entry element.
startBody([, encodingStyle])
Begin the SOAP body element of the message. If the optional encodingStyle (string) is specified, that value will be written as the encodingStyle attribute of the element.
endBody()
End the SOAP body element of the message.
startBodyElement( name, [, namespaceURI])
Begin a new child element of the SOAP body element of the message.
endBodyElement()
End the last started body element.
startTrailerElement( name, [, namespaceURI])
Begin a new child element of the SOAP envelope that appears *after* the body element of the message.
endTrailerElement()
End the last started trailer element.
startFault( faultcode, faultstring, [, faultactor[, faultcodeNS]])
Start the SOAP fault element of the message. The SOAP body element must have been started before calling this method, and the body should contain no other elements. The faultcode should be a string fault identifier as defined by the SOAP specification. The faultcode should *not* be namespace prefixed - the writer will automatically add the appropriate prefix (either the SOAP envelope namespace or faultcodeNS, if given). The faultstring and optional faultactor provide a short error message and information about the source of the fault.
endFault()
End the SOAP fault element of the message.
startFaultDetail()
Begin the fault detail element of the message. This must be called between startFault() and endFault().
endFaultDetail()
End the fault detail element of the message.
writeEncodingStyle(encodingStyle)
Write a SOAP encodingStyle attribute to the current element with the given string value.

1.8.2 SOAPWriter Example

This example uses a SOAPWriter object to produce a simple SOAP message.
from WebService.SOAPWriter import SOAPWriter
from WebService.Utility import DOM

writer = SOAPWriter()
writer.startEnvelope(encodingStyle=writer.NS_SOAP_ENC)
writer.startBody()

# Write the RPC struct element.
writer.startElement('BabelFish', 'urn:xmethodsBabelFish')

# Write the parameter elements.
typestr = writer.makeQName(DOM.NS_XSD, 'string')

writer.startElement('translationmode')
writer.writeAttr('type', typestr, DOM.NS_XSI)
writer.writeText('en_de')
writer.endElement()

writer.startElement('sourcedata')
writer.writeAttr('type', typestr, DOM.NS_XSI)
writer.writeText('This is a test!')
writer.endElement()

# End the RPC struct element.
writer.endElement()

writer.endBody()
writer.endEnvelope()

xml = writer.toString(1)
In this example, printing the xml variable would produce:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope 
 SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" 
 xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" 
 xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" 
 xmlns:ns0="urn:xmethodsBabelFish" 
 xmlns:ns1="http://www.w3.org/2001/XMLSchema" 
 xmlns:ns2="http://www.w3.org/2001/XMLSchema-instance">
  <SOAP-ENV:Body>
    <ns0:BabelFish>
      <translationmode ns2:type="ns1:string">
        en_de
      </translationmode>
      <sourcedata ns2:type="ns1:string">
        This is a test!
      </sourcedata>
    </ns0:BabelFish>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

1.9 WebService.XMLWriter

The XMLWriter module provides a simplified interface for writing XML documents.
class XMLWriter([, encoding])
The XMLWriter class manages an internal DOM document, and provides a way to build XML documents that can be simpler and less verbose than using raw DOM APIs. If the optional encoding is specified, that encoding will be used for the resulting XML document. The default encoding is UTF-8.

1.9.1 XMLWriter Objects

document
The DOM document object that underlies the XMLWriter. You can use this to work with the DOM document directly if needed. Note that due to cleanup issues the lifetime of the document is bound to that of the XMLWriter.
encoding
The encoding to be used for the resulting XML document (the default is UTF-8).
startElement([, namespaceURI[, **attrs]])
Begin a new element with the given name and optional namespaceURI at the current point in the document. The return value is the newly created DOM element. Any keyword arguments specified in **attrs will be written as attributes of the element with the given names and values. Note that attributes passed this way will not be namespace-qualified in the resulting XML document. To write namespace-qualified attributes, use the writeAttr() method.
endElement()
End the last started element.
currentElement()
Returns the currently open element of the document.
writeAttr( name, value[, namespaceURI])
Write an attribute with the given name, value and optional namespaceURI to the current element in the document. If a namespaceURI is specified, a namespace declaration and prefix will be generated if necessary.
writeText(value)
Write a string to the content of the current element in the XML document. Any XML special characters in value will be appropriately escaped.
writeCDATA(value)
Write a CDATA section at the current point in the XML document.
writeXML(value)
Write a literal string to the content of the current element in the XML document. Any XML special characters in value will *not* be escaped.
declareNSDefault(namespaceURI)
Declares the default namespace uri to be used for the XML document. This must be called before starting to write the document if a default namespace is to be used.
declareNSPrefix(prefix, namespaceURI)
Adds an XML namespace declaration to the document, associating prefix with namespaceURI. Note that all XML namespace declarations are made on the root element of the resulting document.
getNSPrefix(namespaceURI)
Return the prefix to be used for the given namespace uri. A namespace prefix will be generated (and declared in the XML document) if a prefix for that uri has not yet been declared.
hasNSPrefix(namespaceURI)
Returns true if a prefix has been declared in the document for namespaceURI.
makeQName(namespaceURI, name)
Return an appropriate XML qualified name for the given namespaceURI and name (prefix:name, or simply name if namespaceURI is the default namespace). This value is suitable for qualified name linking within the document.
makeRefId()
Return a new unique id usable as the id attribute of an XML element for referencing purposes.
toString([, format])
Return the XML document as a string (or unicode, depending on the content and encoding of the document). If the optional format argument is a true value, the output will be formatted for readability.

1.9.2 XMLWriter Example

This example uses an XMLWriter object to produce a simple XML document.
from WebService.XMLWriter import XMLWriter

writer = XMLWriter()
writer.startElement('numbers')
for n in range(5):
    writer.startElement('item')
    writer.writeText(str(n))
    writer.endElement()
writer.endElement()

xml = writer.toString(1)
In this example, printing the xml variable would produce:
<?xml version="1.0" encoding="UTF-8"?>
<numbers>
  <item>
    0
  </item>
  <item>
    1
  </item>
  <item>
    2
  </item>
  <item>
    3
  </item>
  <item>
    4
  </item>
</numbers>

1.10 WebService.Serializer

(Give an overview of the architecture here...) The Serializer module provides classes for managing serialization of data to and from SOAP messages. It supports the SOAP RPC encoding as described in the SOAP 1.1 specification, as well as ``document style'' schema-driven serialization.
class Serializer()
A Serializer handles serialization and deserialization of values to and from SOAP messages. It contains built-in type handlers for the standard SOAP and XML Schema primitive types. One or more XMLSchema instances may be loaded into a serializer to provide support for the types defined in the corresponding schema.
class SerializationContext(serializer)
A SerializationContext maintains per-message serialization state when serializing or deserializing data. The context maintains a handle to the serializer in use, as well as configuration data that can be affect the behavior of the serializer and its type handlers.
exception SerializationError
This exception is raised when errors occur in data serialization or deserialization.

1.10.1 Serializer Objects

A Serializer instance contains a number of type handlers, which know how to convert values of a given type to and from XML. The Serializer provides built-in type handlers for the standard SOAP and XML Schema simple types. The built-in type handlers are shared by all Serializer instances. You can register new type handlers with a Serializer instance either explicitly or by loading one or more XMLSchema objects into the instance. [Note: some of the following API docs are ``pro-active truth'' :)]
serialize( name, value, typeName, context[ ,namespace])
xxx
deserialize(element, context)
xxx
registerHandler(typeName, handler)
xxx
findHandler(typeName[ ,default])
xxx
loadSchema(schema)
xxx

1.10.2 SerializationContext Objects

A SerializationContext instance contains per-message serialization state, and provides a common container used to pass various bits of data around during the serialization process. This data includes the SOAPReader or SOAPWriter to be used for input / output, information about the encoding style to be used, multi-reference data and a reference to the Serializer being used.
serializer
The Serializer instance associated with the serialization context.
reader
The SOAPReader that contains the message being deserialized, or None (if the context is for serialization rather than deserialization).
writer
The SOAPWriter that is managing the SOAP message being serialized, or None (if the context is for deserialization rather than serialization).
mapReferences(values)
Call this method to have the context map the reference relationships between the objects in the passed-in sequence of values. After calling this method, the members of values may be used as arguments to the isMultiRef() method.
isMultiRef(value)
Return true if a value is multi-reference (with regard to a sequence of values previously passed to mapReferences().

1.10.3 Python Type Mapping

The mapping of SOAP / XML Schema simple datatypes to Python data types outlined in the table below. Note that unless otherwise specified, 'string' means either a Python (8-bit) string or Unicode type.
Schema Type  Python Type 
xsd:boolean int
xsd:integer long
xsd:unsignedInt long
xsd:unsignedLong long
xsd:nonPositiveInteger long
xsd:nonNegativeInteger long
xsd:negativeInteger long
xsd:positiveInteger long
xsd:long long
xsd:int int
xsd:short int
xsd:unsignedShort int
xsd:byte int
xsd:unsignedByte int
xsd:decimal float
xsd:double float
xsd:float float
xsd:string string
xsd:normalizedString string
xsd:anyURI string
xsd:QName string
xsd:Name string
xsd:NCName string
xsd:token string
xsd:language string
xsd:NOTATION string
xsd:NMTOKENS sequence
xsd:NMTOKEN string
xsd:IDREFS sequence
xsd:IDREF string
xsd:ENTITIES sequence
xsd:ENTITY string
xsd:ID string
xsd:dateTime date-time tuple
xsd:timePeriod date-time tuple
xsd:duration date-time tuple
xsd:time date-time tuple
xsd:date date-time tuple
xsd:gYearMonth date-time tuple
xsd:gYear date-time tuple
xsd:gMonthDay date-time tuple
xsd:gDay date-time tuple
xsd:gMonth date-time tuple
xsd:base64Binary string
xsd:base64 string
xsd:hexBinary string
enc:base64 string
enc:arrayType sequence
There are also a set of default type mappings that are used by the serializer to guess an appropriate schema type when all it has to go on is the Python type of an object.
Schema Type  Python Type 
string xsd:string
int xsd:integer
long xsd:long
float xsd:float
sequence soap-enc:Array

1.11 WebService.XMLSchema

The XMLSchema module provides classes for working with XML schema descriptions. Note that the goal of this module is *not* to provide a general-purpose XMLSchema library usable for validation or other general applications. Rather, this module is intended to provide just enough support for XML schemas to support web services goals (primarily data serialization). The XMLSchema module is based on the W3C's 2001 XML Schema recommendation. The most important classes and exceptions provided by this module are:
class SchemaReader()
The SchemaReader class provides methods for loading XML schema descriptions from URLs or XML data.
class XMLSchema([targetNamespace[, name[, documentation]]])
XMLSchema instances represent XML schema descriptions and provide an object model for working with those descriptions.
exception SchemaError
This exception is raised when errors occur in the parsing or building of XMLSchema objects, usually indicating invalid structure or usage.
Note that there are quite a few other classes defined in the XMLSchema module that implement the WSDL object model. Instances of those classes are generally accessed through XMLSchema objects, and are documented in the following sections.

1.11.1 SchemaReader Objects

SchemaReader instances are the main interface for loading XML schema descriptions from URLs, XML files or XML string data.
loadFromStream(file)
Return an XMLSchema instance representing the schema description contained in file. The file argument must be a seekable file-like object.
loadFromString(data)
Returns an XMLSchema instance loaded from an XML string.
loadFromFile(filename)
Returns an XMLSchema instance loaded from the file named by filename.
loadFromURL(url)
Returns an XMLSchema instance loaded from the given URL.

1.11.2 SchemaReader Example

Here is an example of using SchemaReader to load a schema from a URL and print the names of the global element declarations:
from WebService.XMLSchema import SchemaReader

reader = SchemaReader()
schema = reader.loadFromURL('http://www.example.com/schemas/someSchema.xml')
for element in schema.elements.values():
    print element.name

1.11.3 XMLSchema Objects

XMLSchema instances implement the XML schema object model. They are most often created by loading an XML source into a SchemaReader. A XMLSchema object provides access to the structures that make up a schema description.
targetNamespace
The target namespace associated with the service description, or None if not specified.
location
The URL from which the schema was loaded, or None if the schema was not loaded from a URL.
simpleTypes
TODO: document this.
complexTypes
TODO: document this.
attrGroups
TODO: document this.
modelGroups
TODO: document this.
attributes
TODO: document this.
elements
TODO: document this.
toXML()
Return an XML string representation of the schema object.
TODO: finish documenting schema API and subobject APIs.

1.12 WebService.Transports

The Transports module defines objects that can be used to send and recieve SOAP messages over HTTP and SMTP. The transport objects defined here allow applications to specify timeout limits, which provides some control over the impact of potentially blocking SOAP calls.
class HTTPTransport([timeout])
An HTTPTransport is used to send SOAP messages over the HTTP protocol. An integer timeout, in seconds, may be given to limit the amount of time a connection attempt can block the application. The HTTPTransport can also be used to communicate with secure servers using HTTPS if the Python installation supports SSL. Note that Python does not have SSL support enabled by default. See the Python documentation for details on enabling SSL support.
class SMTPTransport(smtphost, fromaddr, subject, [timeout])
The SMTPTransport is an experimental transport used to send SOAP messages over SMTP. Note that the SOAP specification does not define an official mapping of SOAP to SMTP - the current implementation simply sends SOAP messages as mail messages and includes the SOAPAction value as a MIME header. The smtphost and fromaddr specify the SMTP host and from address to use in messages sent using the transport. The subject gives the subject line that will be used. Like the HTTP transport, a timeout may be specified to control connection blocking.
exception TimeoutError
This exception is raised when network communications time out.

1.12.1 HTTPTransport Objects

followRedirects
This is a boolean attribute that determines whether the transport will attempt to automatically follow HTTP redirects. The default is to follow redirects (throwing an exception if a circular redirect is detected).
userAgent
The string that the transport will send for the HTTP User-Agent header. This may be changed to customize the apparent user agent.
timeout
The socket timeout for the transport, in seconds.
send(address, soapAction, message [, contentType[, headers]])
Send a SOAP message over HTTP or HTTPS (depending on the address URL). The soapAction should be the value to send for the SOAPAction header, and message should be the SOAP message string to send. The optional contentType indicates the content type of the message (which defaults to 'text/xml'. An optional headers mapping may be specified, containing extra HTTP headers to be sent with the message. This method returns an classHTTPResponse instance containing the response information, unless a server error occurs. An HTTPResponse will be raised as an exception for any non-2xx response that does not include a text/xml message body.

1.12.2 HTTPResponse Objects

HTTPResponse objects capture the server response to an HTTP request.
status
The integer status code returned from the server.
reason
The text status message returned from the server.
headers
An mimetools.Message instance that provides access to the HTTP headers returned by the server.
body
The body of the server response, or None if there was no response body.

1.12.3 SMTPTransport Objects

smtphost
The SMTP server to be used to send messages.
fromaddr
The emphfrom address to use when sending messages.
subject
The subject line to use when sending messages.
timeout
The socket timeout for the transport, in seconds.
send(address, soapAction, message [, contentType[, headers]])
Send a SOAP message using SMTP to the given email address. The given soapAction is sent as the value of a SOAPAction MIME header with the message. The message should be the SOAP message string to be sent. The optional contentType indicates the content type of the message (which defaults to 'text/xml'. An optional headers mapping may be specified, containing extra MIME headers to be sent with the message. Since SMTP messaging is inherently one-way, this method returns None.

1.13 The Utility Module

The Utility module provides utilities and constants used by the rest of the web services package.

1.13.1 The DOM Object

Much of the web services package is built on the document object model (DOM). The DOM object defined by the Utility package is a singleton that encapsulates a number of useful DOM functions and constants (such as XML namespaces used by the various web services technologies). The DOM singleton provides interfaces for creating, loading and working with XML documents using the DOM api without having to worry too much about of the actual DOM implementation in use. The web services package currently uses the built-in Python minidom module, which is good enough for most tasks and doesn't require additional software to be added to a standard Python 2.x installation. This section documents the most important general-use attributes and methods of the DOM singleton (see the source for more esoteric things).
createDocument(namespaceURI, qualifiedName)
Return a new DOM document object, with the given values for the root element.
loadDocument(file)
Return a DOM document object loaded from the given file-like object.
loadFromURL(url)
Return a DOM document object loaded from the given URL.
isElement(node, name[, namespaceURI])
Return true if the given DOM node is an element node matching the given name and namespaceURI.
getElement( node, name[, namespaceURI[, default]])
Return a child element of the given DOM node matching the given name and namespaceURI, or the default if given. If no default is given and a matching element is not found, a KeyError is raised.
getElements( node, name[, namespaceURI])
Return a sequence of the child elements of the given DOM node matching the given name and namespaceURI.
getElementById(node, id[, default])
Return a child element of the given node that has an ``id'' attribute matching the given id, or the default if given. If no default is given and a matching element is not found, a KeyError is raised.
getAttr( element, name[, namespaceURI[, default]])
Return the value of the attribute of element with the given name and optional namespaceURI or the default if given. If no default is given and a matching attribute is not found, an empty string is returned.
hasAttr( element, name[, namespaceURI])
Return true if element has an attribute with the given name and optional namespaceURI.
getElementText(element[, preserveWS])
Return the text value of a DOM element. Leading and trailing whitespace is stripped unless preserveWS is a true value.
elementToString(element[, format])
Return a XML string representation of element. If format is true, the string will be formatted for readability.
NS_SOAP_ENV_ALL
A sequence that contains all of the supported SOAP envelope namespaces.
NS_SOAP_ENC_ALL
A sequence that contains all of the supported SOAP encoding namespaces.
NS_SOAP_ENV
The value of the default SOAP envelope namespace (currently the SOAP 1.1 envelope namespace).
NS_SOAP_ENC
The value of the default SOAP encoding namespace (currently the SOAP 1.1 encoding namespace).
SOAPUriToVersion(uri)
Returns the SOAP version string related to the given SOAP envelope uri.
GetSOAPEnvUri(version)
Return the appropriate SOAP envelope uri for a given SOAP version.
GetSOAPEncUri(version)
Return the appropriate SOAP encoding uri for a given SOAP version.
GetSOAPActorNextUri(version)
Return the appropriate SOAP ``next actor'' uri for a given SOAP version.
NS_XSD_ALL
A sequence that contains all of the supported XML Schema namespaces.
NS_XSI_ALL
A sequence that contains all of the supported XML Schema instance namespaces.
NS_XSD
The value of the default XML Schema namespace (currently the XML Schema 2001 namespace).
NS_XSI
The value of the default XML Schema instance namespace (currently the XML Schema 2001 instance namespace).
NS_XSD_99
The value of the 1999 XML Schema namespace.
NS_XSI_99
The value of the 1999 XML Schema instance namespace.
NS_XSD_00
The value of the 2000 XML Schema namespace.
NS_XSI_00
The value of the 2000 XML Schema instance namespace.
NS_XSD_01
The value of the 2001 XML Schema namespace.
NS_XSI_01
The value of the 2001 XML Schema instance namespace.
InstanceUriForSchemaUri(uri)
Returns the appropriate matching XML Schema instance URI for the given XML Schema namspace URI, or None if no match is found.
SchemaUriForInstanceUri(uri)
Returns the appropriate matching XML Schema namespace URI for the given XML Schema instance URI, or None if no match is found.
NS_WSDL_ALL
A sequence that contains all of the supported WSDL namespaces.
NS_WSDL
The value of the default WSDL namespace (currently the WSDL 1.1 namespace).
WSDLUriToVersion(uri)
Returns a version string related to the given WSDL namespace URI.
GetWSDLSoapBindingUri(version)
Return an appropriate namespace URI for the given WSDL version.
GetWSDLHttpBindingUri(version)
Return an appropriate namespace URI for the given WSDL version.
GetWSDLMimeBindingUri(version)
Return an appropriate namespace URI for the given WSDL version.
GetWSDLHttpTransportUri(version)
Return an appropriate namespace URI for the given WSDL version.

About this document ...

Web Services for Python, Oct 29, 2001, Release 1.0

This document was generated using the LaTeX2HTML translator.

LaTeX2HTML is Copyright © 1993, 1994, 1995, 1996, 1997, Nikos Drakos, Computer Based Learning Unit, University of Leeds, and Copyright © 1997, 1998, Ross Moore, Mathematics Department, Macquarie University, Sydney.

The application of LaTeX2HTML to the Python documentation has been heavily tailored by Fred L. Drake, Jr. Original navigation icons were contributed by Christopher Petrilli.