code
stringlengths
501
5.19M
package
stringlengths
2
81
path
stringlengths
9
304
filename
stringlengths
4
145
from os.path import basename import random import string import mimetypes from email.mime.application import MIMEApplication from email.encoders import encode_7or8bit from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from base64 import b64decode, b64encode from lxml import etree from zeep.transports import Transport from zeep.wsdl.utils import etree_to_string from .utils import str_to_sa from zeep.xsd import builtins from zeep.wsdl.bindings import http from zeep.wsdl import wsdl import codecs import zeep.ns from zeep import client BOUND = "MTOM".center(40, "=") # XOP_LINK = "http://www.w3.org/2004/08/xop/include" FILETAG = 'xop:Include:' ID_LEN = 16 func_getid = lambda N: ''.join( random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N)) mimetypes.init() # I need it my WSDL uses it for the data part. def xmlvalue(self, value): """Patch for xmlvalue""" if value.startswith(FILETAG): return value return b64encode(value) def pythonvalue(self, value): """Patch for pythonvalue""" if value.startswith(FILETAG): return value return b64decode(value) def patch_things(): """Patches something""" # Let's patch the Base64Binary data type. builtins.Base64Binary.accepted_types += (etree.Element, ) builtins.Base64Binary.xmlvalue = xmlvalue builtins.Base64Binary.pythonvalue = pythonvalue # Base64Binary patched. # Update NSMAP zeep.ns.XOP = "http://www.w3.org/2004/08/xop/include" zeep.ns.XMIME5 = "http://www.w3.org/2005/05/xmlmime" # attach method for the client. zeep.Client.attach = _client_attach def set_attachnode(node): """Set the attachment node""" cid = node.text[len(FILETAG):] node.text = None etree.SubElement( node, '{{{}}}Include'.format(zeep.ns.XOP), href="cid:{}".format(cid)) return cid def get_multipart(): """Get the main multipart object""" part = MIMEMultipart( 'related', charset='utf-8', type='application/xop+xml', boundary=BOUND, start='<soap-env:Envelope>') part.set_param('start-info', 'text/xml') part.add_header('Accept-Encoding', 'gzip,deflate') part.add_header('SOAPAction', '""') part.add_header('MIME-Version', '1.0') part.add_header('Host', 'test-idahe.ordre.medecin.fr') part.add_header('Connection', 'Keep-Alive') part.add_header('User-Agent', 'Apache-HttpClient/4.1.1 (java 1.5)') return part def get_envelopepart(envelope): """The Envelope part""" part = MIMEApplication(etree_to_string(envelope), 'xop+xml', encode_7or8bit) part.set_param('charset', 'UTF-8') part.set_param('type', 'application/soap+xml') part.add_header('Content-Transfer-Encoding', '8bit') part.add_header('Content-ID', '<soap-env:Envelope>') return part def _client_attach(self, filename): """add attachment""" attach = Attachment(filename) self.transport.attachments[str_to_sa(attach.cid)] = attach return attach.tag class Attachment(object): """Attachment class""" def __init__(self, filename): self.filename = filename self.basename = basename(self.filename) self.cid = func_getid(ID_LEN) + ":" + self.basename self.tag = FILETAG + self.cid class TransportWithAttach(Transport): """Transport with attachment""" def __init__(self, cache=None, timeout=300, operation_timeout=None, session=None): self.attachments = {} patch_things() super(TransportWithAttach, self).__init__( cache=cache, timeout=timeout, operation_timeout=operation_timeout, session=session) def post_xml(self, address, envelope, headers): # Search for values that startswith FILETAG filetags = envelope.xpath( "//*[starts-with(text(), '{}')]".format(FILETAG)) # if there is some attached file we set the attachments if filetags: message = self.set_attachs(filetags, envelope, headers) # else just the envelope else: message = etree_to_string(envelope) # post the data. return self.post(address, message, headers) def set_attachs(self, filetags, envelope, headers): """Set mtom attachs and return the right envelope""" # let's get the mtom multi part. mtom_part = get_multipart() # let's set xop:Include for al the files. # we need to do this before get the envelope part. files = [set_attachnode(f) for f in filetags] # get the envelope part. env_part = get_envelopepart(envelope) # attach the env_part to the multipart. mtom_part.attach(env_part) # for each filename in files. for cid in files: cid = str_to_sa(cid) # attach the filepart to the multipart. part = self.get_attachpart(cid) mtom_part.attach(part) # some other stuff. bound = '--{}'.format(mtom_part.get_boundary()) marray = mtom_part.as_string().split(bound) mtombody = bound mtombody += bound.join(marray[1:]) mtom_part.add_header("Content-Length", str(len(mtombody))) headers.update(dict(mtom_part.items())) # Awesome Corentin Patch to deal with the f* windows cp1252 encoding ;) mtom_payloads = mtom_part._payload res = "%s\n%s\n%s\n" % (bound, mtom_part._payload[0].as_string(), bound) for part in mtom_part._payload[1:]: res += "\n".join(["%s: %s" % (header[0], str_to_sa(header[1])) for header in part._headers]) + "\n\n%s" % part._payload + "\n%s\n" % bound res = res.replace('\n', '\r\n', 5) return res def get_attachpart(self, cid): """The file part""" attach = self.attachments[cid] mime_type = mimetypes.types_map[".%s" % attach.basename.split(".")[-1]].split("/") part = MIMEBase(mime_type[0], mime_type[1]) part['Content-Type'] = "%s/%s; charset=us-ascii; name=%s" % (mime_type[0], mime_type[1], attach.filename.split("/")[-1]) part['Content-Transfer-Encoding'] = "7bit" part['Content-ID'] = "<{}>".format(attach.cid) part['Content-Disposition'] = 'attachment; name="%s"; filename="%s"' % (attach.filename.split("/")[-1], attach.filename.split("/")[-1]) file_content = codecs.open(attach.filename, 'r', 'latin-1').read() self.file_content = file_content part.set_payload(file_content) del part['mime-version'] return part
zeep-adv
/zeep-adv-1.4.4.tar.gz/zeep-adv-1.4.4/src/zeep/transport_with_attach.py
transport_with_attach.py
from lxml import etree from zeep.utils import qname_attr from zeep.wsdl import definitions NSMAP = { 'wsdl': 'http://schemas.xmlsoap.org/wsdl/', 'wsaw': 'http://www.w3.org/2006/05/addressing/wsdl', } def parse_abstract_message(wsdl, xmlelement): """Create an AbstractMessage object from a xml element. Definition:: <definitions .... > <message name="nmtoken"> * <part name="nmtoken" element="qname"? type="qname"?/> * </message> </definitions> :param wsdl: The parent definition instance :type wsdl: zeep.wsdl.wsdl.Definition :param xmlelement: The XML node :type xmlelement: lxml.etree._Element :rtype: zeep.wsdl.definitions.AbstractMessage """ tns = wsdl.target_namespace parts = [] for part in xmlelement.findall('wsdl:part', namespaces=NSMAP): part_name = part.get('name') part_element = qname_attr(part, 'element', tns) part_type = qname_attr(part, 'type', tns) if part_element is not None: part_element = wsdl.types.get_element(part_element) if part_type is not None: part_type = wsdl.types.get_type(part_type) part = definitions.MessagePart(part_element, part_type) parts.append((part_name, part)) # Create the object, add the parts and return it message_name = qname_attr(xmlelement, 'name', tns) msg = definitions.AbstractMessage(message_name) for part_name, part in parts: msg.add_part(part_name, part) return msg def parse_abstract_operation(wsdl, xmlelement): """Create an AbstractOperation object from a xml element. This is called from the parse_port_type function since the abstract operations are part of the port type element. Definition:: <wsdl:operation name="nmtoken">* <wsdl:documentation .... /> ? <wsdl:input name="nmtoken"? message="qname">? <wsdl:documentation .... /> ? </wsdl:input> <wsdl:output name="nmtoken"? message="qname">? <wsdl:documentation .... /> ? </wsdl:output> <wsdl:fault name="nmtoken" message="qname"> * <wsdl:documentation .... /> ? </wsdl:fault> </wsdl:operation> :param wsdl: The parent definition instance :type wsdl: zeep.wsdl.wsdl.Definition :param xmlelement: The XML node :type xmlelement: lxml.etree._Element :rtype: zeep.wsdl.definitions.AbstractOperation """ name = xmlelement.get('name') kwargs = { 'fault_messages': {} } for msg_node in xmlelement.getchildren(): tag_name = etree.QName(msg_node.tag).localname if tag_name not in ('input', 'output', 'fault'): continue param_msg = qname_attr( msg_node, 'message', wsdl.target_namespace) param_name = msg_node.get('name') param_value = wsdl.get('messages', param_msg.text) if tag_name == 'input': kwargs['input_message'] = param_value elif tag_name == 'output': kwargs['output_message'] = param_value else: kwargs['fault_messages'][param_name] = param_value wsa_action = msg_node.get(etree.QName(NSMAP['wsaw'], 'Action')) param_value.wsa_action = wsa_action kwargs['name'] = name kwargs['parameter_order'] = xmlelement.get('parameterOrder') return definitions.AbstractOperation(**kwargs) def parse_port_type(wsdl, xmlelement): """Create a PortType object from a xml element. Definition:: <wsdl:definitions .... > <wsdl:portType name="nmtoken"> <wsdl:operation name="nmtoken" .... /> * </wsdl:portType> </wsdl:definitions> :param wsdl: The parent definition instance :type wsdl: zeep.wsdl.wsdl.Definition :param xmlelement: The XML node :type xmlelement: lxml.etree._Element :rtype: zeep.wsdl.definitions.PortType """ name = qname_attr(xmlelement, 'name', wsdl.target_namespace) operations = {} for elm in xmlelement.findall('wsdl:operation', namespaces=NSMAP): operation = parse_abstract_operation(wsdl, elm) operations[operation.name] = operation return definitions.PortType(name, operations) def parse_port(wsdl, xmlelement): """Create a Port object from a xml element. This is called via the parse_service function since ports are part of the service xml elements. Definition:: <wsdl:port name="nmtoken" binding="qname"> * <wsdl:documentation .... /> ? <-- extensibility element --> </wsdl:port> :param wsdl: The parent definition instance :type wsdl: zeep.wsdl.wsdl.Definition :param xmlelement: The XML node :type xmlelement: lxml.etree._Element :rtype: zeep.wsdl.definitions.Port """ name = xmlelement.get('name') binding_name = qname_attr(xmlelement, 'binding', wsdl.target_namespace) return definitions.Port(name, binding_name=binding_name, xmlelement=xmlelement) def parse_service(wsdl, xmlelement): """ Definition:: <wsdl:service name="nmtoken"> * <wsdl:documentation .... />? <wsdl:port name="nmtoken" binding="qname"> * <wsdl:documentation .... /> ? <-- extensibility element --> </wsdl:port> <-- extensibility element --> </wsdl:service> Example:: <service name="StockQuoteService"> <documentation>My first service</documentation> <port name="StockQuotePort" binding="tns:StockQuoteBinding"> <soap:address location="http://example.com/stockquote"/> </port> </service> :param wsdl: The parent definition instance :type wsdl: zeep.wsdl.wsdl.Definition :param xmlelement: The XML node :type xmlelement: lxml.etree._Element :rtype: zeep.wsdl.definitions.Service """ name = xmlelement.get('name') ports = [] for port_node in xmlelement.findall('wsdl:port', namespaces=NSMAP): port = parse_port(wsdl, port_node) if port: ports.append(port) obj = definitions.Service(name) for port in ports: obj.add_port(port) return obj
zeep-adv
/zeep-adv-1.4.4.tar.gz/zeep-adv-1.4.4/src/zeep/wsdl/parse.py
parse.py
from __future__ import print_function import logging import operator import os from collections import OrderedDict import six from lxml import etree from zeep.loader import absolute_location, is_relative_path, load_external from zeep.utils import findall_multiple_ns from zeep.wsdl import parse from zeep.xsd import Schema NSMAP = { 'wsdl': 'http://schemas.xmlsoap.org/wsdl/', } logger = logging.getLogger(__name__) class Document(object): """A WSDL Document exists out of one or more definitions. There is always one 'root' definition which should be passed as the location to the Document. This definition can import other definitions. These imports are non-transitive, only the definitions defined in the imported document are available in the parent definition. This Document is mostly just a simple interface to the root definition. After all definitions are loaded the definitions are resolved. This resolves references which were not yet available during the initial parsing phase. :param location: Location of this WSDL :type location: string :param transport: The transport object to be used :type transport: zeep.transports.Transport :param base: The base location of this document :type base: str :param strict: Indicates if strict mode is enabled :type strict: bool """ def __init__(self, location, transport, base=None, strict=True): """Initialize a WSDL document. The root definition properties are exposed as entry points. """ if isinstance(location, six.string_types): if is_relative_path(location): location = os.path.abspath(location) self.location = location else: self.location = base self.transport = transport self.strict = strict # Dict with all definition objects within this WSDL self._definitions = {} self.types = Schema( node=None, transport=self.transport, location=self.location, strict=self.strict) document = self._get_xml_document(location) root_definitions = Definition(self, document, self.location) root_definitions.resolve_imports() # Make the wsdl definitions public self.messages = root_definitions.messages self.port_types = root_definitions.port_types self.bindings = root_definitions.bindings self.services = root_definitions.services def __repr__(self): return '<WSDL(location=%r)>' % self.location def dump(self): print('') print("Prefixes:") for prefix, namespace in self.types.prefix_map.items(): print(' ' * 4, '%s: %s' % (prefix, namespace)) print('') print("Global elements:") for elm_obj in sorted(self.types.elements, key=lambda k: k.qname): value = elm_obj.signature(schema=self.types) print(' ' * 4, value) print('') print("Global types:") for type_obj in sorted(self.types.types, key=lambda k: k.qname or ''): value = type_obj.signature(schema=self.types) print(' ' * 4, value) print('') print("Bindings:") for binding_obj in sorted(self.bindings.values(), key=lambda k: six.text_type(k)): print(' ' * 4, six.text_type(binding_obj)) print('') for service in self.services.values(): print(six.text_type(service)) for port in service.ports.values(): print(' ' * 4, six.text_type(port)) print(' ' * 8, 'Operations:') operations = sorted( port.binding._operations.values(), key=operator.attrgetter('name')) for operation in operations: print('%s%s' % (' ' * 12, six.text_type(operation))) print('') def _get_xml_document(self, location): """Load the XML content from the given location and return an lxml.Element object. :param location: The URL of the document to load :type location: string """ return load_external( location, self.transport, self.location, strict=self.strict) def _add_definition(self, definition): key = (definition.target_namespace, definition.location) self._definitions[key] = definition class Definition(object): """The Definition represents one wsdl:definition within a Document. :param wsdl: The wsdl """ def __init__(self, wsdl, doc, location): """fo :param wsdl: The wsdl """ logger.debug("Creating definition for %s", location) self.wsdl = wsdl self.location = location self.types = wsdl.types self.port_types = {} self.messages = {} self.bindings = {} self.services = OrderedDict() self.imports = {} self._resolved_imports = False self.target_namespace = doc.get('targetNamespace') self.wsdl._add_definition(self) self.nsmap = doc.nsmap # Process the definitions self.parse_imports(doc) self.parse_types(doc) self.messages = self.parse_messages(doc) self.port_types = self.parse_ports(doc) self.bindings = self.parse_binding(doc) self.services = self.parse_service(doc) def __repr__(self): return '<Definition(location=%r)>' % self.location def get(self, name, key, _processed=None): container = getattr(self, name) if key in container: return container[key] # Turns out that no one knows if the wsdl import statement is # transitive or not. WSDL/SOAP specs are awesome... So lets just do it. # TODO: refactor me into something more sane _processed = _processed or set() if self.target_namespace not in _processed: _processed.add(self.target_namespace) for definition in self.imports.values(): try: return definition.get(name, key, _processed) except IndexError: # Try to see if there is an item which has no namespace # but where the localname matches. This is basically for # #356 but in the future we should also ignore mismatching # namespaces as last fallback fallback_key = etree.QName(key).localname try: return definition.get(name, fallback_key, _processed) except IndexError: pass raise IndexError("No definition %r in %r found" % (key, name)) def resolve_imports(self): """Resolve all root elements (types, messages, etc).""" # Simple guard to protect against cyclic imports if self._resolved_imports: return self._resolved_imports = True for definition in self.imports.values(): definition.resolve_imports() for message in self.messages.values(): message.resolve(self) for port_type in self.port_types.values(): port_type.resolve(self) for binding in self.bindings.values(): binding.resolve(self) for service in self.services.values(): service.resolve(self) def parse_imports(self, doc): """Import other WSDL definitions in this document. Note that imports are non-transitive, so only import definitions which are defined in the imported document and ignore definitions imported in that document. This should handle recursive imports though: A -> B -> A A -> B -> C -> A :param doc: The source document :type doc: lxml.etree._Element """ for import_node in doc.findall("wsdl:import", namespaces=NSMAP): namespace = import_node.get('namespace') location = import_node.get('location') location = absolute_location(location, self.location) key = (namespace, location) if key in self.wsdl._definitions: self.imports[key] = self.wsdl._definitions[key] else: document = self.wsdl._get_xml_document(location) if etree.QName(document.tag).localname == 'schema': self.types.add_documents([document], location) else: wsdl = Definition(self.wsdl, document, location) self.imports[key] = wsdl def parse_types(self, doc): """Return an xsd.Schema() instance for the given wsdl:types element. If the wsdl:types contain multiple schema definitions then a new wrapping xsd.Schema is defined with xsd:import statements linking them together. If the wsdl:types doesn't container an xml schema then an empty schema is returned instead. Definition:: <definitions .... > <types> <xsd:schema .... />* </types> </definitions> :param doc: The source document :type doc: lxml.etree._Element """ namespace_sets = [ { 'xsd': 'http://www.w3.org/2001/XMLSchema', 'wsdl': 'http://schemas.xmlsoap.org/wsdl/', }, { 'xsd': 'http://www.w3.org/1999/XMLSchema', 'wsdl': 'http://schemas.xmlsoap.org/wsdl/', }, ] # Find xsd:schema elements (wsdl:types/xsd:schema) schema_nodes = findall_multiple_ns( doc, 'wsdl:types/xsd:schema', namespace_sets) self.types.add_documents(schema_nodes, self.location) def parse_messages(self, doc): """ Definition:: <definitions .... > <message name="nmtoken"> * <part name="nmtoken" element="qname"? type="qname"?/> * </message> </definitions> :param doc: The source document :type doc: lxml.etree._Element """ result = {} for msg_node in doc.findall("wsdl:message", namespaces=NSMAP): msg = parse.parse_abstract_message(self, msg_node) result[msg.name.text] = msg logger.debug("Adding message: %s", msg.name.text) return result def parse_ports(self, doc): """Return dict with `PortType` instances as values Definition:: <wsdl:definitions .... > <wsdl:portType name="nmtoken"> <wsdl:operation name="nmtoken" .... /> * </wsdl:portType> </wsdl:definitions> :param doc: The source document :type doc: lxml.etree._Element """ result = {} for port_node in doc.findall('wsdl:portType', namespaces=NSMAP): port_type = parse.parse_port_type(self, port_node) result[port_type.name.text] = port_type logger.debug("Adding port: %s", port_type.name.text) return result def parse_binding(self, doc): """Parse the binding elements and return a dict of bindings. Currently supported bindings are Soap 1.1, Soap 1.2., HTTP Get and HTTP Post. The detection of the type of bindings is done by the bindings themselves using the introspection of the xml nodes. Definition:: <wsdl:definitions .... > <wsdl:binding name="nmtoken" type="qname"> * <-- extensibility element (1) --> * <wsdl:operation name="nmtoken"> * <-- extensibility element (2) --> * <wsdl:input name="nmtoken"? > ? <-- extensibility element (3) --> </wsdl:input> <wsdl:output name="nmtoken"? > ? <-- extensibility element (4) --> * </wsdl:output> <wsdl:fault name="nmtoken"> * <-- extensibility element (5) --> * </wsdl:fault> </wsdl:operation> </wsdl:binding> </wsdl:definitions> :param doc: The source document :type doc: lxml.etree._Element :returns: Dictionary with binding name as key and Binding instance as value :rtype: dict """ result = {} if not getattr(self.wsdl.transport, 'supports_async', False): from zeep.wsdl import bindings binding_classes = [ bindings.Soap11Binding, bindings.Soap12Binding, bindings.HttpGetBinding, bindings.HttpPostBinding, ] else: from zeep.asyncio import bindings # Python 3.5+ syntax binding_classes = [ bindings.AsyncSoap11Binding, bindings.AsyncSoap12Binding, ] for binding_node in doc.findall('wsdl:binding', namespaces=NSMAP): # Detect the binding type binding = None for binding_class in binding_classes: if binding_class.match(binding_node): try: binding = binding_class.parse(self, binding_node) except NotImplementedError as exc: logger.debug("Ignoring binding: %s", exc) continue logger.debug("Adding binding: %s", binding.name.text) result[binding.name.text] = binding break return result def parse_service(self, doc): """ Definition:: <wsdl:definitions .... > <wsdl:service .... > * <wsdl:port name="nmtoken" binding="qname"> * <-- extensibility element (1) --> </wsdl:port> </wsdl:service> </wsdl:definitions> :param doc: The source document :type doc: lxml.etree._Element """ result = OrderedDict() for service_node in doc.findall('wsdl:service', namespaces=NSMAP): service = parse.parse_service(self, service_node) result[service.name] = service logger.debug("Adding service: %s", service.name) return result
zeep-adv
/zeep-adv-1.4.4.tar.gz/zeep-adv-1.4.4/src/zeep/wsdl/wsdl.py
wsdl.py
from collections import OrderedDict, namedtuple from six import python_2_unicode_compatible MessagePart = namedtuple('MessagePart', ['element', 'type']) class AbstractMessage(object): """Messages consist of one or more logical parts. Each part is associated with a type from some type system using a message-typing attribute. The set of message-typing attributes is extensible. WSDL defines several such message-typing attributes for use with XSD: - element: Refers to an XSD element using a QName. - type: Refers to an XSD simpleType or complexType using a QName. """ def __init__(self, name): self.name = name self.parts = OrderedDict() def __repr__(self): return '<%s(name=%r)>' % (self.__class__.__name__, self.name.text) def resolve(self, definitions): pass def add_part(self, name, element): self.parts[name] = element class AbstractOperation(object): """Abstract operations are defined in the wsdl's portType elements.""" def __init__(self, name, input_message=None, output_message=None, fault_messages=None, parameter_order=None): """Initialize the abstract operation. :param name: The name of the operation :type name: str :param input_message: Message to generate the request XML :type input_message: AbstractMessage :param output_message: Message to process the response XML :type output_message: AbstractMessage :param fault_messages: Dict of messages to handle faults :type fault_messages: dict of str: AbstractMessage """ self.name = name self.input_message = input_message self.output_message = output_message self.fault_messages = fault_messages self.parameter_order = parameter_order class PortType(object): def __init__(self, name, operations): self.name = name self.operations = operations def __repr__(self): return '<%s(name=%r)>' % ( self.__class__.__name__, self.name.text) def resolve(self, definitions): pass @python_2_unicode_compatible class Binding(object): """Base class for the various bindings (SoapBinding / HttpBinding) .. raw:: ascii Binding | +-> Operation | +-> ConcreteMessage | +-> AbstractMessage """ def __init__(self, wsdl, name, port_name): """Binding :param wsdl: :type wsdl: :param name: :type name: string :param port_name: :type port_name: string """ self.name = name self.port_name = port_name self.port_type = None self.wsdl = wsdl self._operations = {} def resolve(self, definitions): self.port_type = definitions.get('port_types', self.port_name.text) for operation in self._operations.values(): operation.resolve(definitions) def _operation_add(self, operation): # XXX: operation name is not unique self._operations[operation.name] = operation def __str__(self): return '%s: %s' % (self.__class__.__name__, self.name.text) def __repr__(self): return '<%s(name=%r, port_type=%r)>' % ( self.__class__.__name__, self.name.text, self.port_type) def get(self, key): try: return self._operations[key] except KeyError: raise ValueError("No such operation %r on %s" % (key, self.name)) @classmethod def match(cls, node): raise NotImplementedError() @classmethod def parse(cls, definitions, xmlelement): raise NotImplementedError() @python_2_unicode_compatible class Operation(object): """Concrete operation Contains references to the concrete messages """ def __init__(self, name, binding): self.name = name self.binding = binding self.abstract = None self.style = None self.input = None self.output = None self.faults = {} def resolve(self, definitions): self.abstract = self.binding.port_type.operations[self.name] def __repr__(self): return '<%s(name=%r, style=%r)>' % ( self.__class__.__name__, self.name, self.style) def __str__(self): if not self.input: return u'%s(missing input message)' % (self.name) retval = u'%s(%s)' % (self.name, self.input.signature()) if self.output: retval += u' -> %s' % (self.output.signature(as_output=True)) return retval def create(self, *args, **kwargs): return self.input.serialize(*args, **kwargs) def process_reply(self, envelope): raise NotImplementedError() @classmethod def parse(cls, wsdl, xmlelement, binding): """ Definition:: <wsdl:operation name="nmtoken"> * <-- extensibility element (2) --> * <wsdl:input name="nmtoken"? > ? <-- extensibility element (3) --> </wsdl:input> <wsdl:output name="nmtoken"? > ? <-- extensibility element (4) --> * </wsdl:output> <wsdl:fault name="nmtoken"> * <-- extensibility element (5) --> * </wsdl:fault> </wsdl:operation> """ raise NotImplementedError() @python_2_unicode_compatible class Port(object): """Specifies an address for a binding, thus defining a single communication endpoint. """ def __init__(self, name, binding_name, xmlelement): self.name = name self._resolve_context = { 'binding_name': binding_name, 'xmlelement': xmlelement, } # Set during resolve() self.binding = None self.binding_options = None def __repr__(self): return '<%s(name=%r, binding=%r, %r)>' % ( self.__class__.__name__, self.name, self.binding, self.binding_options) def __str__(self): return u'Port: %s (%s)' % (self.name, self.binding) def resolve(self, definitions): if self._resolve_context is None: return try: self.binding = definitions.get( 'bindings', self._resolve_context['binding_name'].text) except IndexError: return False if definitions.location: force_https = definitions.location.startswith('https') else: force_https = False self.binding_options = self.binding.process_service_port( self._resolve_context['xmlelement'], force_https) self._resolve_context = None return True @python_2_unicode_compatible class Service(object): """Used to aggregate a set of related ports. """ def __init__(self, name): self.ports = OrderedDict() self.name = name self._is_resolved = False def __str__(self): return u'Service: %s' % self.name def __repr__(self): return '<%s(name=%r, ports=%r)>' % ( self.__class__.__name__, self.name, self.ports) def resolve(self, definitions): if self._is_resolved: return unresolved = [] for name, port in self.ports.items(): is_resolved = port.resolve(definitions) if not is_resolved: unresolved.append(name) # Remove unresolved bindings (http etc) for name in unresolved: del self.ports[name] self._is_resolved = True def add_port(self, port): self.ports[port.name] = port
zeep-adv
/zeep-adv-1.4.4.tar.gz/zeep-adv-1.4.4/src/zeep/wsdl/definitions.py
definitions.py
import six from defusedxml.lxml import fromstring from lxml import etree from zeep import ns, xsd from zeep.helpers import serialize_object from zeep.wsdl.messages.base import ConcreteMessage, SerializedMessage from zeep.wsdl.utils import etree_to_string __all__ = [ 'MimeContent', 'MimeXML', 'MimeMultipart', ] class MimeMessage(ConcreteMessage): _nsmap = { 'mime': ns.MIME, } def __init__(self, wsdl, name, operation, part_name): super(MimeMessage, self).__init__(wsdl, name, operation) self.part_name = part_name def resolve(self, definitions, abstract_message): """Resolve the body element The specs are (again) not really clear how to handle the message parts in relation the message element vs type. The following strategy is chosen, which seem to work: - If the message part has a name and it maches then set it as body - If the message part has a name but it doesn't match but there are no other message parts, then just use that one. - If the message part has no name then handle it like an rpc call, in other words, each part is an argument. """ self.abstract = abstract_message if self.part_name and self.abstract.parts: if self.part_name in self.abstract.parts: message = self.abstract.parts[self.part_name] elif len(self.abstract.parts) == 1: message = list(self.abstract.parts.values())[0] else: raise ValueError( "Multiple parts for message %r while no matching part found" % self.part_name) if message.element: self.body = message.element else: elm = xsd.Element(self.part_name, message.type) self.body = xsd.Element( self.operation.name, xsd.ComplexType(xsd.Sequence([elm]))) else: children = [] for name, message in self.abstract.parts.items(): if message.element: elm = message.element.clone(name) else: elm = xsd.Element(name, message.type) children.append(elm) self.body = xsd.Element( self.operation.name, xsd.ComplexType(xsd.Sequence(children))) class MimeContent(MimeMessage): """WSDL includes a way to bind abstract types to concrete messages in some MIME format. Bindings for the following MIME types are defined: - multipart/related - text/xml - application/x-www-form-urlencoded - Others (by specifying the MIME type string) The set of defined MIME types is both large and evolving, so it is not a goal for WSDL to exhaustively define XML grammar for each MIME type. :param wsdl: The main wsdl document :type wsdl: zeep.wsdl.wsdl.Document :param name: :param operation: The operation to which this message belongs :type operation: zeep.wsdl.bindings.soap.SoapOperation :param part_name: :type type: str """ def __init__(self, wsdl, name, operation, content_type, part_name): super(MimeContent, self).__init__(wsdl, name, operation, part_name) self.content_type = content_type def serialize(self, *args, **kwargs): value = self.body(*args, **kwargs) headers = { 'Content-Type': self.content_type } data = '' if self.content_type == 'application/x-www-form-urlencoded': items = serialize_object(value) data = six.moves.urllib.parse.urlencode(items) elif self.content_type == 'text/xml': document = etree.Element('root') self.body.render(document, value) data = etree_to_string(document.getchildren()[0]) return SerializedMessage( path=self.operation.location, headers=headers, content=data) def deserialize(self, node): node = fromstring(node) part = list(self.abstract.parts.values())[0] return part.type.parse_xmlelement(node) @classmethod def parse(cls, definitions, xmlelement, operation): name = xmlelement.get('name') part_name = content_type = None content_node = xmlelement.find('mime:content', namespaces=cls._nsmap) if content_node is not None: content_type = content_node.get('type') part_name = content_node.get('part') obj = cls(definitions.wsdl, name, operation, content_type, part_name) return obj class MimeXML(MimeMessage): """To specify XML payloads that are not SOAP compliant (do not have a SOAP Envelope), but do have a particular schema, the mime:mimeXml element may be used to specify that concrete schema. The part attribute refers to a message part defining the concrete schema of the root XML element. The part attribute MAY be omitted if the message has only a single part. The part references a concrete schema using the element attribute for simple parts or type attribute for composite parts :param wsdl: The main wsdl document :type wsdl: zeep.wsdl.wsdl.Document :param name: :param operation: The operation to which this message belongs :type operation: zeep.wsdl.bindings.soap.SoapOperation :param part_name: :type type: str """ def serialize(self, *args, **kwargs): raise NotImplementedError() def deserialize(self, node): node = fromstring(node) part = next(iter(self.abstract.parts.values()), None) return part.element.parse(node, self.wsdl.types) @classmethod def parse(cls, definitions, xmlelement, operation): name = xmlelement.get('name') part_name = None content_node = xmlelement.find('mime:mimeXml', namespaces=cls._nsmap) if content_node is not None: part_name = content_node.get('part') obj = cls(definitions.wsdl, name, operation, part_name) return obj class MimeMultipart(MimeMessage): """The multipart/related MIME type aggregates an arbitrary set of MIME formatted parts into one message using the MIME type "multipart/related". The mime:multipartRelated element describes the concrete format of such a message:: <mime:multipartRelated> <mime:part> * <-- mime element --> </mime:part> </mime:multipartRelated> The mime:part element describes each part of a multipart/related message. MIME elements appear within mime:part to specify the concrete MIME type for the part. If more than one MIME element appears inside a mime:part, they are alternatives. :param wsdl: The main wsdl document :type wsdl: zeep.wsdl.wsdl.Document :param name: :param operation: The operation to which this message belongs :type operation: zeep.wsdl.bindings.soap.SoapOperation :param part_name: :type type: str """ pass
zeep-adv
/zeep-adv-1.4.4.tar.gz/zeep-adv-1.4.4/src/zeep/wsdl/messages/mime.py
mime.py
import copy from collections import OrderedDict from lxml import etree from lxml.builder import ElementMaker from zeep import exceptions, xsd from zeep.utils import as_qname from zeep.wsdl.messages.base import ConcreteMessage, SerializedMessage __all__ = [ 'DocumentMessage', 'RpcMessage', ] class SoapMessage(ConcreteMessage): """Base class for the SOAP Document and RPC messages :param wsdl: The main wsdl document :type wsdl: zeep.wsdl.Document :param name: :param operation: The operation to which this message belongs :type operation: zeep.wsdl.bindings.soap.SoapOperation :param type: 'input' or 'output' :type type: str :param nsmap: The namespace mapping :type nsmap: dict """ def __init__(self, wsdl, name, operation, type, nsmap): super(SoapMessage, self).__init__(wsdl, name, operation) self.nsmap = nsmap self.abstract = None # Set during resolve() self.type = type self.body = None self.header = None self.envelope = None def serialize(self, *args, **kwargs): """Create a SerializedMessage for this message""" nsmap = { 'soap-env': self.nsmap['soap-env'] } nsmap.update(self.wsdl.types._prefix_map_custom) soap = ElementMaker(namespace=self.nsmap['soap-env'], nsmap=nsmap) body = header = None # Create the soap:header element headers_value = kwargs.pop('_soapheaders', None) header = self._serialize_header(headers_value, nsmap) # Create the soap:body element if self.body: body_value = self.body(*args, **kwargs) body = soap.Body() self.body.render(body, body_value) # Create the soap:envelope envelope = soap.Envelope() if header is not None: envelope.append(header) if body is not None: envelope.append(body) # XXX: This is only used in Soap 1.1 so should be moved to the the # Soap11Binding._set_http_headers(). But let's keep it like this for # now. headers = { 'SOAPAction': '"%s"' % self.operation.soapaction } return SerializedMessage( path=None, headers=headers, content=envelope) def deserialize(self, envelope): """Deserialize the SOAP:Envelope and return a CompoundValue with the result. """ if not self.envelope: return None body = envelope.find('soap-env:Body', namespaces=self.nsmap) body_result = self._deserialize_body(body) header = envelope.find('soap-env:Header', namespaces=self.nsmap) headers_result = self._deserialize_headers(header) kwargs = body_result kwargs.update(headers_result) result = self.envelope(**kwargs) # If the message if self.header.type._element: return result result = result.body if result is None or len(result) == 0: return None elif len(result) > 1: return result # Check if we can remove the wrapping object to make the return value # easier to use. result = next(iter(result.__values__.values())) if isinstance(result, xsd.CompoundValue): children = result._xsd_type.elements if len(children) == 1: item_name, item_element = children[0] retval = getattr(result, item_name) return retval return result def signature(self, as_output=False): if not self.envelope: return None if as_output: if isinstance(self.envelope.type, xsd.ComplexType): try: if len(self.envelope.type.elements) == 1: return self.envelope.type.elements[0][1].type.signature( schema=self.wsdl.types, standalone=False) except AttributeError: return None return self.envelope.type.signature(schema=self.wsdl.types, standalone=False) parts = [self.body.type.signature(schema=self.wsdl.types, standalone=False)] if self.header.type._element: parts.append('_soapheaders={%s}' % self.header.type.signature( schema=self.wsdl.types, standalone=False)) return ', '.join(part for part in parts if part) @classmethod def parse(cls, definitions, xmlelement, operation, type, nsmap): """Parse a wsdl:binding/wsdl:operation/wsdl:operation for the SOAP implementation. Each wsdl:operation can contain three child nodes: - input - output - fault Definition for input/output:: <input> <soap:body parts="nmtokens"? use="literal|encoded" encodingStyle="uri-list"? namespace="uri"?> <soap:header message="qname" part="nmtoken" use="literal|encoded" encodingStyle="uri-list"? namespace="uri"?>* <soap:headerfault message="qname" part="nmtoken" use="literal|encoded" encodingStyle="uri-list"? namespace="uri"?/>* </soap:header> </input> And the definition for fault:: <soap:fault name="nmtoken" use="literal|encoded" encodingStyle="uri-list"? namespace="uri"?> """ name = xmlelement.get('name') obj = cls(definitions.wsdl, name, operation, nsmap=nsmap, type=type) body_data = None header_data = None # After some profiling it turns out that .find() and .findall() in this # case are twice as fast as the xpath method body = xmlelement.find('soap:body', namespaces=operation.binding.nsmap) if body is not None: body_data = cls._parse_body(body) # Parse soap:header (multiple) elements = xmlelement.findall( 'soap:header', namespaces=operation.binding.nsmap) header_data = cls._parse_header( elements, definitions.target_namespace, operation) obj._resolve_info = { 'body': body_data, 'header': header_data } return obj @classmethod def _parse_body(cls, xmlelement): """Parse soap:body and return a dict with data to resolve it. <soap:body parts="nmtokens"? use="literal|encoded"? encodingStyle="uri-list"? namespace="uri"?> """ return { 'part': xmlelement.get('part'), 'use': xmlelement.get('use', 'literal'), 'encodingStyle': xmlelement.get('encodingStyle'), 'namespace': xmlelement.get('namespace'), } @classmethod def _parse_header(cls, xmlelements, tns, operation): """Parse the soap:header and optionally included soap:headerfault elements <soap:header message="qname" part="nmtoken" use="literal|encoded" encodingStyle="uri-list"? namespace="uri"? />* The header can optionally contain one ore more soap:headerfault elements which can contain the same attributes as the soap:header:: <soap:headerfault message="qname" part="nmtoken" use="literal|encoded" encodingStyle="uri-list"? namespace="uri"?/>* """ result = [] for xmlelement in xmlelements: data = cls._parse_header_element(xmlelement, tns) # Add optional soap:headerfault elements data['faults'] = [] fault_elements = xmlelement.findall( 'soap:headerfault', namespaces=operation.binding.nsmap) for fault_element in fault_elements: fault_data = cls._parse_header_element(fault_element, tns) data['faults'].append(fault_data) result.append(data) return result @classmethod def _parse_header_element(cls, xmlelement, tns): attributes = xmlelement.attrib message_qname = as_qname( attributes['message'], xmlelement.nsmap, tns) try: return { 'message': message_qname, 'part': attributes['part'], 'use': attributes['use'], 'encodingStyle': attributes.get('encodingStyle'), 'namespace': attributes.get('namespace'), } except KeyError: raise exceptions.WsdlSyntaxError("Invalid soap:header(fault)") def resolve(self, definitions, abstract_message): """Resolve the data in the self._resolve_info dict (set via parse()) This creates three xsd.Element objects: - self.header - self.body - self.envelope (combination of headers and body) XXX headerfaults are not implemented yet. """ info = self._resolve_info del self._resolve_info # If this message has no parts then we have nothing to do. This might # happen for output messages which don't return anything. if not abstract_message.parts and self.type != 'input': return self.abstract = abstract_message parts = OrderedDict(self.abstract.parts) self.header = self._resolve_header(info['header'], definitions, parts) self.body = self._resolve_body(info['body'], definitions, parts) self.envelope = self._create_envelope_element() def _create_envelope_element(self): """Create combined `envelope` complexType which contains both the elements from the body and the headers. """ all_elements = xsd.Sequence([]) if self.header.type._element: all_elements.append( xsd.Element('{%s}header' % self.nsmap['soap-env'], self.header.type)) all_elements.append( xsd.Element('{%s}body' % self.nsmap['soap-env'], self.body.type)) return xsd.Element('{%s}envelope' % self.nsmap['soap-env'], xsd.ComplexType(all_elements)) def _serialize_header(self, headers_value, nsmap): if not headers_value: return headers_value = copy.deepcopy(headers_value) soap = ElementMaker(namespace=self.nsmap['soap-env'], nsmap=nsmap) header = soap.Header() if isinstance(headers_value, list): for header_value in headers_value: if hasattr(header_value, '_xsd_elm'): header_value._xsd_elm.render(header, header_value) elif hasattr(header_value, '_xsd_type'): header_value._xsd_type.render(header, header_value) elif isinstance(header_value, etree._Element): header.append(header_value) else: raise ValueError("Invalid value given to _soapheaders") elif isinstance(headers_value, dict): if not self.header: raise ValueError( "_soapheaders only accepts a dictionary if the wsdl " "defines the headers.") # Only render headers for which we have a value headers_value = self.header(**headers_value) for name, elm in self.header.type.elements: if name in headers_value and headers_value[name] is not None: elm.render(header, headers_value[name], ['header', name]) else: raise ValueError("Invalid value given to _soapheaders") return header def _deserialize_headers(self, xmlelement): """Deserialize the values in the SOAP:Header element""" if not self.header or xmlelement is None: return {} result = self.header.parse(xmlelement, self.wsdl.types) if result is not None: return {'header': result} return {} def _resolve_header(self, info, definitions, parts): name = etree.QName(self.nsmap['soap-env'], 'Header') container = xsd.All() if not info: return xsd.Element(name, xsd.ComplexType(container)) for item in info: message_name = item['message'].text part_name = item['part'] message = definitions.get('messages', message_name) if message == self.abstract: del parts[part_name] part = message.parts[part_name] if part.element: element = part.element.clone() element.attr_name = part_name else: element = xsd.Element(part_name, part.type) container.append(element) return xsd.Element(name, xsd.ComplexType(container)) class DocumentMessage(SoapMessage): """In the document message there are no additional wrappers, and the message parts appear directly under the SOAP Body element. .. inheritance-diagram:: zeep.wsdl.messages.soap.DocumentMessage :parts: 1 :param wsdl: The main wsdl document :type wsdl: zeep.wsdl.Document :param name: :param operation: The operation to which this message belongs :type operation: zeep.wsdl.bindings.soap.SoapOperation :param type: 'input' or 'output' :type type: str :param nsmap: The namespace mapping :type nsmap: dict """ def __init__(self, *args, **kwargs): super(DocumentMessage, self).__init__(*args, **kwargs) self._is_body_wrapped = False def _deserialize_body(self, xmlelement): if self._is_body_wrapped: result = self.body.parse(xmlelement, self.wsdl.types) else: # For now we assume that the body only has one child since only # one part is specified in the wsdl. This should be handled way # better # XXX xmlelement = xmlelement.getchildren()[0] result = self.body.parse(xmlelement, self.wsdl.types) return {'body': result} def _resolve_body(self, info, definitions, parts): name = etree.QName(self.nsmap['soap-env'], 'Body') if not info or not parts: return xsd.Element(name, xsd.ComplexType([])) # If the part name is omitted then all parts are available under # the soap:body tag. Otherwise only the part with the given name. if info['part']: part_name = info['part'] sub_elements = [parts[part_name].element] else: sub_elements = [] for part_name, part in parts.items(): element = part.element.clone() element.attr_name = part_name or element.name sub_elements.append(element) if len(sub_elements) > 1: self._is_body_wrapped = True return xsd.Element(name, xsd.ComplexType(xsd.All(sub_elements))) else: self._is_body_wrapped = False return sub_elements[0] class RpcMessage(SoapMessage): """In RPC messages each part is a parameter or a return value and appears inside a wrapper element within the body. The wrapper element is named identically to the operation name and its namespace is the value of the namespace attribute. Each message part (parameter) appears under the wrapper, represented by an accessor named identically to the corresponding parameter of the call. Parts are arranged in the same order as the parameters of the call. .. inheritance-diagram:: zeep.wsdl.messages.soap.DocumentMessage :parts: 1 :param wsdl: The main wsdl document :type wsdl: zeep.wsdl.Document :param name: :param operation: The operation to which this message belongs :type operation: zeep.wsdl.bindings.soap.SoapOperation :param type: 'input' or 'output' :type type: str :param nsmap: The namespace mapping :type nsmap: dict """ def _resolve_body(self, info, definitions, parts): """Return an XSD element for the SOAP:Body. Each part is a parameter or a return value and appears inside a wrapper element within the body named identically to the operation name and its namespace is the value of the namespace attribute. """ name = etree.QName(self.nsmap['soap-env'], 'Body') if not info: return xsd.Element(name, xsd.ComplexType([])) namespace = info['namespace'] if self.type == 'input': tag_name = etree.QName(namespace, self.operation.name) else: tag_name = etree.QName(namespace, self.abstract.name.localname) # Create the xsd element to create/parse the response. Each part # is a sub element of the root node (which uses the operation name) elements = [] for name, msg in parts.items(): if msg.element: elements.append(msg.element) else: elements.append(xsd.Element(name, msg.type)) return xsd.Element(tag_name, xsd.ComplexType(xsd.Sequence(elements))) def _deserialize_body(self, body_element): """The name of the wrapper element is not defined. The WS-I defines that it should be the operation name with the 'Response' string as suffix. But lets just do it really stupid for now and use the first element. """ response_element = body_element.getchildren()[0] if self.body: result = self.body.parse(response_element, self.wsdl.types) return {'body': result} return {'body': None}
zeep-adv
/zeep-adv-1.4.4.tar.gz/zeep-adv-1.4.4/src/zeep/wsdl/messages/soap.py
soap.py
from zeep import xsd from zeep.wsdl.messages.base import ConcreteMessage, SerializedMessage __all__ = [ 'UrlEncoded', 'UrlReplacement', ] class HttpMessage(ConcreteMessage): """Base class for HTTP Binding messages""" def resolve(self, definitions, abstract_message): self.abstract = abstract_message children = [] for name, message in self.abstract.parts.items(): if message.element: elm = message.element.clone(name) else: elm = xsd.Element(name, message.type) children.append(elm) self.body = xsd.Element( self.operation.name, xsd.ComplexType(xsd.Sequence(children))) class UrlEncoded(HttpMessage): """The urlEncoded element indicates that all the message parts are encoded into the HTTP request URI using the standard URI-encoding rules (name1=value&name2=value...). The names of the parameters correspond to the names of the message parts. Each value contributed by the part is encoded using a name=value pair. This may be used with GET to specify URL encoding, or with POST to specify a FORM-POST. For GET, the "?" character is automatically appended as necessary. """ def serialize(self, *args, **kwargs): params = {key: None for key in self.abstract.parts.keys()} params.update(zip(self.abstract.parts.keys(), args)) params.update(kwargs) headers = {'Content-Type': 'text/xml; charset=utf-8'} return SerializedMessage( path=self.operation.location, headers=headers, content=params) @classmethod def parse(cls, definitions, xmlelement, operation): name = xmlelement.get('name') obj = cls(definitions.wsdl, name, operation) return obj class UrlReplacement(HttpMessage): """The http:urlReplacement element indicates that all the message parts are encoded into the HTTP request URI using a replacement algorithm. - The relative URI value of http:operation is searched for a set of search patterns. - The search occurs before the value of the http:operation is combined with the value of the location attribute from http:address. - There is one search pattern for each message part. The search pattern string is the name of the message part surrounded with parenthesis "(" and ")". - For each match, the value of the corresponding message part is substituted for the match at the location of the match. - Matches are performed before any values are replaced (replaced values do not trigger additional matches). Message parts MUST NOT have repeating values. <http:urlReplacement/> """ def serialize(self, *args, **kwargs): params = {key: None for key in self.abstract.parts.keys()} params.update(zip(self.abstract.parts.keys(), args)) params.update(kwargs) headers = {'Content-Type': 'text/xml; charset=utf-8'} path = self.operation.location for key, value in params.items(): path = path.replace('(%s)' % key, value if value is not None else '') return SerializedMessage(path=path, headers=headers, content='') @classmethod def parse(cls, definitions, xmlelement, operation): name = xmlelement.get('name') obj = cls(definitions.wsdl, name, operation) return obj
zeep-adv
/zeep-adv-1.4.4.tar.gz/zeep-adv-1.4.4/src/zeep/wsdl/messages/http.py
http.py
import logging from lxml import etree from requests_toolbelt.multipart.decoder import MultipartDecoder from zeep import ns, plugins, wsa from zeep.exceptions import Fault, TransportError, XMLSyntaxError from zeep.loader import parse_xml from zeep.utils import as_qname, get_media_type, qname_attr from zeep.wsdl.attachments import MessagePack from zeep.wsdl.definitions import Binding, Operation from zeep.wsdl.messages import DocumentMessage, RpcMessage from zeep.wsdl.utils import etree_to_string, url_http_to_https logger = logging.getLogger(__name__) class SoapBinding(Binding): """Soap 1.1/1.2 binding""" def __init__(self, wsdl, name, port_name, transport, default_style): """The SoapBinding is the base class for the Soap11Binding and Soap12Binding. :param wsdl: :type wsdl: :param name: :type name: string :param port_name: :type port_name: string :param transport: :type transport: zeep.transports.Transport :param default_style: """ super(SoapBinding, self).__init__(wsdl, name, port_name) self.transport = transport self.default_style = default_style @classmethod def match(cls, node): """Check if this binding instance should be used to parse the given node. :param node: The node to match against :type node: lxml.etree._Element """ soap_node = node.find('soap:binding', namespaces=cls.nsmap) return soap_node is not None def create_message(self, operation, *args, **kwargs): envelope, http_headers = self._create(operation, args, kwargs) return envelope def _create(self, operation, args, kwargs, client=None, options=None): """Create the XML document to send to the server. Note that this generates the soap envelope without the wsse applied. """ operation_obj = self.get(operation) if not operation_obj: raise ValueError("Operation %r not found" % operation) # Create the SOAP envelope serialized = operation_obj.create(*args, **kwargs) self._set_http_headers(serialized, operation_obj) envelope = serialized.content http_headers = serialized.headers # Apply ws-addressing if client: if not options: options = client.service._binding_options if operation_obj.abstract.input_message.wsa_action: envelope, http_headers = wsa.WsAddressingPlugin().egress( envelope, http_headers, operation_obj, options) # Apply plugins envelope, http_headers = plugins.apply_egress( client, envelope, http_headers, operation_obj, options) # Apply WSSE if client.wsse: envelope, http_headers = client.wsse.apply(envelope, http_headers) return envelope, http_headers def send(self, client, options, operation, args, kwargs): """Called from the service :param client: The client with which the operation was called :type client: zeep.client.Client :param options: The binding options :type options: dict :param operation: The operation object from which this is a reply :type operation: zeep.wsdl.definitions.Operation :param args: The args to pass to the operation :type args: tuple :param kwargs: The kwargs to pass to the operation :type kwargs: dict """ envelope, http_headers = self._create( operation, args, kwargs, client=client, options=options) response = client.transport.post_xml( options['address'], envelope, http_headers) operation_obj = self.get(operation) # If the client wants to return the raw data then let's do that. if client.raw_response: return response return self.process_reply(client, operation_obj, response) def process_reply(self, client, operation, response): """Process the XML reply from the server. :param client: The client with which the operation was called :type client: zeep.client.Client :param operation: The operation object from which this is a reply :type operation: zeep.wsdl.definitions.Operation :param response: The response object returned by the remote server :type response: requests.Response """ if response.status_code != 200 and not response.content: raise TransportError( u'Server returned HTTP status %d (no content available)' % response.status_code) content_type = response.headers.get('Content-Type', 'text/xml') media_type = get_media_type(content_type) message_pack = None if media_type == 'multipart/related': decoder = MultipartDecoder( response.content, content_type, response.encoding or 'utf-8') content = decoder.parts[0].content if len(decoder.parts) > 1: message_pack = MessagePack(parts=decoder.parts[1:]) else: content = response.content try: doc = parse_xml(content, self.transport) except XMLSyntaxError: raise TransportError( u'Server returned HTTP status %d (%s)' % (response.status_code, response.content)) if client.wsse: client.wsse.verify(doc) doc, http_headers = plugins.apply_ingress( client, doc, response.headers, operation) # If the response code is not 200 or if there is a Fault node available # then assume that an error occured. fault_node = doc.find( 'soap-env:Body/soap-env:Fault', namespaces=self.nsmap) if response.status_code != 200 or fault_node is not None: return self.process_error(doc, operation) result = operation.process_reply(doc) if message_pack: message_pack._set_root(result) return message_pack return result def process_error(self, doc, operation): raise NotImplementedError def process_service_port(self, xmlelement, force_https=False): address_node = xmlelement.find('soap:address', namespaces=self.nsmap) # Force the usage of HTTPS when the force_https boolean is true location = address_node.get('location') if force_https and location: location = url_http_to_https(location) if location != address_node.get('location'): logger.warning("Forcing soap:address location to HTTPS") return { 'address': location } @classmethod def parse(cls, definitions, xmlelement): """ Definition:: <wsdl:binding name="nmtoken" type="qname"> * <-- extensibility element (1) --> * <wsdl:operation name="nmtoken"> * <-- extensibility element (2) --> * <wsdl:input name="nmtoken"? > ? <-- extensibility element (3) --> </wsdl:input> <wsdl:output name="nmtoken"? > ? <-- extensibility element (4) --> * </wsdl:output> <wsdl:fault name="nmtoken"> * <-- extensibility element (5) --> * </wsdl:fault> </wsdl:operation> </wsdl:binding> """ name = qname_attr(xmlelement, 'name', definitions.target_namespace) port_name = qname_attr(xmlelement, 'type', definitions.target_namespace) # The soap:binding element contains the transport method and # default style attribute for the operations. soap_node = xmlelement.find('soap:binding', namespaces=cls.nsmap) transport = soap_node.get('transport') supported_transports = [ 'http://schemas.xmlsoap.org/soap/http', 'http://www.w3.org/2003/05/soap/bindings/HTTP/', ] if transport not in supported_transports: raise NotImplementedError( "The binding transport %s is not supported (only soap/http)" % ( transport)) default_style = soap_node.get('style', 'document') obj = cls(definitions.wsdl, name, port_name, transport, default_style) for node in xmlelement.findall('wsdl:operation', namespaces=cls.nsmap): operation = SoapOperation.parse(definitions, node, obj, nsmap=cls.nsmap) obj._operation_add(operation) return obj class Soap11Binding(SoapBinding): nsmap = { 'soap': ns.SOAP_11, 'soap-env': ns.SOAP_ENV_11, 'wsdl': ns.WSDL, 'xsd': ns.XSD, } def process_error(self, doc, operation): fault_node = doc.find( 'soap-env:Body/soap-env:Fault', namespaces=self.nsmap) if fault_node is None: raise Fault( message='Unknown fault occured', code=None, actor=None, detail=etree_to_string(doc)) def get_text(name): child = fault_node.find(name) if child is not None: return child.text raise Fault( message=get_text('faultstring'), code=get_text('faultcode'), actor=get_text('faultactor'), detail=fault_node.find('detail')) def _set_http_headers(self, serialized, operation): serialized.headers['Content-Type'] = 'text/xml; charset=utf-8' class Soap12Binding(SoapBinding): nsmap = { 'soap': ns.SOAP_12, 'soap-env': ns.SOAP_ENV_12, 'wsdl': ns.WSDL, 'xsd': ns.XSD, } def process_error(self, doc, operation): fault_node = doc.find( 'soap-env:Body/soap-env:Fault', namespaces=self.nsmap) if fault_node is None: raise Fault( message='Unknown fault occured', code=None, actor=None, detail=etree_to_string(doc)) def get_text(name): child = fault_node.find(name) if child is not None: return child.text message = fault_node.findtext('soap-env:Reason/soap-env:Text', namespaces=self.nsmap) code = fault_node.findtext('soap-env:Code/soap-env:Value', namespaces=self.nsmap) # Extract the fault subcodes. These can be nested, as in subcodes can # also contain other subcodes. subcodes = [] subcode_element = fault_node.find('soap-env:Code/soap-env:Subcode', namespaces=self.nsmap) while subcode_element is not None: subcode_value_element = subcode_element.find('soap-env:Value', namespaces=self.nsmap) subcode_qname = as_qname(subcode_value_element.text, subcode_value_element.nsmap, None) subcodes.append(subcode_qname) subcode_element = subcode_element.find('soap-env:Subcode', namespaces=self.nsmap) # TODO: We should use the fault message as defined in the wsdl. detail_node = fault_node.find('soap-env:Detail', namespaces=self.nsmap) raise Fault( message=message, code=code, actor=None, detail=detail_node, subcodes=subcodes) def _set_http_headers(self, serialized, operation): serialized.headers['Content-Type'] = '; '.join([ 'application/soap+xml', 'charset=utf-8', 'action="%s"' % operation.soapaction ]) class SoapOperation(Operation): """Represent's an operation within a specific binding.""" def __init__(self, name, binding, nsmap, soapaction, style): super(SoapOperation, self).__init__(name, binding) self.nsmap = nsmap self.soapaction = soapaction self.style = style def process_reply(self, envelope): envelope_qname = etree.QName(self.nsmap['soap-env'], 'Envelope') if envelope.tag != envelope_qname: raise XMLSyntaxError(( "The XML returned by the server does not contain a valid " + "{%s}Envelope root element. The root element found is %s " ) % (envelope_qname.namespace, envelope.tag)) return self.output.deserialize(envelope) @classmethod def parse(cls, definitions, xmlelement, binding, nsmap): """ Definition:: <wsdl:operation name="nmtoken"> * <soap:operation soapAction="uri"? style="rpc|document"?>? <wsdl:input name="nmtoken"? > ? <soap:body use="literal"/> </wsdl:input> <wsdl:output name="nmtoken"? > ? <-- extensibility element (4) --> * </wsdl:output> <wsdl:fault name="nmtoken"> * <-- extensibility element (5) --> * </wsdl:fault> </wsdl:operation> Example:: <wsdl:operation name="GetLastTradePrice"> <soap:operation soapAction="http://example.com/GetLastTradePrice"/> <wsdl:input> <soap:body use="literal"/> </wsdl:input> <wsdl:output> </wsdl:output> <wsdl:fault name="dataFault"> <soap:fault name="dataFault" use="literal"/> </wsdl:fault> </operation> """ name = xmlelement.get('name') # The soap:operation element is required for soap/http bindings # and may be omitted for other bindings. soap_node = xmlelement.find('soap:operation', namespaces=binding.nsmap) action = None if soap_node is not None: action = soap_node.get('soapAction') style = soap_node.get('style', binding.default_style) else: style = binding.default_style obj = cls(name, binding, nsmap, action, style) if style == 'rpc': message_class = RpcMessage else: message_class = DocumentMessage for node in xmlelement.getchildren(): tag_name = etree.QName(node.tag).localname if tag_name not in ('input', 'output', 'fault'): continue msg = message_class.parse( definitions=definitions, xmlelement=node, operation=obj, nsmap=nsmap, type=tag_name) if tag_name == 'fault': obj.faults[msg.name] = msg else: setattr(obj, tag_name, msg) return obj def resolve(self, definitions): super(SoapOperation, self).resolve(definitions) for name, fault in self.faults.items(): if name in self.abstract.fault_messages: fault.resolve(definitions, self.abstract.fault_messages[name]) if self.output: self.output.resolve(definitions, self.abstract.output_message) if self.input: self.input.resolve(definitions, self.abstract.input_message)
zeep-adv
/zeep-adv-1.4.4.tar.gz/zeep-adv-1.4.4/src/zeep/wsdl/bindings/soap.py
soap.py
import logging import six from lxml import etree from zeep import ns from zeep.exceptions import Fault from zeep.utils import qname_attr from zeep.wsdl import messages from zeep.wsdl.definitions import Binding, Operation logger = logging.getLogger(__name__) NSMAP = { 'http': ns.HTTP, 'wsdl': ns.WSDL, 'mime': ns.MIME, } class HttpBinding(Binding): def create_message(self, operation, *args, **kwargs): if isinstance(operation, six.string_types): operation = self.get(operation) if not operation: raise ValueError("Operation not found") return operation.create(*args, **kwargs) def process_service_port(self, xmlelement, force_https=False): address_node = xmlelement.find('http:address', namespaces=NSMAP) if address_node is None: raise ValueError("No `http:address` node found") # Force the usage of HTTPS when the force_https boolean is true location = address_node.get('location') if force_https and location and location.startswith('http://'): logger.warning("Forcing http:address location to HTTPS") location = 'https://' + location[8:] return { 'address': location } @classmethod def parse(cls, definitions, xmlelement): name = qname_attr(xmlelement, 'name', definitions.target_namespace) port_name = qname_attr(xmlelement, 'type', definitions.target_namespace) obj = cls(definitions.wsdl, name, port_name) for node in xmlelement.findall('wsdl:operation', namespaces=NSMAP): operation = HttpOperation.parse(definitions, node, obj) obj._operation_add(operation) return obj def process_reply(self, client, operation, response): if response.status_code != 200: return self.process_error(response.content) raise NotImplementedError("No error handling yet!") return operation.process_reply(response.content) def process_error(self, doc): raise Fault(message=doc) class HttpPostBinding(HttpBinding): def send(self, client, options, operation, args, kwargs): """Called from the service""" operation_obj = self.get(operation) if not operation_obj: raise ValueError("Operation %r not found" % operation) serialized = operation_obj.create(*args, **kwargs) url = options['address'] + serialized.path response = client.transport.post( url, serialized.content, headers=serialized.headers) return self.process_reply(client, operation_obj, response) @classmethod def match(cls, node): """Check if this binding instance should be used to parse the given node. :param node: The node to match against :type node: lxml.etree._Element """ http_node = node.find(etree.QName(NSMAP['http'], 'binding')) return http_node is not None and http_node.get('verb') == 'POST' class HttpGetBinding(HttpBinding): def send(self, client, options, operation, args, kwargs): """Called from the service""" operation_obj = self.get(operation) if not operation_obj: raise ValueError("Operation %r not found" % operation) serialized = operation_obj.create(*args, **kwargs) url = options['address'] + serialized.path response = client.transport.get( url, serialized.content, headers=serialized.headers) return self.process_reply(client, operation_obj, response) @classmethod def match(cls, node): """Check if this binding instance should be used to parse the given node. :param node: The node to match against :type node: lxml.etree._Element """ http_node = node.find(etree.QName(ns.HTTP, 'binding')) return http_node is not None and http_node.get('verb') == 'GET' class HttpOperation(Operation): def __init__(self, name, binding, location): super(HttpOperation, self).__init__(name, binding) self.location = location def process_reply(self, envelope): return self.output.deserialize(envelope) @classmethod def parse(cls, definitions, xmlelement, binding): """ <wsdl:operation name="GetLastTradePrice"> <http:operation location="GetLastTradePrice"/> <wsdl:input> <mime:content type="application/x-www-form-urlencoded"/> </wsdl:input> <wsdl:output> <mime:mimeXml/> </wsdl:output> </wsdl:operation> """ name = xmlelement.get('name') http_operation = xmlelement.find('http:operation', namespaces=NSMAP) location = http_operation.get('location') obj = cls(name, binding, location) for node in xmlelement.getchildren(): tag_name = etree.QName(node.tag).localname if tag_name not in ('input', 'output'): continue # XXX Multiple mime types may be declared as alternatives message_node = None if len(node.getchildren()) > 0: message_node = node.getchildren()[0] message_class = None if message_node is not None: if message_node.tag == etree.QName(ns.HTTP, 'urlEncoded'): message_class = messages.UrlEncoded elif message_node.tag == etree.QName(ns.HTTP, 'urlReplacement'): message_class = messages.UrlReplacement elif message_node.tag == etree.QName(ns.MIME, 'content'): message_class = messages.MimeContent elif message_node.tag == etree.QName(ns.MIME, 'mimeXml'): message_class = messages.MimeXML if message_class: msg = message_class.parse(definitions, node, obj) assert msg setattr(obj, tag_name, msg) return obj def resolve(self, definitions): super(HttpOperation, self).resolve(definitions) if self.output: self.output.resolve(definitions, self.abstract.output_message) if self.input: self.input.resolve(definitions, self.abstract.input_message)
zeep-adv
/zeep-adv-1.4.4.tar.gz/zeep-adv-1.4.4/src/zeep/wsdl/bindings/http.py
http.py
import base64 import hashlib import os from zeep import ns from zeep.wsse import utils class UsernameToken(object): """UsernameToken Profile 1.1 https://docs.oasis-open.org/wss/v1.1/wss-v1.1-spec-os-UsernameTokenProfile.pdf Example response using PasswordText:: <wsse:Security> <wsse:UsernameToken> <wsse:Username>scott</wsse:Username> <wsse:Password Type="wsse:PasswordText">password</wsse:Password> </wsse:UsernameToken> </wsse:Security> Example using PasswordDigest:: <wsse:Security> <wsse:UsernameToken> <wsse:Username>NNK</wsse:Username> <wsse:Password Type="wsse:PasswordDigest"> weYI3nXd8LjMNVksCKFV8t3rgHh3Rw== </wsse:Password> <wsse:Nonce>WScqanjCEAC4mQoBE07sAQ==</wsse:Nonce> <wsu:Created>2003-07-16T01:24:32Z</wsu:Created> </wsse:UsernameToken> </wsse:Security> """ username_token_profile_ns = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0' # noqa soap_message_secutity_ns = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0' # noqa def __init__(self, username, password=None, password_digest=None, use_digest=False, nonce=None, created=None): self.username = username self.password = password self.password_digest = password_digest self.nonce = nonce self.created = created self.use_digest = use_digest def apply(self, envelope, headers): security = utils.get_security_header(envelope) # The token placeholder might already exists since it is specified in # the WSDL. token = security.find('{%s}UsernameToken' % ns.WSSE) if token is None: token = utils.WSSE.UsernameToken() security.append(token) # Create the sub elements of the UsernameToken element elements = [ utils.WSSE.Username(self.username) ] if self.password is not None or self.password_digest is not None: if self.use_digest: elements.extend(self._create_password_digest()) else: elements.extend(self._create_password_text()) token.extend(elements) return envelope, headers def verify(self, envelope): pass def _create_password_text(self): return [ utils.WSSE.Password( self.password, Type='%s#PasswordText' % self.username_token_profile_ns) ] def _create_password_digest(self): if self.nonce: nonce = self.nonce.encode('utf-8') else: nonce = os.urandom(16) timestamp = utils.get_timestamp(self.created) # digest = Base64 ( SHA-1 ( nonce + created + password ) ) if not self.password_digest: digest = base64.b64encode( hashlib.sha1( nonce + timestamp.encode('utf-8') + self.password.encode('utf-8') ).digest() ).decode('ascii') else: digest = self.password_digest return [ utils.WSSE.Password( digest, Type='%s#PasswordDigest' % self.username_token_profile_ns ), utils.WSSE.Nonce( base64.b64encode(nonce).decode('utf-8'), EncodingType='%s#Base64Binary' % self.soap_message_secutity_ns ), utils.WSU.Created(timestamp) ]
zeep-adv
/zeep-adv-1.4.4.tar.gz/zeep-adv-1.4.4/src/zeep/wsse/username.py
username.py
from lxml import etree from lxml.etree import QName try: import xmlsec except ImportError: xmlsec = None from zeep import ns from zeep.utils import detect_soap_env from zeep.exceptions import SignatureVerificationFailed from zeep.wsse.utils import ensure_id, get_security_header # SOAP envelope SOAP_NS = 'http://schemas.xmlsoap.org/soap/envelope/' class Signature(object): """Sign given SOAP envelope with WSSE sig using given key and cert.""" def __init__(self, key_file, certfile, password=None): check_xmlsec_import() self.key_file = key_file self.certfile = certfile self.password = password def apply(self, envelope, headers): sign_envelope(envelope, self.key_file, self.certfile, self.password) return envelope, headers def verify(self, envelope): verify_envelope(envelope, self.certfile) return envelope def check_xmlsec_import(): if xmlsec is None: raise ImportError( "The xmlsec module is required for wsse.Signature()\n" + "You can install xmlsec with: pip install xmlsec\n" + "or install zeep via: pip install zeep[xmlsec]\n" ) def sign_envelope(envelope, keyfile, certfile, password=None): """Sign given SOAP envelope with WSSE sig using given key and cert. Sign the wsu:Timestamp node in the wsse:Security header and the soap:Body; both must be present. Add a ds:Signature node in the wsse:Security header containing the signature. Use EXCL-C14N transforms to normalize the signed XML (so that irrelevant whitespace or attribute ordering changes don't invalidate the signature). Use SHA1 signatures. Expects to sign an incoming document something like this (xmlns attributes omitted for readability): <soap:Envelope> <soap:Header> <wsse:Security mustUnderstand="true"> <wsu:Timestamp> <wsu:Created>2015-06-25T21:53:25.246276+00:00</wsu:Created> <wsu:Expires>2015-06-25T21:58:25.246276+00:00</wsu:Expires> </wsu:Timestamp> </wsse:Security> </soap:Header> <soap:Body> ... </soap:Body> </soap:Envelope> After signing, the sample document would look something like this (note the added wsu:Id attr on the soap:Body and wsu:Timestamp nodes, and the added ds:Signature node in the header, with ds:Reference nodes with URI attribute referencing the wsu:Id of the signed nodes): <soap:Envelope> <soap:Header> <wsse:Security mustUnderstand="true"> <Signature xmlns="http://www.w3.org/2000/09/xmldsig#"> <SignedInfo> <CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/> <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/> <Reference URI="#id-d0f9fd77-f193-471f-8bab-ba9c5afa3e76"> <Transforms> <Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/> </Transforms> <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/> <DigestValue>nnjjqTKxwl1hT/2RUsBuszgjTbI=</DigestValue> </Reference> <Reference URI="#id-7c425ac1-534a-4478-b5fe-6cae0690f08d"> <Transforms> <Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/> </Transforms> <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/> <DigestValue>qAATZaSqAr9fta9ApbGrFWDuCCQ=</DigestValue> </Reference> </SignedInfo> <SignatureValue>Hz8jtQb...bOdT6ZdTQ==</SignatureValue> <KeyInfo> <wsse:SecurityTokenReference> <X509Data> <X509Certificate>MIIDnzC...Ia2qKQ==</X509Certificate> <X509IssuerSerial> <X509IssuerName>...</X509IssuerName> <X509SerialNumber>...</X509SerialNumber> </X509IssuerSerial> </X509Data> </wsse:SecurityTokenReference> </KeyInfo> </Signature> <wsu:Timestamp wsu:Id="id-7c425ac1-534a-4478-b5fe-6cae0690f08d"> <wsu:Created>2015-06-25T22:00:29.821700+00:00</wsu:Created> <wsu:Expires>2015-06-25T22:05:29.821700+00:00</wsu:Expires> </wsu:Timestamp> </wsse:Security> </soap:Header> <soap:Body wsu:Id="id-d0f9fd77-f193-471f-8bab-ba9c5afa3e76"> ... </soap:Body> </soap:Envelope> """ # Create the Signature node. signature = xmlsec.template.create( envelope, xmlsec.Transform.EXCL_C14N, xmlsec.Transform.RSA_SHA1, ) # Add a KeyInfo node with X509Data child to the Signature. XMLSec will fill # in this template with the actual certificate details when it signs. key_info = xmlsec.template.ensure_key_info(signature) x509_data = xmlsec.template.add_x509_data(key_info) xmlsec.template.x509_data_add_issuer_serial(x509_data) xmlsec.template.x509_data_add_certificate(x509_data) # Load the signing key and certificate. key = xmlsec.Key.from_file(keyfile, xmlsec.KeyFormat.PEM, password=password) key.load_cert_from_file(certfile, xmlsec.KeyFormat.PEM) # Insert the Signature node in the wsse:Security header. security = get_security_header(envelope) security.insert(0, signature) # Perform the actual signing. ctx = xmlsec.SignatureContext() ctx.key = key security.append(etree.Element(QName(ns.WSU, 'Timestamp'))) soap_env = detect_soap_env(envelope) _sign_node(ctx, signature, envelope.find(QName(soap_env, 'Body'))) _sign_node(ctx, signature, security.find(QName(ns.WSU, 'Timestamp'))) ctx.sign(signature) # Place the X509 data inside a WSSE SecurityTokenReference within # KeyInfo. The recipient expects this structure, but we can't rearrange # like this until after signing, because otherwise xmlsec won't populate # the X509 data (because it doesn't understand WSSE). sec_token_ref = etree.SubElement( key_info, QName(ns.WSSE, 'SecurityTokenReference')) sec_token_ref.append(x509_data) def verify_envelope(envelope, certfile): """Verify WS-Security signature on given SOAP envelope with given cert. Expects a document like that found in the sample XML in the ``sign()`` docstring. Raise SignatureValidationFailed on failure, silent on success. """ soap_env = detect_soap_env(envelope) header = envelope.find(QName(soap_env, 'Header')) security = header.find(QName(ns.WSSE, 'Security')) signature = security.find(QName(ns.DS, 'Signature')) ctx = xmlsec.SignatureContext() # Find each signed element and register its ID with the signing context. refs = signature.xpath( 'ds:SignedInfo/ds:Reference', namespaces={'ds': ns.DS}) for ref in refs: # Get the reference URI and cut off the initial '#' referenced_id = ref.get('URI')[1:] referenced = envelope.xpath( "//*[@wsu:Id='%s']" % referenced_id, namespaces={'wsu': ns.WSU}, )[0] ctx.register_id(referenced, 'Id', ns.WSU) key = xmlsec.Key.from_file(certfile, xmlsec.KeyFormat.CERT_PEM, None) ctx.key = key try: ctx.verify(signature) except xmlsec.Error: # Sadly xmlsec gives us no details about the reason for the failure, so # we have nothing to pass on except that verification failed. raise SignatureVerificationFailed() def _sign_node(ctx, signature, target): """Add sig for ``target`` in ``signature`` node, using ``ctx`` context. Doesn't actually perform the signing; ``ctx.sign(signature)`` should be called later to do that. Adds a Reference node to the signature with URI attribute pointing to the target node, and registers the target node's ID so XMLSec will be able to find the target node by ID when it signs. """ # Ensure the target node has a wsu:Id attribute and get its value. node_id = ensure_id(target) # Unlike HTML, XML doesn't have a single standardized Id. WSSE suggests the # use of the wsu:Id attribute for this purpose, but XMLSec doesn't # understand that natively. So for XMLSec to be able to find the referenced # node by id, we have to tell xmlsec about it using the register_id method. ctx.register_id(target, 'Id', ns.WSU) # Add reference to signature with URI attribute pointing to that ID. ref = xmlsec.template.add_reference( signature, xmlsec.Transform.SHA1, uri='#' + node_id) # This is an XML normalization transform which will be performed on the # target node contents before signing. This ensures that changes to # irrelevant whitespace, attribute ordering, etc won't invalidate the # signature. xmlsec.template.add_transform(ref, xmlsec.Transform.EXCL_C14N)
zeep-adv
/zeep-adv-1.4.4.tar.gz/zeep-adv-1.4.4/src/zeep/wsse/signature.py
signature.py
import asyncio import logging import aiohttp from requests import Response from zeep.transports import Transport from zeep.utils import get_version from zeep.wsdl.utils import etree_to_string __all__ = ['AsyncTransport'] class AsyncTransport(Transport): """Asynchronous Transport class using aiohttp.""" supports_async = True def __init__(self, loop, cache=None, timeout=300, operation_timeout=None, session=None): self.loop = loop if loop else asyncio.get_event_loop() self.cache = cache self.load_timeout = timeout self.operation_timeout = operation_timeout self.logger = logging.getLogger(__name__) self.session = session or aiohttp.ClientSession(loop=self.loop) self._close_session = session is None self.session._default_headers['User-Agent'] = ( 'Zeep/%s (www.python-zeep.org)' % (get_version())) def __del__(self): if self._close_session: self.session.close() def _load_remote_data(self, url): result = None async def _load_remote_data_async(): nonlocal result with aiohttp.Timeout(self.load_timeout): response = await self.session.get(url) result = await response.read() # Block until we have the data self.loop.run_until_complete(_load_remote_data_async()) return result async def post(self, address, message, headers): self.logger.debug("HTTP Post to %s:\n%s", address, message) with aiohttp.Timeout(self.operation_timeout): response = await self.session.post( address, data=message, headers=headers) self.logger.debug( "HTTP Response from %s (status: %d):\n%s", address, response.status, await response.read()) return response async def post_xml(self, address, envelope, headers): message = etree_to_string(envelope) response = await self.post(address, message, headers) return await self.new_response(response) async def get(self, address, params, headers): with aiohttp.Timeout(self.operation_timeout): response = await self.session.get( address, params=params, headers=headers) return await self.new_response(response) async def new_response(self, response): """Convert an aiohttp.Response object to a requests.Response object""" new = Response() new._content = await response.read() new.status_code = response.status new.headers = response.headers new.cookies = response.cookies new.encoding = response.charset return new
zeep-adv
/zeep-adv-1.4.4.tar.gz/zeep-adv-1.4.4/src/zeep/asyncio/transport.py
transport.py
import logging from collections import OrderedDict from lxml import etree from zeep import exceptions from zeep import ns from zeep.xsd.elements import builtins as xsd_builtins_elements from zeep.xsd.types import builtins as xsd_builtins_types from zeep.xsd.visitor import SchemaVisitor logger = logging.getLogger(__name__) class Schema(object): """A schema is a collection of schema documents.""" def __init__(self, node=None, transport=None, location=None, strict=True): """ :param node: :param transport: :param location: :param strict: Boolean to indicate if the parsing is strict (default) """ self.strict = strict self._transport = transport self._documents = OrderedDict() self._prefix_map_auto = {} self._prefix_map_custom = {} self._load_default_documents() if not isinstance(node, list): nodes = [node] if node is not None else [] else: nodes = node self.add_documents(nodes, location) @property def documents(self): for documents in self._documents.values(): for document in documents: yield document @property def prefix_map(self): retval = {} retval.update(self._prefix_map_custom) retval.update({ k: v for k, v in self._prefix_map_auto.items() if v not in retval.values() }) return retval @property def root_document(self): return next( (doc for doc in self.documents if not doc._is_internal), None) @property def is_empty(self): """Boolean to indicate if this schema contains any types or elements""" return all(document.is_empty for document in self.documents) @property def namespaces(self): return set(self._documents.keys()) @property def elements(self): """Yield all globla xsd.Type objects :rtype: Iterable of zeep.xsd.Element """ seen = set() for document in self.documents: for element in document._elements.values(): if element.qname not in seen: yield element seen.add(element.qname) @property def types(self): """Yield all global xsd.Type objects :rtype: Iterable of zeep.xsd.ComplexType """ seen = set() for document in self.documents: for type_ in document._types.values(): if type_.qname not in seen: yield type_ seen.add(type_.qname) def __repr__(self): main_doc = self.root_document if main_doc: return '<Schema(location=%r, tns=%r)>' % ( main_doc._location, main_doc._target_namespace) return '<Schema()>' def add_documents(self, schema_nodes, location): documents = [] for node in schema_nodes: document = self.create_new_document(node, location) documents.append(document) for document in documents: document.resolve() self._prefix_map_auto = self._create_prefix_map() def get_element(self, qname): """Return a global xsd.Element object with the given qname :rtype: zeep.xsd.Group """ qname = self._create_qname(qname) return self._get_instance(qname, 'get_element', 'element') def get_type(self, qname, fail_silently=False): """Return a global xsd.Type object with the given qname :rtype: zeep.xsd.ComplexType or zeep.xsd.AnySimpleType """ qname = self._create_qname(qname) try: return self._get_instance(qname, 'get_type', 'type') except exceptions.NamespaceError as exc: if fail_silently: logger.debug(str(exc)) else: raise def get_group(self, qname): """Return a global xsd.Group object with the given qname. :rtype: zeep.xsd.Group """ return self._get_instance(qname, 'get_group', 'group') def get_attribute(self, qname): """Return a global xsd.attributeGroup object with the given qname :rtype: zeep.xsd.Attribute """ return self._get_instance(qname, 'get_attribute', 'attribute') def get_attribute_group(self, qname): """Return a global xsd.attributeGroup object with the given qname :rtype: zeep.xsd.AttributeGroup """ return self._get_instance(qname, 'get_attribute_group', 'attributeGroup') def set_ns_prefix(self, prefix, namespace): self._prefix_map_custom[prefix] = namespace def get_ns_prefix(self, prefix): try: try: return self._prefix_map_custom[prefix] except KeyError: return self._prefix_map_auto[prefix] except KeyError: raise ValueError("No such prefix %r" % prefix) def get_shorthand_for_ns(self, namespace): for prefix, other_namespace in self._prefix_map_auto.items(): if namespace == other_namespace: return prefix for prefix, other_namespace in self._prefix_map_custom.items(): if namespace == other_namespace: return prefix if namespace == 'http://schemas.xmlsoap.org/soap/envelope/': return 'soap-env' return namespace def create_new_document(self, node, url, base_url=None): namespace = node.get('targetNamespace') if node is not None else None if base_url is None: base_url = url schema = SchemaDocument(namespace, url, base_url) self._add_schema_document(schema) schema.load(self, node) return schema def merge(self, schema): """Merge an other XSD schema in this one""" for document in schema.documents: self._add_schema_document(document) self._prefix_map_auto = self._create_prefix_map() def _load_default_documents(self): schema = SchemaDocument(ns.XSD, None, None) for cls in xsd_builtins_types._types: instance = cls(is_global=True) schema.register_type(cls._default_qname, instance) for cls in xsd_builtins_elements._elements: instance = cls() schema.register_element(cls.qname, instance) schema._is_internal = True self._add_schema_document(schema) return schema def _get_instance(self, qname, method_name, name): """Return an object from one of the SchemaDocument's""" qname = self._create_qname(qname) try: last_exception = None for schema in self._get_schema_documents(qname.namespace): method = getattr(schema, method_name) try: return method(qname) except exceptions.LookupError as exc: last_exception = exc continue raise last_exception except exceptions.NamespaceError: raise exceptions.NamespaceError(( "Unable to resolve %s %s. " + "No schema available for the namespace %r." ) % (name, qname.text, qname.namespace)) def _create_qname(self, name): """Create an `lxml.etree.QName()` object for the given qname string. This also expands the shorthand notation. :rtype: lxml.etree.QNaame """ if isinstance(name, etree.QName): return name if not name.startswith('{') and ':' in name and self._prefix_map_auto: prefix, localname = name.split(':', 1) if prefix in self._prefix_map_custom: return etree.QName(self._prefix_map_custom[prefix], localname) elif prefix in self._prefix_map_auto: return etree.QName(self._prefix_map_auto[prefix], localname) else: raise ValueError( "No namespace defined for the prefix %r" % prefix) else: return etree.QName(name) def _create_prefix_map(self): prefix_map = { 'xsd': 'http://www.w3.org/2001/XMLSchema', } i = 0 for namespace in self._documents.keys(): if namespace is None or namespace in prefix_map.values(): continue prefix_map['ns%d' % i] = namespace i += 1 return prefix_map def _has_schema_document(self, namespace): """Return a boolean if there is a SchemaDocumnet for the namespace. :rtype: boolean """ return namespace in self._documents def _add_schema_document(self, document): logger.debug("Add document with tns %s to schema %s", document.namespace, id(self)) documents = self._documents.setdefault(document.namespace, []) documents.append(document) def _get_schema_document(self, namespace, location): """Return a list of SchemaDocument's for the given namespace AND location. :rtype: SchemaDocument """ for document in self._documents.get(namespace, []): if document._location == location: return document def _get_schema_documents(self, namespace, fail_silently=False): """Return a list of SchemaDocument's for the given namespace. :rtype: list of SchemaDocument """ if namespace not in self._documents: if fail_silently: return [] raise exceptions.NamespaceError( "No schema available for the namespace %r" % namespace) return self._documents[namespace] class SchemaDocument(object): def __init__(self, namespace, location, base_url): logger.debug("Init schema document for %r", location) # Internal self._base_url = base_url or location self._location = location self._target_namespace = namespace self._is_internal = False self._attribute_groups = {} self._attributes = {} self._elements = {} self._groups = {} self._types = {} self._imports = OrderedDict() self._element_form = 'unqualified' self._attribute_form = 'unqualified' self._resolved = False # self._xml_schema = None def __repr__(self): return '<SchemaDocument(location=%r, tns=%r, is_empty=%r)>' % ( self._location, self._target_namespace, self.is_empty) @property def namespace(self): return self._target_namespace @property def is_empty(self): return not bool(self._imports or self._types or self._elements) def load(self, schema, node): if node is None: return if not schema._has_schema_document(self._target_namespace): raise RuntimeError( "The document needs to be registered in the schema before " + "it can be loaded") # Disable XML schema validation for now # if len(node) > 0: # self.xml_schema = etree.XMLSchema(node) visitor = SchemaVisitor(schema, self) visitor.visit_schema(node) def resolve(self): logger.debug("Resolving in schema %s", self) if self._resolved: return self._resolved = True for schemas in self._imports.values(): for schema in schemas: schema.resolve() def _resolve_dict(val): try: for key, obj in val.items(): new = obj.resolve() assert new is not None, "resolve() should return an object" val[key] = new except exceptions.LookupError as exc: raise exceptions.LookupError( ( "Unable to resolve %(item_name)s %(qname)s in " "%(file)s. (via %(parent)s)" ) % { 'item_name': exc.item_name, 'item_name': exc.item_name, 'qname': exc.qname, 'file': exc.location, 'parent': obj.qname, }) _resolve_dict(self._attribute_groups) _resolve_dict(self._attributes) _resolve_dict(self._elements) _resolve_dict(self._groups) _resolve_dict(self._types) def register_import(self, namespace, schema): schemas = self._imports.setdefault(namespace, []) schemas.append(schema) def is_imported(self, namespace): return namespace in self._imports def register_type(self, name, value): assert not isinstance(value, type) assert value is not None if isinstance(name, etree.QName): name = name.text logger.debug("register_type(%r, %r)", name, value) self._types[name] = value def register_element(self, name, value): if isinstance(name, etree.QName): name = name.text logger.debug("register_element(%r, %r)", name, value) self._elements[name] = value def register_group(self, name, value): if isinstance(name, etree.QName): name = name.text logger.debug("register_group(%r, %r)", name, value) self._groups[name] = value def register_attribute(self, name, value): if isinstance(name, etree.QName): name = name.text logger.debug("register_attribute(%r, %r)", name, value) self._attributes[name] = value def register_attribute_group(self, name, value): if isinstance(name, etree.QName): name = name.text logger.debug("register_attribute_group(%r, %r)", name, value) self._attribute_groups[name] = value def get_type(self, qname): """Return a xsd.Type object from this schema :rtype: zeep.xsd.ComplexType or zeep.xsd.AnySimpleType """ return self._get_instance(qname, self._types, 'type') def get_element(self, qname): """Return a xsd.Element object from this schema :rtype: zeep.xsd.Element """ return self._get_instance(qname, self._elements, 'element') def get_group(self, qname): """Return a xsd.Group object from this schema. :rtype: zeep.xsd.Group """ return self._get_instance(qname, self._groups, 'group') def get_attribute(self, qname): """Return a xsd.Attribute object from this schema :rtype: zeep.xsd.Attribute """ return self._get_instance(qname, self._attributes, 'attribute') def get_attribute_group(self, qname): """Return a xsd.AttributeGroup object from this schema :rtype: zeep.xsd.AttributeGroup """ return self._get_instance(qname, self._attribute_groups, 'attributeGroup') def _get_instance(self, qname, items, item_name): try: return items[qname] except KeyError: known_items = ', '.join(items.keys()) raise exceptions.LookupError(( "No %(item_name)s '%(localname)s' in namespace %(namespace)s. " + "Available %(item_name_plural)s are: %(known_items)s" ) % { 'item_name': item_name, 'item_name_plural': item_name + 's', 'localname': qname.localname, 'namespace': qname.namespace, 'known_items': known_items or ' - ' }, qname=qname, item_name=item_name, location=self._location)
zeep-adv
/zeep-adv-1.4.4.tar.gz/zeep-adv-1.4.4/src/zeep/xsd/schema.py
schema.py
from collections import OrderedDict from six import StringIO class PrettyPrinter(object): """Cleaner pprint output. Heavily inspired by the Python pprint module, but more basic for now. """ def pformat(self, obj): stream = StringIO() self._format(obj, stream) return stream.getvalue() def _format(self, obj, stream, indent=4, level=1): _repr = getattr(type(obj), '__repr__', None) write = stream.write if ( (isinstance(obj, dict) and _repr is dict.__repr__) or (isinstance(obj, OrderedDict) and _repr == OrderedDict.__repr__) ): write('{\n') num = len(obj) if num > 0: for i, (key, value) in enumerate(obj.items()): write(' ' * (indent * level)) write("'%s'" % key) write(': ') self._format(value, stream, level=level + 1) if i < num - 1: write(',') write('\n') write(' ' * (indent * (level - 1))) write('}') elif isinstance(obj, list) and _repr is list.__repr__: write('[') num = len(obj) if num > 0: write('\n') for i, value in enumerate(obj): write(' ' * (indent * level)) self._format(value, stream, level=level + 1) if i < num - 1: write(',') write('\n') write(' ' * (indent * (level - 1))) write(']') else: value = repr(obj) if '\n' in value: lines = value.split('\n') num = len(lines) for i, line in enumerate(lines): if i > 0: write(' ' * (indent * (level - 1))) write(line) if i < num - 1: write('\n') else: write(value)
zeep-adv
/zeep-adv-1.4.4.tar.gz/zeep-adv-1.4.4/src/zeep/xsd/printer.py
printer.py
import keyword import logging import re from lxml import etree from zeep.exceptions import XMLParseError from zeep.loader import absolute_location, load_external from zeep.utils import as_qname, qname_attr from zeep.xsd import elements as xsd_elements from zeep.xsd import types as xsd_types from zeep.xsd.const import xsd_ns logger = logging.getLogger(__name__) class tags(object): pass for name in [ 'schema', 'import', 'include', 'annotation', 'element', 'simpleType', 'complexType', 'simpleContent', 'complexContent', 'sequence', 'group', 'choice', 'all', 'list', 'union', 'attribute', 'any', 'anyAttribute', 'attributeGroup', 'restriction', 'extension', 'notation', ]: attr = name if name not in keyword.kwlist else name + '_' setattr(tags, attr, xsd_ns(name)) class SchemaVisitor(object): """Visitor which processes XSD files and registers global elements and types in the given schema. :param schema: :type schema: zeep.xsd.schema.Schema :param document: :type document: zeep.xsd.schema.SchemaDocument """ def __init__(self, schema, document): self.document = document self.schema = schema self._includes = set() def register_element(self, qname, instance): self.document.register_element(qname, instance) def register_attribute(self, name, instance): self.document.register_attribute(name, instance) def register_type(self, qname, instance): self.document.register_type(qname, instance) def register_group(self, qname, instance): self.document.register_group(qname, instance) def register_attribute_group(self, qname, instance): self.document.register_attribute_group(qname, instance) def register_import(self, namespace, document): self.document.register_import(namespace, document) def process(self, node, parent): visit_func = self.visitors.get(node.tag) if not visit_func: raise ValueError("No visitor defined for %r" % node.tag) result = visit_func(self, node, parent) return result def process_ref_attribute(self, node, array_type=None): ref = qname_attr(node, 'ref') if ref: ref = self._create_qname(ref) # Some wsdl's reference to xs:schema, we ignore that for now. It # might be better in the future to process the actual schema file # so that it is handled correctly if ref.namespace == 'http://www.w3.org/2001/XMLSchema': return return xsd_elements.RefAttribute( node.tag, ref, self.schema, array_type=array_type) def process_reference(self, node, **kwargs): ref = qname_attr(node, 'ref') if not ref: return if node.tag == tags.element: cls = xsd_elements.RefElement elif node.tag == tags.attribute: cls = xsd_elements.RefAttribute elif node.tag == tags.group: cls = xsd_elements.RefGroup elif node.tag == tags.attributeGroup: cls = xsd_elements.RefAttributeGroup return cls(node.tag, ref, self.schema, **kwargs) def visit_schema(self, node): """Visit the xsd:schema element and process all the child elements Definition:: <schema attributeFormDefault = (qualified | unqualified): unqualified blockDefault = (#all | List of (extension | restriction | substitution) : '' elementFormDefault = (qualified | unqualified): unqualified finalDefault = (#all | List of (extension | restriction | list | union): '' id = ID targetNamespace = anyURI version = token xml:lang = language {any attributes with non-schema Namespace}...> Content: ( (include | import | redefine | annotation)*, (((simpleType | complexType | group | attributeGroup) | element | attribute | notation), annotation*)*) </schema> :param node: The XML node :type node: lxml.etree._Element """ assert node is not None self.document._target_namespace = node.get('targetNamespace') self.document._element_form = node.get('elementFormDefault', 'unqualified') self.document._attribute_form = node.get('attributeFormDefault', 'unqualified') for child in node: self.process(child, parent=node) def visit_import(self, node, parent): """ Definition:: <import id = ID namespace = anyURI schemaLocation = anyURI {any attributes with non-schema Namespace}...> Content: (annotation?) </import> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ schema_node = None namespace = node.get('namespace') location = node.get('schemaLocation') if location: location = absolute_location(location, self.document._base_url) if not namespace and not self.document._target_namespace: raise XMLParseError( "The attribute 'namespace' must be existent if the " "importing schema has no target namespace.", filename=self._document.location, sourceline=node.sourceline) # Check if the schema is already imported before based on the # namespace. Schema's without namespace are registered as 'None' document = self.schema._get_schema_document(namespace, location) if document: logger.debug("Returning existing schema: %r", location) self.register_import(namespace, document) return document # Hardcode the mapping between the xml namespace and the xsd for now. # This seems to fix issues with exchange wsdl's, see #220 if not location and namespace == 'http://www.w3.org/XML/1998/namespace': location = 'https://www.w3.org/2001/xml.xsd' # Silently ignore import statements which we can't resolve via the # namespace and doesn't have a schemaLocation attribute. if not location: logger.debug( "Ignoring import statement for namespace %r " + "(missing schemaLocation)", namespace) return # Load the XML schema_node = load_external( location, self.schema._transport, strict=self.schema.strict) # Check if the xsd:import namespace matches the targetNamespace. If # the xsd:import statement didn't specify a namespace then make sure # that the targetNamespace wasn't declared by another schema yet. schema_tns = schema_node.get('targetNamespace') if namespace and schema_tns and namespace != schema_tns: raise XMLParseError(( "The namespace defined on the xsd:import doesn't match the " "imported targetNamespace located at %r " ) % (location), filename=self.document._location, sourceline=node.sourceline) schema = self.schema.create_new_document(schema_node, location) self.register_import(namespace, schema) return schema def visit_include(self, node, parent): """ Definition:: <include id = ID schemaLocation = anyURI {any attributes with non-schema Namespace}...> Content: (annotation?) </include> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ if not node.get('schemaLocation'): raise NotImplementedError("schemaLocation is required") location = node.get('schemaLocation') if location in self._includes: return schema_node = load_external( location, self.schema._transport, base_url=self.document._base_url, strict=self.schema.strict) self._includes.add(location) # When the included document has no default namespace defined but the # parent document does have this then we should (atleast for #360) # transfer the default namespace to the included schema. We can't # update the nsmap of elements in lxml so we create a new schema with # the correct nsmap and move all the content there. if not schema_node.nsmap.get(None) and node.nsmap.get(None): nsmap = {None: node.nsmap[None]} nsmap.update(schema_node.nsmap) new = etree.Element(schema_node.tag, nsmap=nsmap) for child in schema_node: new.append(child) schema_node = new # Iterate directly over the children for child in schema_node: self.process(child, parent=schema_node) def visit_element(self, node, parent): """ Definition:: <element abstract = Boolean : false block = (#all | List of (extension | restriction | substitution)) default = string final = (#all | List of (extension | restriction)) fixed = string form = (qualified | unqualified) id = ID maxOccurs = (nonNegativeInteger | unbounded) : 1 minOccurs = nonNegativeInteger : 1 name = NCName nillable = Boolean : false ref = QName substitutionGroup = QName type = QName {any attributes with non-schema Namespace}...> Content: (annotation?, ( (simpleType | complexType)?, (unique | key | keyref)*)) </element> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ is_global = parent.tag == tags.schema # minOccurs / maxOccurs are not allowed on global elements if not is_global: min_occurs, max_occurs = _process_occurs_attrs(node) else: max_occurs = 1 min_occurs = 1 # If the element has a ref attribute then all other attributes cannot # be present. Short circuit that here. # Ref is prohibited on global elements (parent = schema) if not is_global: result = self.process_reference( node, min_occurs=min_occurs, max_occurs=max_occurs) if result: return result element_form = node.get('form', self.document._element_form) if element_form == 'qualified' or is_global: qname = qname_attr(node, 'name', self.document._target_namespace) else: qname = etree.QName(node.get('name')) children = node.getchildren() xsd_type = None if children: value = None for child in children: if child.tag == tags.annotation: continue elif child.tag in (tags.simpleType, tags.complexType): assert not value xsd_type = self.process(child, node) if not xsd_type: node_type = qname_attr(node, 'type') if node_type: xsd_type = self._get_type(node_type.text) else: xsd_type = xsd_types.AnyType() # Naive workaround to mark fields which are part of a choice element # as optional if parent.tag == tags.choice: min_occurs = 0 nillable = node.get('nillable') == 'true' default = node.get('default') element = xsd_elements.Element( name=qname, type_=xsd_type, min_occurs=min_occurs, max_occurs=max_occurs, nillable=nillable, default=default, is_global=is_global) # Only register global elements if is_global: self.register_element(qname, element) return element def visit_attribute(self, node, parent): """Declares an attribute. Definition:: <attribute default = string fixed = string form = (qualified | unqualified) id = ID name = NCName ref = QName type = QName use = (optional | prohibited | required): optional {any attributes with non-schema Namespace...}> Content: (annotation?, (simpleType?)) </attribute> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ is_global = parent.tag == tags.schema # Check of wsdl:arayType array_type = node.get('{http://schemas.xmlsoap.org/wsdl/}arrayType') if array_type: match = re.match('([^\[]+)', array_type) if match: array_type = match.groups()[0] qname = as_qname(array_type, node.nsmap) array_type = xsd_types.UnresolvedType(qname, self.schema) # If the elment has a ref attribute then all other attributes cannot # be present. Short circuit that here. # Ref is prohibited on global elements (parent = schema) if not is_global: result = self.process_ref_attribute(node, array_type=array_type) if result: return result attribute_form = node.get('form', self.document._attribute_form) if attribute_form == 'qualified' or is_global: name = qname_attr(node, 'name', self.document._target_namespace) else: name = etree.QName(node.get('name')) annotation, items = self._pop_annotation(node.getchildren()) if items: xsd_type = self.visit_simple_type(items[0], node) else: node_type = qname_attr(node, 'type') if node_type: xsd_type = self._get_type(node_type) else: xsd_type = xsd_types.AnyType() # TODO: We ignore 'prohobited' for now required = node.get('use') == 'required' default = node.get('default') attr = xsd_elements.Attribute( name, type_=xsd_type, default=default, required=required) # Only register global elements if is_global: self.register_attribute(name, attr) return attr def visit_simple_type(self, node, parent): """ Definition:: <simpleType final = (#all | (list | union | restriction)) id = ID name = NCName {any attributes with non-schema Namespace}...> Content: (annotation?, (restriction | list | union)) </simpleType> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ if parent.tag == tags.schema: name = node.get('name') is_global = True else: name = parent.get('name', 'Anonymous') is_global = False base_type = '{http://www.w3.org/2001/XMLSchema}string' qname = as_qname(name, node.nsmap, self.document._target_namespace) annotation, items = self._pop_annotation(node.getchildren()) child = items[0] if child.tag == tags.restriction: base_type = self.visit_restriction_simple_type(child, node) xsd_type = xsd_types.UnresolvedCustomType( qname, base_type, self.schema) elif child.tag == tags.list: xsd_type = self.visit_list(child, node) elif child.tag == tags.union: xsd_type = self.visit_union(child, node) else: raise AssertionError("Unexpected child: %r" % child.tag) assert xsd_type is not None if is_global: self.register_type(qname, xsd_type) return xsd_type def visit_complex_type(self, node, parent): """ Definition:: <complexType abstract = Boolean : false block = (#all | List of (extension | restriction)) final = (#all | List of (extension | restriction)) id = ID mixed = Boolean : false name = NCName {any attributes with non-schema Namespace...}> Content: (annotation?, (simpleContent | complexContent | ((group | all | choice | sequence)?, ((attribute | attributeGroup)*, anyAttribute?)))) </complexType> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ children = [] base_type = '{http://www.w3.org/2001/XMLSchema}anyType' # If the complexType's parent is an element then this type is # anonymous and should have no name defined. Otherwise it's global if parent.tag == tags.schema: name = node.get('name') is_global = True else: name = parent.get('name') is_global = False qname = as_qname(name, node.nsmap, self.document._target_namespace) cls_attributes = { '__module__': 'zeep.xsd.dynamic_types', '_xsd_name': qname, } xsd_cls = type(name, (xsd_types.ComplexType,), cls_attributes) xsd_type = None # Process content annotation, children = self._pop_annotation(node.getchildren()) first_tag = children[0].tag if children else None if first_tag == tags.simpleContent: base_type, attributes = self.visit_simple_content(children[0], node) xsd_type = xsd_cls( attributes=attributes, extension=base_type, qname=qname, is_global=is_global) elif first_tag == tags.complexContent: kwargs = self.visit_complex_content(children[0], node) xsd_type = xsd_cls(qname=qname, is_global=is_global, **kwargs) elif first_tag: element = None if first_tag in (tags.group, tags.all, tags.choice, tags.sequence): child = children.pop(0) element = self.process(child, node) attributes = self._process_attributes(node, children) xsd_type = xsd_cls( element=element, attributes=attributes, qname=qname, is_global=is_global) else: xsd_type = xsd_cls(qname=qname, is_global=is_global) if is_global: self.register_type(qname, xsd_type) return xsd_type def visit_complex_content(self, node, parent): """The complexContent element defines extensions or restrictions on a complex type that contains mixed content or elements only. Definition:: <complexContent id = ID mixed = Boolean {any attributes with non-schema Namespace}...> Content: (annotation?, (restriction | extension)) </complexContent> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ child = node.getchildren()[-1] if child.tag == tags.restriction: base, element, attributes = self.visit_restriction_complex_content( child, node) return { 'attributes': attributes, 'element': element, 'restriction': base, } elif child.tag == tags.extension: base, element, attributes = self.visit_extension_complex_content( child, node) return { 'attributes': attributes, 'element': element, 'extension': base, } def visit_simple_content(self, node, parent): """Contains extensions or restrictions on a complexType element with character data or a simpleType element as content and contains no elements. Definition:: <simpleContent id = ID {any attributes with non-schema Namespace}...> Content: (annotation?, (restriction | extension)) </simpleContent> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ child = node.getchildren()[-1] if child.tag == tags.restriction: return self.visit_restriction_simple_content(child, node) elif child.tag == tags.extension: return self.visit_extension_simple_content(child, node) raise AssertionError("Expected restriction or extension") def visit_restriction_simple_type(self, node, parent): """ Definition:: <restriction base = QName id = ID {any attributes with non-schema Namespace}...> Content: (annotation?, (simpleType?, ( minExclusive | minInclusive | maxExclusive | maxInclusive | totalDigits |fractionDigits | length | minLength | maxLength | enumeration | whiteSpace | pattern)*)) </restriction> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ base_name = qname_attr(node, 'base') if base_name: return self._get_type(base_name) annotation, children = self._pop_annotation(node.getchildren()) if children[0].tag == tags.simpleType: return self.visit_simple_type(children[0], node) def visit_restriction_simple_content(self, node, parent): """ Definition:: <restriction base = QName id = ID {any attributes with non-schema Namespace}...> Content: (annotation?, (simpleType?, ( minExclusive | minInclusive | maxExclusive | maxInclusive | totalDigits |fractionDigits | length | minLength | maxLength | enumeration | whiteSpace | pattern)* )?, ((attribute | attributeGroup)*, anyAttribute?)) </restriction> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ base_name = qname_attr(node, 'base') base_type = self._get_type(base_name) return base_type, [] def visit_restriction_complex_content(self, node, parent): """ Definition:: <restriction base = QName id = ID {any attributes with non-schema Namespace}...> Content: (annotation?, (group | all | choice | sequence)?, ((attribute | attributeGroup)*, anyAttribute?)) </restriction> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ base_name = qname_attr(node, 'base') base_type = self._get_type(base_name) annotation, children = self._pop_annotation(node.getchildren()) element = None attributes = [] if children: child = children[0] if child.tag in (tags.group, tags.all, tags.choice, tags.sequence): children.pop(0) element = self.process(child, node) attributes = self._process_attributes(node, children) return base_type, element, attributes def visit_extension_complex_content(self, node, parent): """ Definition:: <extension base = QName id = ID {any attributes with non-schema Namespace}...> Content: (annotation?, ( (group | all | choice | sequence)?, ((attribute | attributeGroup)*, anyAttribute?))) </extension> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ base_name = qname_attr(node, 'base') base_type = self._get_type(base_name) annotation, children = self._pop_annotation(node.getchildren()) element = None attributes = [] if children: child = children[0] if child.tag in (tags.group, tags.all, tags.choice, tags.sequence): children.pop(0) element = self.process(child, node) attributes = self._process_attributes(node, children) return base_type, element, attributes def visit_extension_simple_content(self, node, parent): """ Definition:: <extension base = QName id = ID {any attributes with non-schema Namespace}...> Content: (annotation?, ((attribute | attributeGroup)*, anyAttribute?)) </extension> """ base_name = qname_attr(node, 'base') base_type = self._get_type(base_name) annotation, children = self._pop_annotation(node.getchildren()) attributes = self._process_attributes(node, children) return base_type, attributes def visit_annotation(self, node, parent): """Defines an annotation. Definition:: <annotation id = ID {any attributes with non-schema Namespace}...> Content: (appinfo | documentation)* </annotation> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ return def visit_any(self, node, parent): """ Definition:: <any id = ID maxOccurs = (nonNegativeInteger | unbounded) : 1 minOccurs = nonNegativeInteger : 1 namespace = "(##any | ##other) | List of (anyURI | (##targetNamespace | ##local))) : ##any processContents = (lax | skip | strict) : strict {any attributes with non-schema Namespace...}> Content: (annotation?) </any> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ min_occurs, max_occurs = _process_occurs_attrs(node) process_contents = node.get('processContents', 'strict') return xsd_elements.Any( max_occurs=max_occurs, min_occurs=min_occurs, process_contents=process_contents) def visit_sequence(self, node, parent): """ Definition:: <sequence id = ID maxOccurs = (nonNegativeInteger | unbounded) : 1 minOccurs = nonNegativeInteger : 1 {any attributes with non-schema Namespace}...> Content: (annotation?, (element | group | choice | sequence | any)*) </sequence> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ sub_types = [ tags.annotation, tags.any, tags.choice, tags.element, tags.group, tags.sequence ] min_occurs, max_occurs = _process_occurs_attrs(node) result = xsd_elements.Sequence( min_occurs=min_occurs, max_occurs=max_occurs) annotation, items = self._pop_annotation(node.getchildren()) for child in items: assert child.tag in sub_types, child item = self.process(child, node) assert item is not None result.append(item) assert None not in result return result def visit_all(self, node, parent): """Allows the elements in the group to appear (or not appear) in any order in the containing element. Definition:: <all id = ID maxOccurs= 1: 1 minOccurs= (0 | 1): 1 {any attributes with non-schema Namespace...}> Content: (annotation?, element*) </all> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ sub_types = [ tags.annotation, tags.element ] result = xsd_elements.All() for child in node.iterchildren(): assert child.tag in sub_types, child item = self.process(child, node) result.append(item) assert None not in result return result def visit_group(self, node, parent): """Groups a set of element declarations so that they can be incorporated as a group into complex type definitions. Definition:: <group name= NCName id = ID maxOccurs = (nonNegativeInteger | unbounded) : 1 minOccurs = nonNegativeInteger : 1 name = NCName ref = QName {any attributes with non-schema Namespace}...> Content: (annotation?, (all | choice | sequence)) </group> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ min_occurs, max_occurs = _process_occurs_attrs(node) result = self.process_reference( node, min_occurs=min_occurs, max_occurs=max_occurs) if result: return result qname = qname_attr(node, 'name', self.document._target_namespace) # There should be only max nodes, first node (annotation) is irrelevant annotation, children = self._pop_annotation(node.getchildren()) child = children[0] item = self.process(child, parent) elm = xsd_elements.Group(name=qname, child=item) if parent.tag == tags.schema: self.register_group(qname, elm) return elm def visit_list(self, node, parent): """ Definition:: <list id = ID itemType = QName {any attributes with non-schema Namespace}...> Content: (annotation?, (simpleType?)) </list> The use of the simpleType element child and the itemType attribute is mutually exclusive. :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ item_type = qname_attr(node, 'itemType') if item_type: sub_type = self._get_type(item_type.text) else: subnodes = node.getchildren() child = subnodes[-1] # skip annotation sub_type = self.visit_simple_type(child, node) return xsd_types.ListType(sub_type) def visit_choice(self, node, parent): """ Definition:: <choice id = ID maxOccurs= (nonNegativeInteger | unbounded) : 1 minOccurs= nonNegativeInteger : 1 {any attributes with non-schema Namespace}...> Content: (annotation?, (element | group | choice | sequence | any)*) </choice> """ min_occurs, max_occurs = _process_occurs_attrs(node) children = node.getchildren() annotation, children = self._pop_annotation(children) choices = [] for child in children: elm = self.process(child, node) choices.append(elm) return xsd_elements.Choice( choices, min_occurs=min_occurs, max_occurs=max_occurs) def visit_union(self, node, parent): """Defines a collection of multiple simpleType definitions. Definition:: <union id = ID memberTypes = List of QNames {any attributes with non-schema Namespace}...> Content: (annotation?, (simpleType*)) </union> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ # TODO members = node.get('memberTypes') types = [] if members: for member in members.split(): qname = as_qname(member, node.nsmap) xsd_type = self._get_type(qname) types.append(xsd_type) else: annotation, types = self._pop_annotation(node.getchildren()) types = [self.visit_simple_type(t, node) for t in types] return xsd_types.UnionType(types) def visit_unique(self, node, parent): """Specifies that an attribute or element value (or a combination of attribute or element values) must be unique within the specified scope. The value must be unique or nil. Definition:: <unique id = ID name = NCName {any attributes with non-schema Namespace}...> Content: (annotation?, (selector, field+)) </unique> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ # TODO pass def visit_attribute_group(self, node, parent): """ Definition:: <attributeGroup id = ID name = NCName ref = QName {any attributes with non-schema Namespace...}> Content: (annotation?), ((attribute | attributeGroup)*, anyAttribute?)) </attributeGroup> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ ref = self.process_reference(node) if ref: return ref qname = qname_attr(node, 'name', self.document._target_namespace) annotation, children = self._pop_annotation(node.getchildren()) attributes = self._process_attributes(node, children) attribute_group = xsd_elements.AttributeGroup(qname, attributes) self.register_attribute_group(qname, attribute_group) def visit_any_attribute(self, node, parent): """ Definition:: <anyAttribute id = ID namespace = ((##any | ##other) | List of (anyURI | (##targetNamespace | ##local))) : ##any processContents = (lax | skip | strict): strict {any attributes with non-schema Namespace...}> Content: (annotation?) </anyAttribute> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ process_contents = node.get('processContents', 'strict') return xsd_elements.AnyAttribute(process_contents=process_contents) def visit_notation(self, node, parent): """Contains the definition of a notation to describe the format of non-XML data within an XML document. An XML Schema notation declaration is a reconstruction of XML 1.0 NOTATION declarations. Definition:: <notation id = ID name = NCName public = Public identifier per ISO 8879 system = anyURI {any attributes with non-schema Namespace}...> Content: (annotation?) </notation> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ pass def _get_type(self, name): assert name is not None name = self._create_qname(name) return xsd_types.UnresolvedType(name, self.schema) def _create_qname(self, name): if not isinstance(name, etree.QName): name = etree.QName(name) # Handle reserved namespace if name.namespace == 'xml': name = etree.QName( 'http://www.w3.org/XML/1998/namespace', name.localname) # Various xsd builders assume that some schema's are available by # default (actually this is mostly just the soap-enc ns). So live with # that fact and handle it by auto-importing the schema if it is # referenced. if ( name.namespace == 'http://schemas.xmlsoap.org/soap/encoding/' and not self.document.is_imported(name.namespace) ): import_node = etree.Element( tags.import_, namespace=name.namespace, schemaLocation=name.namespace) self.visit_import(import_node, None) return name def _pop_annotation(self, items): if not len(items): return None, [] if items[0].tag == tags.annotation: annotation = self.visit_annotation(items[0], None) return annotation, items[1:] return None, items def _process_attributes(self, node, items): attributes = [] for child in items: if child.tag in (tags.attribute, tags.attributeGroup, tags.anyAttribute): attribute = self.process(child, node) attributes.append(attribute) else: raise XMLParseError( "Unexpected tag `%s`" % (child.tag), filename=self.document._location, sourceline=node.sourceline) return attributes visitors = { tags.any: visit_any, tags.element: visit_element, tags.choice: visit_choice, tags.simpleType: visit_simple_type, tags.anyAttribute: visit_any_attribute, tags.complexType: visit_complex_type, tags.simpleContent: None, tags.complexContent: None, tags.sequence: visit_sequence, tags.all: visit_all, tags.group: visit_group, tags.attribute: visit_attribute, tags.import_: visit_import, tags.include: visit_include, tags.annotation: visit_annotation, tags.attributeGroup: visit_attribute_group, tags.notation: visit_notation, } def _process_occurs_attrs(node): """Process the min/max occurrence indicators""" max_occurs = node.get('maxOccurs', '1') min_occurs = int(node.get('minOccurs', '1')) if max_occurs == 'unbounded': max_occurs = 'unbounded' else: max_occurs = int(max_occurs) return min_occurs, max_occurs
zeep-adv
/zeep-adv-1.4.4.tar.gz/zeep-adv-1.4.4/src/zeep/xsd/visitor.py
visitor.py
import copy from collections import OrderedDict from zeep.xsd.printer import PrettyPrinter __all__ = ['AnyObject', 'CompoundValue'] class AnyObject(object): """Create an any object :param xsd_object: the xsd type :param value: The value """ def __init__(self, xsd_object, value): self.xsd_obj = xsd_object self.value = value def __repr__(self): return '<%s(type=%r, value=%r)>' % ( self.__class__.__name__, self.xsd_elm, self.value) def __deepcopy__(self, memo): return type(self)(self.xsd_elm, copy.deepcopy(self.value)) @property def xsd_type(self): return self.xsd_obj @property def xsd_elm(self): return self.xsd_obj class CompoundValue(object): """Represents a data object for a specific xsd:complexType.""" def __init__(self, *args, **kwargs): values = OrderedDict() # Set default values for container_name, container in self._xsd_type.elements_nested: elm_values = container.default_value if isinstance(elm_values, dict): values.update(elm_values) else: values[container_name] = elm_values # Set attributes for attribute_name, attribute in self._xsd_type.attributes: values[attribute_name] = attribute.default_value # Set elements items = _process_signature(self._xsd_type, args, kwargs) for key, value in items.items(): values[key] = value self.__values__ = values def __contains__(self, key): return self.__values__.__contains__(key) def __eq__(self, other): if self.__class__ != other.__class__: return False other_values = {key: other[key] for key in other} return other_values == self.__values__ def __len__(self): return self.__values__.__len__() def __iter__(self): return self.__values__.__iter__() def __repr__(self): return PrettyPrinter().pformat(self.__values__) def __delitem__(self, key): return self.__values__.__delitem__(key) def __getitem__(self, key): return self.__values__[key] def __setitem__(self, key, value): self.__values__[key] = value def __setattr__(self, key, value): if key.startswith('__') or key in ('_xsd_type', '_xsd_elm'): return super(CompoundValue, self).__setattr__(key, value) self.__values__[key] = value def __getattribute__(self, key): if key.startswith('__') or key in ('_xsd_type', '_xsd_elm'): return super(CompoundValue, self).__getattribute__(key) try: return self.__values__[key] except KeyError: raise AttributeError( "%s instance has no attribute '%s'" % ( self.__class__.__name__, key)) def __deepcopy__(self, memo): new = type(self)() new.__values__ = copy.deepcopy(self.__values__) for attr, value in self.__dict__.items(): if attr != '__values__': setattr(new, attr, value) return new def _process_signature(xsd_type, args, kwargs): """Return a dict with the args/kwargs mapped to the field name. Special handling is done for Choice elements since we need to record which element the user intends to use. :param fields: List of tuples (name, element) :type fields: list :param args: arg tuples :type args: tuple :param kwargs: kwargs :type kwargs: dict """ result = OrderedDict() # Process the positional arguments. args is currently still modified # in-place here if args: args = list(args) num_args = len(args) index = 0 for element_name, element in xsd_type.elements_nested: values, args, index = element.parse_args(args, index) if not values: break result.update(values) for attribute_name, attribute in xsd_type.attributes: if num_args <= index: break result[attribute_name] = args[index] index += 1 if num_args > index: raise TypeError( "__init__() takes at most %s positional arguments (%s given)" % ( len(result), num_args)) # Process the named arguments (sequence/group/all/choice). The # available_kwargs set is modified in-place. available_kwargs = set(kwargs.keys()) for element_name, element in xsd_type.elements_nested: if element.accepts_multiple: values = element.parse_kwargs(kwargs, element_name, available_kwargs) else: values = element.parse_kwargs(kwargs, None, available_kwargs) if values is not None: for key, value in values.items(): if key not in result: result[key] = value # Process the named arguments for attributes if available_kwargs: for attribute_name, attribute in xsd_type.attributes: if attribute_name in available_kwargs: available_kwargs.remove(attribute_name) result[attribute_name] = kwargs[attribute_name] if available_kwargs: raise TypeError(( "%s() got an unexpected keyword argument %r. " + "Signature: `%s`" ) % ( xsd_type.qname or 'ComplexType', next(iter(available_kwargs)), xsd_type.signature(standalone=False))) return result
zeep-adv
/zeep-adv-1.4.4.tar.gz/zeep-adv-1.4.4/src/zeep/xsd/valueobjects.py
valueobjects.py
import copy import operator from collections import OrderedDict, defaultdict, deque from cached_property import threaded_cached_property from zeep.exceptions import UnexpectedElementError, ValidationError from zeep.xsd.const import NotSet, SkipValue from zeep.xsd.elements import Any, Element from zeep.xsd.elements.base import Base from zeep.xsd.utils import ( NamePrefixGenerator, UniqueNameGenerator, create_prefixed_name, max_occurs_iter) __all__ = ['All', 'Choice', 'Group', 'Sequence'] class Indicator(Base): def __repr__(self): return '<%s(%s)>' % ( self.__class__.__name__, super(Indicator, self).__repr__()) @threaded_cached_property def default_value(self): values = OrderedDict([ (name, element.default_value) for name, element in self.elements ]) if self.accepts_multiple: return {'_value_1': values} return values def clone(self, name, min_occurs=1, max_occurs=1): raise NotImplementedError() class OrderIndicator(Indicator, list): name = None def __init__(self, elements=None, min_occurs=1, max_occurs=1): self.min_occurs = min_occurs self.max_occurs = max_occurs super(OrderIndicator, self).__init__() if elements is not None: self.extend(elements) def clone(self, name, min_occurs=1, max_occurs=1): return self.__class__( elements=list(self), min_occurs=min_occurs, max_occurs=max_occurs) @threaded_cached_property def elements(self): """List of tuples containing the element name and the element""" result = [] for name, elm in self.elements_nested: if name is None: result.extend(elm.elements) else: result.append((name, elm)) return result @threaded_cached_property def elements_nested(self): """List of tuples containing the element name and the element""" result = [] generator = NamePrefixGenerator() generator_2 = UniqueNameGenerator() for elm in self: if isinstance(elm, (All, Choice, Group, Sequence)): if elm.accepts_multiple: result.append((generator.get_name(), elm)) else: for sub_name, sub_elm in elm.elements: sub_name = generator_2.create_name(sub_name) result.append((None, elm)) elif isinstance(elm, (Any, Choice)): result.append((generator.get_name(), elm)) else: name = generator_2.create_name(elm.attr_name) result.append((name, elm)) return result def accept(self, values): """Return the number of values which are accepted by this choice. If not all required elements are available then 0 is returned. """ if not self.accepts_multiple: values = [values] results = set() for value in values: num = 0 for name, element in self.elements_nested: if isinstance(element, Element): if element.name in value and value[element.name] is not None: num += 1 else: num += element.accept(value) results.add(num) return max(results) def parse_args(self, args, index=0): result = {} for name, element in self.elements: if index >= len(args): break result[name] = args[index] index += 1 return result, args, index def parse_kwargs(self, kwargs, name, available_kwargs): """Apply the given kwarg to the element. The available_kwargs is modified in-place. Returns a dict with the result. """ if self.accepts_multiple: assert name if name: if name not in available_kwargs: return {} assert self.accepts_multiple # Make sure we have a list, lame lame item_kwargs = kwargs.get(name) if not isinstance(item_kwargs, list): item_kwargs = [item_kwargs] result = [] for item_value in max_occurs_iter(self.max_occurs, item_kwargs): try: item_kwargs = set(item_value.keys()) except AttributeError: raise TypeError( "A list of dicts is expected for unbounded Sequences") subresult = OrderedDict() for item_name, element in self.elements: value = element.parse_kwargs(item_value, item_name, item_kwargs) if value is not None: subresult.update(value) if item_kwargs: raise TypeError(( "%s() got an unexpected keyword argument %r." ) % (self, list(item_kwargs)[0])) result.append(subresult) result = {name: result} # All items consumed if not any(filter(None, item_kwargs)): available_kwargs.remove(name) return result else: assert not self.accepts_multiple result = OrderedDict() for elm_name, element in self.elements_nested: sub_result = element.parse_kwargs(kwargs, elm_name, available_kwargs) if sub_result: result.update(sub_result) return result def resolve(self): for i, elm in enumerate(self): self[i] = elm.resolve() return self def render(self, parent, value, render_path): """Create subelements in the given parent object.""" if not isinstance(value, list): values = [value] else: values = value self.validate(values, render_path) for value in max_occurs_iter(self.max_occurs, values): for name, element in self.elements_nested: if name: if name in value: element_value = value[name] child_path = render_path + [name] else: element_value = NotSet child_path = render_path else: element_value = value child_path = render_path if element_value is SkipValue: continue if element_value is not None or not element.is_optional: element.render(parent, element_value, child_path) def validate(self, value, render_path): for item in value: if item is NotSet: raise ValidationError("No value set", path=render_path) def signature(self, schema=None, standalone=True): parts = [] for name, element in self.elements_nested: if isinstance(element, Indicator): parts.append(element.signature(schema, standalone=False)) else: value = element.signature(schema, standalone=False) parts.append('%s: %s' % (name, value)) part = ', '.join(parts) if self.accepts_multiple: return '[%s]' % (part,) return part class All(OrderIndicator): """Allows the elements in the group to appear (or not appear) in any order in the containing element. """ def parse_xmlelements(self, xmlelements, schema, name=None, context=None): """Consume matching xmlelements :param xmlelements: Dequeue of XML element objects :type xmlelements: collections.deque of lxml.etree._Element :param schema: The parent XML schema :type schema: zeep.xsd.Schema :param name: The name of the parent element :type name: str :param context: Optional parsing context (for inline schemas) :type context: zeep.xsd.context.XmlParserContext :rtype: dict or None """ result = OrderedDict() expected_tags = {element.qname for __, element in self.elements} consumed_tags = set() values = defaultdict(deque) for i, elm in enumerate(xmlelements): if elm.tag in expected_tags: consumed_tags.add(i) values[elm.tag].append(elm) # Remove the consumed tags from the xmlelements for i in sorted(consumed_tags, reverse=True): del xmlelements[i] for name, element in self.elements: sub_elements = values.get(element.qname) if sub_elements: result[name] = element.parse_xmlelements( sub_elements, schema, context=context) return result class Choice(OrderIndicator): """Permits one and only one of the elements contained in the group.""" @property def is_optional(self): return True @property def default_value(self): return OrderedDict() def parse_xmlelements(self, xmlelements, schema, name=None, context=None): """Consume matching xmlelements :param xmlelements: Dequeue of XML element objects :type xmlelements: collections.deque of lxml.etree._Element :param schema: The parent XML schema :type schema: zeep.xsd.Schema :param name: The name of the parent element :type name: str :param context: Optional parsing context (for inline schemas) :type context: zeep.xsd.context.XmlParserContext :rtype: dict or None """ result = [] for _unused in max_occurs_iter(self.max_occurs): if not xmlelements: break # Choose out of multiple options = [] for element_name, element in self.elements_nested: local_xmlelements = copy.copy(xmlelements) try: sub_result = element.parse_xmlelements( xmlelements=local_xmlelements, schema=schema, name=element_name, context=context) except UnexpectedElementError: continue if isinstance(element, Element): sub_result = {element_name: sub_result} num_consumed = len(xmlelements) - len(local_xmlelements) if num_consumed: options.append((num_consumed, sub_result)) if not options: xmlelements = [] break # Sort on least left options = sorted(options, key=operator.itemgetter(0), reverse=True) if options: result.append(options[0][1]) for i in range(options[0][0]): xmlelements.popleft() else: break if self.accepts_multiple: result = {name: result} else: result = result[0] if result else {} return result def parse_kwargs(self, kwargs, name, available_kwargs): """Processes the kwargs for this choice element. Returns a dict containing the values found. This handles two distinct initialization methods: 1. Passing the choice elements directly to the kwargs (unnested) 2. Passing the choice elements into the `name` kwarg (_value_1) (nested). This case is required when multiple choice elements are given. :param name: Name of the choice element (_value_1) :type name: str :param element: Choice element object :type element: zeep.xsd.Choice :param kwargs: dict (or list of dicts) of kwargs for initialization :type kwargs: list / dict """ if name and name in available_kwargs: assert self.accepts_multiple values = kwargs[name] or [] available_kwargs.remove(name) result = [] if isinstance(values, dict): values = [values] # TODO: Use most greedy choice instead of first matching for value in values: for element in self: if isinstance(element, OrderIndicator): choice_value = value[name] if name in value else value if element.accept(choice_value): result.append(choice_value) break else: if element.name in value: choice_value = value.get(element.name) result.append({element.name: choice_value}) break else: raise TypeError( "No complete xsd:Sequence found for the xsd:Choice %r.\n" "The signature is: %s" % (name, self.signature())) if not self.accepts_multiple: result = result[0] if result else None else: # Direct use-case isn't supported when maxOccurs > 1 if self.accepts_multiple: return {} result = {} # When choice elements are specified directly in the kwargs found = False for name, choice in self.elements_nested: temp_kwargs = copy.copy(available_kwargs) subresult = choice.parse_kwargs(kwargs, name, temp_kwargs) if subresult: if not any(subresult.values()): available_kwargs.intersection_update(temp_kwargs) result.update(subresult) elif not found: available_kwargs.intersection_update(temp_kwargs) result.update(subresult) found = True if found: for choice_name, choice in self.elements: result.setdefault(choice_name, None) else: result = {} if name and self.accepts_multiple: result = {name: result} return result def render(self, parent, value, render_path): """Render the value to the parent element tree node. This is a bit more complex then the order render methods since we need to search for the best matching choice element. """ if not self.accepts_multiple: value = [value] self.validate(value, render_path) for item in value: result = self._find_element_to_render(item) if result: element, choice_value = result element.render(parent, choice_value, render_path) def validate(self, value, render_path): found = 0 for item in value: result = self._find_element_to_render(item) if result: found += 1 if not found and not self.is_optional: raise ValidationError("Missing choice values", path=render_path) def accept(self, values): """Return the number of values which are accepted by this choice. If not all required elements are available then 0 is returned. """ nums = set() for name, element in self.elements_nested: if isinstance(element, Element): if self.accepts_multiple: if all(name in item and item[name] for item in values): nums.add(1) else: if name in values and values[name]: nums.add(1) else: num = element.accept(values) nums.add(num) return max(nums) if nums else 0 def _find_element_to_render(self, value): """Return a tuple (element, value) for the best matching choice. This is used to decide which choice child is best suitable for rendering the available data. """ matches = [] for name, element in self.elements_nested: if isinstance(element, Element): if element.name in value: try: choice_value = value[element.name] except KeyError: choice_value = value if choice_value is not None: matches.append((1, element, choice_value)) else: if name is not None: try: choice_value = value[name] except KeyError: choice_value = value else: choice_value = value score = element.accept(choice_value) if score: matches.append((score, element, choice_value)) if matches: matches = sorted(matches, key=operator.itemgetter(0), reverse=True) return matches[0][1:] def signature(self, schema=None, standalone=True): parts = [] for name, element in self.elements_nested: if isinstance(element, OrderIndicator): parts.append('{%s}' % (element.signature(schema, standalone=False))) else: parts.append('{%s: %s}' % (name, element.signature(schema, standalone=False))) part = '(%s)' % ' | '.join(parts) if self.accepts_multiple: return '%s[]' % (part,) return part class Sequence(OrderIndicator): """Requires the elements in the group to appear in the specified sequence within the containing element. """ def parse_xmlelements(self, xmlelements, schema, name=None, context=None): """Consume matching xmlelements :param xmlelements: Dequeue of XML element objects :type xmlelements: collections.deque of lxml.etree._Element :param schema: The parent XML schema :type schema: zeep.xsd.Schema :param name: The name of the parent element :type name: str :param context: Optional parsing context (for inline schemas) :type context: zeep.xsd.context.XmlParserContext :rtype: dict or None """ result = [] if self.accepts_multiple: assert name for _unused in max_occurs_iter(self.max_occurs): if not xmlelements: break item_result = OrderedDict() for elm_name, element in self.elements: try: item_subresult = element.parse_xmlelements( xmlelements, schema, name, context=context) except UnexpectedElementError: if schema.strict: raise item_subresult = None # Unwrap if allowed if isinstance(element, OrderIndicator): item_result.update(item_subresult) else: item_result[elm_name] = item_subresult if not xmlelements: break if item_result: result.append(item_result) if not self.accepts_multiple: return result[0] if result else None return {name: result} class Group(Indicator): """Groups a set of element declarations so that they can be incorporated as a group into complex type definitions. """ def __init__(self, name, child, max_occurs=1, min_occurs=1): super(Group, self).__init__() self.child = child self.qname = name self.name = name.localname self.max_occurs = max_occurs self.min_occurs = min_occurs def __str__(self): return self.signature() def __iter__(self, *args, **kwargs): for item in self.child: yield item @threaded_cached_property def elements(self): if self.accepts_multiple: return [('_value_1', self.child)] return self.child.elements def clone(self, name, min_occurs=1, max_occurs=1): return self.__class__( name=name, child=self.child, min_occurs=min_occurs, max_occurs=max_occurs) def accept(self, values): """Return the number of values which are accepted by this choice. If not all required elements are available then 0 is returned. """ return self.child.accept(values) def parse_args(self, args, index=0): return self.child.parse_args(args, index) def parse_kwargs(self, kwargs, name, available_kwargs): if self.accepts_multiple: if name not in kwargs: return {} available_kwargs.remove(name) item_kwargs = kwargs[name] result = [] sub_name = '_value_1' if self.child.accepts_multiple else None for sub_kwargs in max_occurs_iter(self.max_occurs, item_kwargs): available_sub_kwargs = set(sub_kwargs.keys()) subresult = self.child.parse_kwargs( sub_kwargs, sub_name, available_sub_kwargs) if available_sub_kwargs: raise TypeError(( "%s() got an unexpected keyword argument %r." ) % (self, list(available_sub_kwargs)[0])) if subresult: result.append(subresult) if result: result = {name: result} else: result = self.child.parse_kwargs(kwargs, name, available_kwargs) return result def parse_xmlelements(self, xmlelements, schema, name=None, context=None): """Consume matching xmlelements :param xmlelements: Dequeue of XML element objects :type xmlelements: collections.deque of lxml.etree._Element :param schema: The parent XML schema :type schema: zeep.xsd.Schema :param name: The name of the parent element :type name: str :param context: Optional parsing context (for inline schemas) :type context: zeep.xsd.context.XmlParserContext :rtype: dict or None """ result = [] for _unused in max_occurs_iter(self.max_occurs): result.append( self.child.parse_xmlelements( xmlelements, schema, name, context=context) ) if not xmlelements: break if not self.accepts_multiple and result: return result[0] return {name: result} def render(self, parent, value, render_path): if not isinstance(value, list): values = [value] else: values = value for value in values: self.child.render(parent, value, render_path) def resolve(self): self.child = self.child.resolve() return self def signature(self, schema=None, standalone=True): name = create_prefixed_name(self.qname, schema) if standalone: return '%s(%s)' % ( name, self.child.signature(schema, standalone=False)) else: return self.child.signature(schema, standalone=False)
zeep-adv
/zeep-adv-1.4.4.tar.gz/zeep-adv-1.4.4/src/zeep/xsd/elements/indicators.py
indicators.py
import logging from lxml import etree from zeep import exceptions from zeep.utils import qname_attr from zeep.xsd.const import xsi_ns, NotSet from zeep.xsd.elements.base import Base from zeep.xsd.utils import max_occurs_iter from zeep.xsd.valueobjects import AnyObject logger = logging.getLogger(__name__) __all__ = ['Any', 'AnyAttribute'] class Any(Base): name = None def __init__(self, max_occurs=1, min_occurs=1, process_contents='strict', restrict=None): """ :param process_contents: Specifies how the XML processor should handle validation against the elements specified by this any element :type process_contents: str (strict, lax, skip) """ super(Any, self).__init__() self.max_occurs = max_occurs self.min_occurs = min_occurs self.restrict = restrict self.process_contents = process_contents # cyclic import from zeep.xsd import AnyType self.type = AnyType() def __call__(self, any_object): return any_object def __repr__(self): return '<%s(name=%r)>' % (self.__class__.__name__, self.name) def accept(self, value): return True def parse(self, xmlelement, schema, context=None): if self.process_contents == 'skip': return xmlelement # If a schema was passed inline then check for a matching one qname = etree.QName(xmlelement.tag) if context and context.schemas: for context_schema in context.schemas: if context_schema._has_schema_document(qname.namespace): schema = context_schema break # Lookup type via xsi:type attribute xsd_type = qname_attr(xmlelement, xsi_ns('type')) if xsd_type is not None: xsd_type = schema.get_type(xsd_type) return xsd_type.parse_xmlelement(xmlelement, schema, context=context) # Check if a restrict is used if self.restrict: return self.restrict.parse_xmlelement( xmlelement, schema, context=context) try: element = schema.get_element(xmlelement.tag) return element.parse(xmlelement, schema, context=context) except (exceptions.NamespaceError, exceptions.LookupError): return xmlelement def parse_kwargs(self, kwargs, name, available_kwargs): if name in available_kwargs: available_kwargs.remove(name) value = kwargs[name] return {name: value} return {} def parse_xmlelements(self, xmlelements, schema, name=None, context=None): """Consume matching xmlelements and call parse() on each of them :param xmlelements: Dequeue of XML element objects :type xmlelements: collections.deque of lxml.etree._Element :param schema: The parent XML schema :type schema: zeep.xsd.Schema :param name: The name of the parent element :type name: str :param context: Optional parsing context (for inline schemas) :type context: zeep.xsd.context.XmlParserContext :return: dict or None """ result = [] for _unused in max_occurs_iter(self.max_occurs): if xmlelements: xmlelement = xmlelements.popleft() item = self.parse(xmlelement, schema, context=context) if item is not None: result.append(item) else: break if not self.accepts_multiple: result = result[0] if result else None return result def render(self, parent, value, render_path=None): assert parent is not None self.validate(value, render_path) if self.accepts_multiple and isinstance(value, list): from zeep.xsd import AnySimpleType if isinstance(self.restrict, AnySimpleType): for val in value: node = etree.SubElement(parent, 'item') node.set(xsi_ns('type'), self.restrict.qname) self._render_value_item(node, val, render_path) elif self.restrict: for val in value: node = etree.SubElement(parent, self.restrict.name) # node.set(xsi_ns('type'), self.restrict.qname) self._render_value_item(node, val, render_path) else: for val in value: self._render_value_item(parent, val, render_path) else: self._render_value_item(parent, value, render_path) def _render_value_item(self, parent, value, render_path): if value is None: # can be an lxml element return elif isinstance(value, etree._Element): parent.append(value) elif self.restrict: if isinstance(value, list): for val in value: self.restrict.render(parent, val, None, render_path) else: self.restrict.render(parent, value, None, render_path) else: if isinstance(value.value, list): for val in value.value: value.xsd_elm.render(parent, val, render_path) else: value.xsd_elm.render(parent, value.value, render_path) def validate(self, value, render_path): if self.accepts_multiple and isinstance(value, list): # Validate bounds if len(value) < self.min_occurs: raise exceptions.ValidationError( "Expected at least %d items (minOccurs check)" % self.min_occurs) if self.max_occurs != 'unbounded' and len(value) > self.max_occurs: raise exceptions.ValidationError( "Expected at most %d items (maxOccurs check)" % self.min_occurs) for val in value: self._validate_item(val, render_path) else: if not self.is_optional and value in (None, NotSet): raise exceptions.ValidationError("Missing element for Any") self._validate_item(value, render_path) def _validate_item(self, value, render_path): if value is None: # can be an lxml element return # Check if we received a proper value object. If we receive the wrong # type then return a nice error message if self.restrict: expected_types = (etree._Element,) + self.restrict.accepted_types else: expected_types = (etree._Element, AnyObject) if not isinstance(value, expected_types): type_names = [ '%s.%s' % (t.__module__, t.__name__) for t in expected_types ] err_message = "Any element received object of type %r, expected %s" % ( type(value).__name__, ' or '.join(type_names)) raise TypeError('\n'.join(( err_message, "See http://docs.python-zeep.org/en/master/datastructures.html" "#any-objects for more information" ))) def resolve(self): return self def signature(self, schema=None, standalone=True): if self.restrict: base = self.restrict.name else: base = 'ANY' if self.accepts_multiple: return '%s[]' % base return base class AnyAttribute(Base): name = None def __init__(self, process_contents='strict'): self.qname = None self.process_contents = process_contents def parse(self, attributes, context=None): return attributes def resolve(self): return self def render(self, parent, value, render_path=None): if value is None: return for name, val in value.items(): parent.set(name, val) def signature(self, schema=None, standalone=True): return '{}'
zeep-adv
/zeep-adv-1.4.4.tar.gz/zeep-adv-1.4.4/src/zeep/xsd/elements/any.py
any.py
import copy import logging from lxml import etree from zeep import exceptions from zeep.exceptions import UnexpectedElementError from zeep.utils import qname_attr from zeep.xsd.const import NotSet, xsi_ns from zeep.xsd.context import XmlParserContext from zeep.xsd.elements.base import Base from zeep.xsd.utils import max_occurs_iter, create_prefixed_name logger = logging.getLogger(__name__) __all__ = ['Element'] class Element(Base): def __init__(self, name, type_=None, min_occurs=1, max_occurs=1, nillable=False, default=None, is_global=False, attr_name=None): if name is None: raise ValueError("name cannot be None", self.__class__) if not isinstance(name, etree.QName): name = etree.QName(name) self.name = name.localname if name else None self.qname = name self.type = type_ self.min_occurs = min_occurs self.max_occurs = max_occurs self.nillable = nillable self.is_global = is_global self.default = default self.attr_name = attr_name or self.name # assert type_ def __str__(self): if self.type: if self.type.is_global: return '%s(%s)' % (self.name, self.type.qname) else: return '%s(%s)' % (self.name, self.type.signature()) return '%s()' % self.name def __call__(self, *args, **kwargs): instance = self.type(*args, **kwargs) if hasattr(instance, '_xsd_type'): instance._xsd_elm = self return instance def __repr__(self): return '<%s(name=%r, type=%r)>' % ( self.__class__.__name__, self.name, self.type) def __eq__(self, other): return ( other is not None and self.__class__ == other.__class__ and self.__dict__ == other.__dict__) def get_prefixed_name(self, schema): return create_prefixed_name(self.qname, schema) @property def default_value(self): value = [] if self.accepts_multiple else self.default return value def clone(self, name=None, min_occurs=1, max_occurs=1): new = copy.copy(self) if name: if not isinstance(name, etree.QName): name = etree.QName(name) new.name = name.localname new.qname = name new.attr_name = new.name new.min_occurs = min_occurs new.max_occurs = max_occurs return new def parse(self, xmlelement, schema, allow_none=False, context=None): """Process the given xmlelement. If it has an xsi:type attribute then use that for further processing. This should only be done for subtypes of the defined type but for now we just accept everything. """ context = context or XmlParserContext() instance_type = qname_attr(xmlelement, xsi_ns('type')) xsd_type = None if instance_type: xsd_type = schema.get_type(instance_type, fail_silently=True) xsd_type = xsd_type or self.type return xsd_type.parse_xmlelement( xmlelement, schema, allow_none=allow_none, context=context) def parse_kwargs(self, kwargs, name, available_kwargs): return self.type.parse_kwargs( kwargs, name or self.attr_name, available_kwargs) def parse_xmlelements(self, xmlelements, schema, name=None, context=None): """Consume matching xmlelements and call parse() on each of them :param xmlelements: Dequeue of XML element objects :type xmlelements: collections.deque of lxml.etree._Element :param schema: The parent XML schema :type schema: zeep.xsd.Schema :param name: The name of the parent element :type name: str :param context: Optional parsing context (for inline schemas) :type context: zeep.xsd.context.XmlParserContext :return: dict or None """ result = [] num_matches = 0 for _unused in max_occurs_iter(self.max_occurs): if not xmlelements: break # Workaround for SOAP servers which incorrectly use unqualified # or qualified elements in the responses (#170, #176). To make the # best of it we compare the full uri's if both elements have a # namespace. If only one has a namespace then only compare the # localname. # If both elements have a namespace and they don't match then skip element_tag = etree.QName(xmlelements[0].tag) if ( element_tag.namespace and self.qname.namespace and element_tag.namespace != self.qname.namespace and schema.strict ): break # Only compare the localname if element_tag.localname == self.qname.localname: xmlelement = xmlelements.popleft() num_matches += 1 item = self.parse( xmlelement, schema, allow_none=True, context=context) result.append(item) else: # If the element passed doesn't match and the current one is # not optional then throw an error if num_matches == 0 and not self.is_optional: raise UnexpectedElementError( "Unexpected element %r, expected %r" % ( element_tag.text, self.qname.text)) break if not self.accepts_multiple: result = result[0] if result else None return result def render(self, parent, value, render_path=None): """Render the value(s) on the parent lxml.Element. This actually just calls _render_value_item for each value. """ if not render_path: render_path = [self.qname.localname] assert parent is not None self.validate(value, render_path) if self.accepts_multiple and isinstance(value, list): for val in value: self._render_value_item(parent, val, render_path) else: self._render_value_item(parent, value, render_path) def _render_value_item(self, parent, value, render_path): """Render the value on the parent lxml.Element""" if value is None or value is NotSet: if self.is_optional: return elm = etree.SubElement(parent, self.qname) if self.nillable: elm.set(xsi_ns('nil'), 'true') return node = etree.SubElement(parent, self.qname) xsd_type = getattr(value, '_xsd_type', self.type) if xsd_type != self.type: return value._xsd_type.render(node, value, xsd_type, render_path) return self.type.render(node, value, None, render_path) def validate(self, value, render_path=None): """Validate that the value is valid""" if self.accepts_multiple and isinstance(value, list): # Validate bounds if len(value) < self.min_occurs: raise exceptions.ValidationError( "Expected at least %d items (minOccurs check)" % self.min_occurs, path=render_path) elif self.max_occurs != 'unbounded' and len(value) > self.max_occurs: raise exceptions.ValidationError( "Expected at most %d items (maxOccurs check)" % self.min_occurs, path=render_path) for val in value: self._validate_item(val, render_path) else: if not self.is_optional and not self.nillable and value in (None, NotSet): raise exceptions.ValidationError( "Missing element %s" % (self.name), path=render_path) self._validate_item(value, render_path) def _validate_item(self, value, render_path): if self.nillable and value in (None, NotSet): return try: self.type.validate(value, required=True) except exceptions.ValidationError as exc: raise exceptions.ValidationError( "The element %s is not valid: %s" % (self.qname, exc.message), path=render_path) def resolve_type(self): self.type = self.type.resolve() def resolve(self): self.resolve_type() return self def signature(self, schema=None, standalone=True): from zeep.xsd import ComplexType if self.type.is_global: value = self.type.get_prefixed_name(schema) else: value = self.type.signature(schema, standalone=False) if not standalone and isinstance(self.type, ComplexType): value = '{%s}' % value if standalone: value = '%s(%s)' % (self.get_prefixed_name(schema), value) if self.accepts_multiple: return '%s[]' % value return value
zeep-adv
/zeep-adv-1.4.4.tar.gz/zeep-adv-1.4.4/src/zeep/xsd/elements/element.py
element.py
import logging from lxml import etree from zeep import exceptions from zeep.xsd.const import NotSet from zeep.xsd.elements.element import Element logger = logging.getLogger(__name__) __all__ = ['Attribute', 'AttributeGroup'] class Attribute(Element): def __init__(self, name, type_=None, required=False, default=None): super(Attribute, self).__init__(name=name, type_=type_, default=default) self.required = required self.array_type = None def parse(self, value): try: return self.type.pythonvalue(value) except (TypeError, ValueError): logger.exception("Error during xml -> python translation") return None def render(self, parent, value, render_path=None): if value in (None, NotSet) and not self.required: return self.validate(value, render_path) value = self.type.xmlvalue(value) parent.set(self.qname, value) def validate(self, value, render_path): try: self.type.validate(value, required=self.required) except exceptions.ValidationError as exc: raise exceptions.ValidationError( "The attribute %s is not valid: %s" % (self.qname, exc.message), path=render_path) def clone(self, *args, **kwargs): array_type = kwargs.pop('array_type', None) new = super(Attribute, self).clone(*args, **kwargs) new.array_type = array_type return new def resolve(self): retval = super(Attribute, self).resolve() self.type = self.type.resolve() if self.array_type: retval.array_type = self.array_type.resolve() return retval class AttributeGroup(object): def __init__(self, name, attributes): if not isinstance(name, etree.QName): name = etree.QName(name) self.name = name.localname self.qname = name self.type = None self._attributes = attributes self.is_global = True @property def attributes(self): result = [] for attr in self._attributes: if isinstance(attr, AttributeGroup): result.extend(attr.attributes) else: result.append(attr) return result def resolve(self): resolved = [] for attribute in self._attributes: value = attribute.resolve() assert value is not None if isinstance(value, list): resolved.extend(value) else: resolved.append(value) self._attributes = resolved return self def signature(self, schema=None, standalone=True): return ', '.join(attr.signature(schema) for attr in self._attributes)
zeep-adv
/zeep-adv-1.4.4.tar.gz/zeep-adv-1.4.4/src/zeep/xsd/elements/attribute.py
attribute.py
import logging import six from lxml import etree from zeep.exceptions import ValidationError from zeep.xsd.const import xsd_ns from zeep.xsd.types.any import AnyType logger = logging.getLogger(__name__) __all__ = ['AnySimpleType'] @six.python_2_unicode_compatible class AnySimpleType(AnyType): _default_qname = xsd_ns('anySimpleType') def __init__(self, qname=None, is_global=False): super(AnySimpleType, self).__init__( qname or etree.QName(self._default_qname), is_global) def __call__(self, *args, **kwargs): """Return the xmlvalue for the given value. Expects only one argument 'value'. The args, kwargs handling is done here manually so that we can return readable error messages instead of only '__call__ takes x arguments' """ num_args = len(args) + len(kwargs) if num_args != 1: raise TypeError(( '%s() takes exactly 1 argument (%d given). ' + 'Simple types expect only a single value argument' ) % (self.__class__.__name__, num_args)) if kwargs and 'value' not in kwargs: raise TypeError(( '%s() got an unexpected keyword argument %r. ' + 'Simple types expect only a single value argument' ) % (self.__class__.__name__, next(six.iterkeys(kwargs)))) value = args[0] if args else kwargs['value'] return self.xmlvalue(value) def __eq__(self, other): return ( other is not None and self.__class__ == other.__class__ and self.__dict__ == other.__dict__) def __str__(self): return '%s(value)' % (self.__class__.__name__) def parse_xmlelement(self, xmlelement, schema=None, allow_none=True, context=None): if xmlelement.text is None: return try: return self.pythonvalue(xmlelement.text) except (TypeError, ValueError): logger.exception("Error during xml -> python translation") return None def pythonvalue(self, xmlvalue): raise NotImplementedError( '%s.pytonvalue() not implemented' % self.__class__.__name__) def render(self, parent, value, xsd_type=None, render_path=None): parent.text = self.xmlvalue(value) def signature(self, schema=None, standalone=True): return self.get_prefixed_name(schema) def validate(self, value, required=False): if required and value is None: raise ValidationError("Value is required") def xmlvalue(self, value): raise NotImplementedError( '%s.xmlvalue() not implemented' % self.__class__.__name__)
zeep-adv
/zeep-adv-1.4.4.tar.gz/zeep-adv-1.4.4/src/zeep/xsd/types/simple.py
simple.py
from zeep.utils import get_base_class from zeep.xsd.types.simple import AnySimpleType __all__ = ['ListType', 'UnionType'] class ListType(AnySimpleType): """Space separated list of simpleType values""" def __init__(self, item_type): self.item_type = item_type super(ListType, self).__init__() def __call__(self, value): return value def render(self, parent, value, xsd_type=None, render_path=None): parent.text = self.xmlvalue(value) def resolve(self): self.item_type = self.item_type.resolve() self.base_class = self.item_type.__class__ return self def xmlvalue(self, value): item_type = self.item_type return ' '.join(item_type.xmlvalue(v) for v in value) def pythonvalue(self, value): if not value: return [] item_type = self.item_type return [item_type.pythonvalue(v) for v in value.split()] def signature(self, schema=None, standalone=True): return self.item_type.signature(schema) + '[]' class UnionType(AnySimpleType): """Simple type existing out of multiple other types""" def __init__(self, item_types): self.item_types = item_types self.item_class = None assert item_types super(UnionType, self).__init__(None) def resolve(self): self.item_types = [item.resolve() for item in self.item_types] base_class = get_base_class(self.item_types) if issubclass(base_class, AnySimpleType) and base_class != AnySimpleType: self.item_class = base_class return self def signature(self, schema=None, standalone=True): return '' def parse_xmlelement(self, xmlelement, schema=None, allow_none=True, context=None): if self.item_class: return self.item_class().parse_xmlelement( xmlelement, schema, allow_none, context) return xmlelement.text def pythonvalue(self, value): if self.item_class: return self.item_class().pythonvalue(value) return value def xmlvalue(self, value): if self.item_class: return self.item_class().xmlvalue(value) return value
zeep-adv
/zeep-adv-1.4.4.tar.gz/zeep-adv-1.4.4/src/zeep/xsd/types/collection.py
collection.py
from zeep.xsd.utils import create_prefixed_name class Type(object): def __init__(self, qname=None, is_global=False): self.qname = qname self.name = qname.localname if qname else None self._resolved = False self.is_global = is_global def get_prefixed_name(self, schema): return create_prefixed_name(self.qname, schema) def accept(self, value): raise NotImplementedError def validate(self, value, required=False): return def parse_kwargs(self, kwargs, name, available_kwargs): value = None name = name or self.name if name in available_kwargs: value = kwargs[name] available_kwargs.remove(name) return {name: value} return {} def parse_xmlelement(self, xmlelement, schema=None, allow_none=True, context=None): raise NotImplementedError( '%s.parse_xmlelement() is not implemented' % self.__class__.__name__) def parsexml(self, xml, schema=None): raise NotImplementedError def render(self, parent, value, xsd_type=None, render_path=None): raise NotImplementedError( '%s.render() is not implemented' % self.__class__.__name__) def resolve(self): raise NotImplementedError( '%s.resolve() is not implemented' % self.__class__.__name__) def extend(self, child): raise NotImplementedError( '%s.extend() is not implemented' % self.__class__.__name__) def restrict(self, child): raise NotImplementedError( '%s.restrict() is not implemented' % self.__class__.__name__) @property def attributes(self): return [] @classmethod def signature(cls, schema=None, standalone=True): return '' class UnresolvedType(Type): def __init__(self, qname, schema): self.qname = qname assert self.qname.text != 'None' self.schema = schema def __repr__(self): return '<%s(qname=%r)>' % (self.__class__.__name__, self.qname.text) def render(self, parent, value, xsd_type=None, render_path=None): raise RuntimeError( "Unable to render unresolved type %s. This is probably a bug." % ( self.qname)) def resolve(self): retval = self.schema.get_type(self.qname) return retval.resolve() class UnresolvedCustomType(Type): def __init__(self, qname, base_type, schema): assert qname is not None self.qname = qname self.name = str(qname.localname) self.schema = schema self.base_type = base_type def __repr__(self): return '<%s(qname=%r, base_type=%r)>' % ( self.__class__.__name__, self.qname.text, self.base_type) def resolve(self): base = self.base_type base = base.resolve() cls_attributes = { '__module__': 'zeep.xsd.dynamic_types', } from zeep.xsd.types.collection import UnionType # FIXME from zeep.xsd.types.simple import AnySimpleType # FIXME if issubclass(base.__class__, UnionType): xsd_type = type(self.name, (base.__class__,), cls_attributes) return xsd_type(base.item_types) elif issubclass(base.__class__, AnySimpleType): xsd_type = type(self.name, (base.__class__,), cls_attributes) return xsd_type(self.qname) else: xsd_type = type(self.name, (base.base_class,), cls_attributes) return xsd_type(self.qname)
zeep-adv
/zeep-adv-1.4.4.tar.gz/zeep-adv-1.4.4/src/zeep/xsd/types/base.py
base.py
import copy import logging from collections import OrderedDict, deque from itertools import chain from cached_property import threaded_cached_property from zeep.exceptions import UnexpectedElementError, XMLParseError from zeep.xsd.const import NotSet, SkipValue, xsi_ns from zeep.xsd.elements import ( Any, AnyAttribute, AttributeGroup, Choice, Element, Group, Sequence) from zeep.xsd.elements.indicators import OrderIndicator from zeep.xsd.types.any import AnyType from zeep.xsd.types.simple import AnySimpleType from zeep.xsd.utils import NamePrefixGenerator from zeep.xsd.valueobjects import CompoundValue logger = logging.getLogger(__name__) __all__ = ['ComplexType'] class ComplexType(AnyType): _xsd_name = None def __init__(self, element=None, attributes=None, restriction=None, extension=None, qname=None, is_global=False): if element and type(element) == list: element = Sequence(element) self.name = self.__class__.__name__ if qname else None self._element = element self._attributes = attributes or [] self._restriction = restriction self._extension = extension super(ComplexType, self).__init__(qname=qname, is_global=is_global) def __call__(self, *args, **kwargs): return self._value_class(*args, **kwargs) @property def accepted_types(self): return (self._value_class,) @threaded_cached_property def _value_class(self): return type( self.__class__.__name__, (CompoundValue,), {'_xsd_type': self, '__module__': 'zeep.objects'}) def __str__(self): return '%s(%s)' % (self.__class__.__name__, self.signature()) @threaded_cached_property def attributes(self): generator = NamePrefixGenerator(prefix='_attr_') result = [] elm_names = {name for name, elm in self.elements if name is not None} for attr in self._attributes_unwrapped: if attr.name is None: name = generator.get_name() elif attr.name in elm_names: name = 'attr__%s' % attr.name else: name = attr.name result.append((name, attr)) return result @threaded_cached_property def _attributes_unwrapped(self): attributes = [] for attr in self._attributes: if isinstance(attr, AttributeGroup): attributes.extend(attr.attributes) else: attributes.append(attr) return attributes @threaded_cached_property def elements(self): """List of tuples containing the element name and the element""" result = [] for name, element in self.elements_nested: if isinstance(element, Element): result.append((element.attr_name, element)) else: result.extend(element.elements) return result @threaded_cached_property def elements_nested(self): """List of tuples containing the element name and the element""" result = [] generator = NamePrefixGenerator() # Handle wsdl:arrayType objects attrs = {attr.qname.text: attr for attr in self._attributes if attr.qname} array_type = attrs.get('{http://schemas.xmlsoap.org/soap/encoding/}arrayType') if array_type: name = generator.get_name() if isinstance(self._element, Group): return [(name, Sequence([ Any(max_occurs='unbounded', restrict=array_type.array_type) ]))] else: return [(name, self._element)] # _element is one of All, Choice, Group, Sequence if self._element: result.append((generator.get_name(), self._element)) return result def parse_xmlelement(self, xmlelement, schema=None, allow_none=True, context=None): """Consume matching xmlelements and call parse() on each :param xmlelement: XML element objects :type xmlelement: lxml.etree._Element :param schema: The parent XML schema :type schema: zeep.xsd.Schema :param allow_none: Allow none :type allow_none: bool :param context: Optional parsing context (for inline schemas) :type context: zeep.xsd.context.XmlParserContext :return: dict or None """ # If this is an empty complexType (<xsd:complexType name="x"/>) if not self.attributes and not self.elements: return None attributes = xmlelement.attrib init_kwargs = OrderedDict() # If this complexType extends a simpleType then we have no nested # elements. Parse it directly via the type object. This is the case # for xsd:simpleContent if isinstance(self._element, Element) and isinstance(self._element.type, AnySimpleType): name, element = self.elements_nested[0] init_kwargs[name] = element.type.parse_xmlelement( xmlelement, schema, name, context=context) else: elements = deque(xmlelement.iterchildren()) if allow_none and len(elements) == 0 and len(attributes) == 0: return # Parse elements. These are always indicator elements (all, choice, # group, sequence) assert len(self.elements_nested) < 2 for name, element in self.elements_nested: try: result = element.parse_xmlelements( elements, schema, name, context=context) if result: init_kwargs.update(result) except UnexpectedElementError as exc: raise XMLParseError(exc.message) # Check if all children are consumed (parsed) if elements: raise XMLParseError("Unexpected element %r" % elements[0].tag) # Parse attributes if attributes: attributes = copy.copy(attributes) for name, attribute in self.attributes: if attribute.name: if attribute.qname.text in attributes: value = attributes.pop(attribute.qname.text) init_kwargs[name] = attribute.parse(value) else: init_kwargs[name] = attribute.parse(attributes) return self(**init_kwargs) def render(self, parent, value, xsd_type=None, render_path=None): """Serialize the given value lxml.Element subelements on the parent element. """ if not render_path: render_path = [self.name] if not self.elements_nested and not self.attributes: return # Render attributes for name, attribute in self.attributes: attr_value = value[name] if name in value else NotSet child_path = render_path + [name] attribute.render(parent, attr_value, child_path) # Render sub elements for name, element in self.elements_nested: if isinstance(element, Element) or element.accepts_multiple: element_value = value[name] if name in value else NotSet child_path = render_path + [name] else: element_value = value child_path = list(render_path) if element_value is SkipValue: continue if isinstance(element, Element): element.type.render(parent, element_value, None, child_path) else: element.render(parent, element_value, child_path) if xsd_type: if xsd_type._xsd_name: parent.set(xsi_ns('type'), xsd_type._xsd_name) if xsd_type.qname: parent.set(xsi_ns('type'), xsd_type.qname) def parse_kwargs(self, kwargs, name, available_kwargs): value = None name = name or self.name if name in available_kwargs: value = kwargs[name] available_kwargs.remove(name) value = self._create_object(value, name) return {name: value} return {} def _create_object(self, value, name): """Return the value as a CompoundValue object""" if value is None: return None if isinstance(value, list): return [self._create_object(val, name) for val in value] if isinstance(value, CompoundValue) or value is SkipValue: return value if isinstance(value, dict): return self(**value) # Check if the valueclass only expects one value, in that case # we can try to automatically create an object for it. if len(self.attributes) + len(self.elements) == 1: return self(value) raise ValueError(( "Error while create XML for complexType '%s': " "Expected instance of type %s, received %r instead." ) % (self.qname or name, self._value_class, type(value))) def resolve(self): """Resolve all sub elements and types""" if self._resolved: return self._resolved self._resolved = self resolved = [] for attribute in self._attributes: value = attribute.resolve() assert value is not None if isinstance(value, list): resolved.extend(value) else: resolved.append(value) self._attributes = resolved if self._extension: self._extension = self._extension.resolve() self._resolved = self.extend(self._extension) elif self._restriction: self._restriction = self._restriction.resolve() self._resolved = self.restrict(self._restriction) if self._element: self._element = self._element.resolve() return self._resolved def extend(self, base): """Create a new complextype instance which is the current type extending the given base type. Used for handling xsd:extension tags TODO: Needs a rewrite where the child containers are responsible for the extend functionality. """ if isinstance(base, ComplexType): base_attributes = base._attributes_unwrapped base_element = base._element else: base_attributes = [] base_element = None attributes = base_attributes + self._attributes_unwrapped # Make sure we don't have duplicate (child is leading) if base_attributes and self._attributes_unwrapped: new_attributes = OrderedDict() for attr in attributes: if isinstance(attr, AnyAttribute): new_attributes['##any'] = attr else: new_attributes[attr.qname.text] = attr attributes = new_attributes.values() # If the base and the current type both have an element defined then # these need to be merged. The base_element might be empty (or just # container a placeholder element). element = [] if self._element and base_element: self._element = self._element.resolve() base_element = base_element.resolve() element = self._element.clone(self._element.name) if isinstance(base_element, OrderIndicator): if isinstance(self._element, Choice): element = base_element.clone(self._element.name) element.append(self._element) elif isinstance(element, OrderIndicator): for item in reversed(base_element): element.insert(0, item) elif isinstance(self._element, Group): raise NotImplementedError('TODO') else: pass # Element (ignore for now) elif self._element or base_element: element = self._element or base_element else: element = Element('_value_1', base) new = self.__class__( element=element, attributes=attributes, qname=self.qname, is_global=self.is_global) return new def restrict(self, base): """Create a new complextype instance which is the current type restricted by the base type. Used for handling xsd:restriction """ attributes = list( chain(base._attributes_unwrapped, self._attributes_unwrapped)) # Make sure we don't have duplicate (self is leading) if base._attributes_unwrapped and self._attributes_unwrapped: new_attributes = OrderedDict() for attr in attributes: if isinstance(attr, AnyAttribute): new_attributes['##any'] = attr else: new_attributes[attr.qname.text] = attr attributes = new_attributes.values() if base._element: base._element.resolve() new = self.__class__( element=self._element or base._element, attributes=attributes, qname=self.qname, is_global=self.is_global) return new.resolve() def signature(self, schema=None, standalone=True): parts = [] for name, element in self.elements_nested: part = element.signature(schema, standalone=False) parts.append(part) for name, attribute in self.attributes: part = '%s: %s' % (name, attribute.signature(schema, standalone=False)) parts.append(part) value = ', '.join(parts) if standalone: return '%s(%s)' % (self.get_prefixed_name(schema), value) else: return value
zeep-adv
/zeep-adv-1.4.4.tar.gz/zeep-adv-1.4.4/src/zeep/xsd/types/complex.py
complex.py
import logging from zeep.utils import qname_attr from zeep.xsd.const import xsd_ns, xsi_ns from zeep.xsd.types.base import Type from zeep.xsd.valueobjects import AnyObject logger = logging.getLogger(__name__) __all__ = ['AnyType'] class AnyType(Type): _default_qname = xsd_ns('anyType') _attributes_unwrapped = [] _element = None def __call__(self, value=None): return value or '' def render(self, parent, value, xsd_type=None, render_path=None): if isinstance(value, AnyObject): if value.xsd_type is None: parent.set(xsi_ns('nil'), 'true') else: value.xsd_type.render(parent, value.value, None, render_path) parent.set(xsi_ns('type'), value.xsd_type.qname) elif hasattr(value, '_xsd_elm'): value._xsd_elm.render(parent, value, render_path) parent.set(xsi_ns('type'), value._xsd_elm.qname) else: parent.text = self.xmlvalue(value) def parse_xmlelement(self, xmlelement, schema=None, allow_none=True, context=None): xsi_type = qname_attr(xmlelement, xsi_ns('type')) xsi_nil = xmlelement.get(xsi_ns('nil')) children = list(xmlelement.getchildren()) # Handle xsi:nil attribute if xsi_nil == 'true': return None # Check if a xsi:type is defined and try to parse the xml according # to that type. if xsi_type and schema: xsd_type = schema.get_type(xsi_type, fail_silently=True) # If we were unable to resolve a type for the xsi:type (due to # buggy soap servers) then we just return the lxml element. if not xsd_type: return children # If the xsd_type is xsd:anyType then we will recurs so ignore # that. if isinstance(xsd_type, self.__class__): return xmlelement.text or None return xsd_type.parse_xmlelement( xmlelement, schema, context=context) # If no xsi:type is set and the element has children then there is # not much we can do. Just return the children elif children: return children elif xmlelement.text is not None: return self.pythonvalue(xmlelement.text) return None def resolve(self): return self def xmlvalue(self, value): return value def pythonvalue(self, value, schema=None): return value
zeep-adv
/zeep-adv-1.4.4.tar.gz/zeep-adv-1.4.4/src/zeep/xsd/types/any.py
any.py
import base64 import datetime import math import re from decimal import Decimal as _Decimal import isodate import pytz import six from zeep.xsd.const import xsd_ns from zeep.xsd.types.any import AnyType from zeep.xsd.types.simple import AnySimpleType class ParseError(ValueError): pass class BuiltinType(object): def __init__(self, qname=None, is_global=False): super(BuiltinType, self).__init__(qname, is_global=True) def check_no_collection(func): def _wrapper(self, value): if isinstance(value, (list, dict, set)): raise ValueError( "The %s type doesn't accept collections as value" % ( self.__class__.__name__)) return func(self, value) return _wrapper ## # Primitive types class String(BuiltinType, AnySimpleType): _default_qname = xsd_ns('string') accepted_types = six.string_types @check_no_collection def xmlvalue(self, value): if isinstance(value, bytes): return value.decode('utf-8') return six.text_type(value if value is not None else '') def pythonvalue(self, value): return value class Boolean(BuiltinType, AnySimpleType): _default_qname = xsd_ns('boolean') accepted_types = (bool,) @check_no_collection def xmlvalue(self, value): return 'true' if value else 'false' def pythonvalue(self, value): """Return True if the 'true' or '1'. 'false' and '0' are legal false values, but we consider everything not true as false. """ return value in ('true', '1') class Decimal(BuiltinType, AnySimpleType): _default_qname = xsd_ns('decimal') accepted_types = (_Decimal, float) + six.string_types @check_no_collection def xmlvalue(self, value): return str(value) def pythonvalue(self, value): return _Decimal(value) class Float(BuiltinType, AnySimpleType): _default_qname = xsd_ns('float') accepted_types = (float, _Decimal) + six.string_types def xmlvalue(self, value): return str(value).upper() def pythonvalue(self, value): return float(value) class Double(BuiltinType, AnySimpleType): _default_qname = xsd_ns('double') accepted_types = (_Decimal, float) + six.string_types @check_no_collection def xmlvalue(self, value): return str(value) def pythonvalue(self, value): return float(value) class Duration(BuiltinType, AnySimpleType): _default_qname = xsd_ns('duration') accepted_types = (isodate.duration.Duration,) + six.string_types @check_no_collection def xmlvalue(self, value): return isodate.duration_isoformat(value) def pythonvalue(self, value): return isodate.parse_duration(value) class DateTime(BuiltinType, AnySimpleType): _default_qname = xsd_ns('dateTime') accepted_types = (datetime.datetime,) + six.string_types @check_no_collection def xmlvalue(self, value): # Bit of a hack, since datetime is a subclass of date we can't just # test it with an isinstance(). And actually, we should not really # care about the type, as long as it has the required attributes if not all(hasattr(value, attr) for attr in ('hour', 'minute', 'second')): value = datetime.datetime.combine(value, datetime.time( getattr(value, 'hour', 0), getattr(value, 'minute', 0), getattr(value, 'second', 0))) if getattr(value, 'microsecond', 0): return isodate.isostrf.strftime(value, '%Y-%m-%dT%H:%M:%S.%f%Z') return isodate.isostrf.strftime(value, '%Y-%m-%dT%H:%M:%S%Z') def pythonvalue(self, value): return isodate.parse_datetime(value) class Time(BuiltinType, AnySimpleType): _default_qname = xsd_ns('time') accepted_types = (datetime.time,) + six.string_types @check_no_collection def xmlvalue(self, value): if value.microsecond: return isodate.isostrf.strftime(value, '%H:%M:%S.%f%Z') return isodate.isostrf.strftime(value, '%H:%M:%S%Z') def pythonvalue(self, value): return isodate.parse_time(value) class Date(BuiltinType, AnySimpleType): _default_qname = xsd_ns('date') accepted_types = (datetime.date,) + six.string_types @check_no_collection def xmlvalue(self, value): if isinstance(value, six.string_types): return value return isodate.isostrf.strftime(value, '%Y-%m-%d') def pythonvalue(self, value): return isodate.parse_date(value) class gYearMonth(BuiltinType, AnySimpleType): """gYearMonth represents a specific gregorian month in a specific gregorian year. Lexical representation: CCYY-MM """ accepted_types = (datetime.date,) + six.string_types _default_qname = xsd_ns('gYearMonth') _pattern = re.compile( r'^(?P<year>-?\d{4,})-(?P<month>\d\d)(?P<timezone>Z|[-+]\d\d:?\d\d)?$') @check_no_collection def xmlvalue(self, value): year, month, tzinfo = value return '%04d-%02d%s' % (year, month, _unparse_timezone(tzinfo)) def pythonvalue(self, value): match = self._pattern.match(value) if not match: raise ParseError() group = match.groupdict() return ( int(group['year']), int(group['month']), _parse_timezone(group['timezone'])) class gYear(BuiltinType, AnySimpleType): """gYear represents a gregorian calendar year. Lexical representation: CCYY """ accepted_types = (datetime.date,) + six.string_types _default_qname = xsd_ns('gYear') _pattern = re.compile(r'^(?P<year>-?\d{4,})(?P<timezone>Z|[-+]\d\d:?\d\d)?$') @check_no_collection def xmlvalue(self, value): year, tzinfo = value return '%04d%s' % (year, _unparse_timezone(tzinfo)) def pythonvalue(self, value): match = self._pattern.match(value) if not match: raise ParseError() group = match.groupdict() return (int(group['year']), _parse_timezone(group['timezone'])) class gMonthDay(BuiltinType, AnySimpleType): """gMonthDay is a gregorian date that recurs, specifically a day of the year such as the third of May. Lexical representation: --MM-DD """ accepted_types = (datetime.date, ) + six.string_types _default_qname = xsd_ns('gMonthDay') _pattern = re.compile( r'^--(?P<month>\d\d)-(?P<day>\d\d)(?P<timezone>Z|[-+]\d\d:?\d\d)?$') @check_no_collection def xmlvalue(self, value): month, day, tzinfo = value return '--%02d-%02d%s' % (month, day, _unparse_timezone(tzinfo)) def pythonvalue(self, value): match = self._pattern.match(value) if not match: raise ParseError() group = match.groupdict() return ( int(group['month']), int(group['day']), _parse_timezone(group['timezone'])) class gDay(BuiltinType, AnySimpleType): """gDay is a gregorian day that recurs, specifically a day of the month such as the 5th of the month Lexical representation: ---DD """ accepted_types = (datetime.date,) + six.string_types _default_qname = xsd_ns('gDay') _pattern = re.compile(r'^---(?P<day>\d\d)(?P<timezone>Z|[-+]\d\d:?\d\d)?$') @check_no_collection def xmlvalue(self, value): day, tzinfo = value return '---%02d%s' % (day, _unparse_timezone(tzinfo)) def pythonvalue(self, value): match = self._pattern.match(value) if not match: raise ParseError() group = match.groupdict() return (int(group['day']), _parse_timezone(group['timezone'])) class gMonth(BuiltinType, AnySimpleType): """gMonth is a gregorian month that recurs every year. Lexical representation: --MM """ accepted_types = (datetime.date,) + six.string_types _default_qname = xsd_ns('gMonth') _pattern = re.compile(r'^--(?P<month>\d\d)(?P<timezone>Z|[-+]\d\d:?\d\d)?$') @check_no_collection def xmlvalue(self, value): month, tzinfo = value return '--%d%s' % (month, _unparse_timezone(tzinfo)) def pythonvalue(self, value): match = self._pattern.match(value) if not match: raise ParseError() group = match.groupdict() return (int(group['month']), _parse_timezone(group['timezone'])) class HexBinary(BuiltinType, AnySimpleType): accepted_types = six.string_types _default_qname = xsd_ns('hexBinary') @check_no_collection def xmlvalue(self, value): return value def pythonvalue(self, value): return value class Base64Binary(BuiltinType, AnySimpleType): accepted_types = six.string_types _default_qname = xsd_ns('base64Binary') @check_no_collection def xmlvalue(self, value): return base64.b64encode(value) def pythonvalue(self, value): return base64.b64decode(value) class AnyURI(BuiltinType, AnySimpleType): accepted_types = six.string_types _default_qname = xsd_ns('anyURI') @check_no_collection def xmlvalue(self, value): return value def pythonvalue(self, value): return value class QName(BuiltinType, AnySimpleType): accepted_types = six.string_types _default_qname = xsd_ns('QName') @check_no_collection def xmlvalue(self, value): return value def pythonvalue(self, value): return value class Notation(BuiltinType, AnySimpleType): accepted_types = six.string_types _default_qname = xsd_ns('NOTATION') ## # Derived datatypes class NormalizedString(String): _default_qname = xsd_ns('normalizedString') class Token(NormalizedString): _default_qname = xsd_ns('token') class Language(Token): _default_qname = xsd_ns('language') class NmToken(Token): _default_qname = xsd_ns('NMTOKEN') class NmTokens(NmToken): _default_qname = xsd_ns('NMTOKENS') class Name(Token): _default_qname = xsd_ns('Name') class NCName(Name): _default_qname = xsd_ns('NCName') class ID(NCName): _default_qname = xsd_ns('ID') class IDREF(NCName): _default_qname = xsd_ns('IDREF') class IDREFS(IDREF): _default_qname = xsd_ns('IDREFS') class Entity(NCName): _default_qname = xsd_ns('ENTITY') class Entities(Entity): _default_qname = xsd_ns('ENTITIES') class Integer(Decimal): _default_qname = xsd_ns('integer') accepted_types = (int, float) + six.string_types def xmlvalue(self, value): return str(value) def pythonvalue(self, value): return int(value) class NonPositiveInteger(Integer): _default_qname = xsd_ns('nonPositiveInteger') class NegativeInteger(Integer): _default_qname = xsd_ns('negativeInteger') class Long(Integer): _default_qname = xsd_ns('long') def pythonvalue(self, value): return long(value) if six.PY2 else int(value) # noqa class Int(Long): _default_qname = xsd_ns('int') class Short(Int): _default_qname = xsd_ns('short') class Byte(Short): """A signed 8-bit integer""" _default_qname = xsd_ns('byte') class NonNegativeInteger(Integer): _default_qname = xsd_ns('nonNegativeInteger') class UnsignedLong(NonNegativeInteger): _default_qname = xsd_ns('unsignedLong') class UnsignedInt(UnsignedLong): _default_qname = xsd_ns('unsignedInt') class UnsignedShort(UnsignedInt): _default_qname = xsd_ns('unsignedShort') class UnsignedByte(UnsignedShort): _default_qname = xsd_ns('unsignedByte') class PositiveInteger(NonNegativeInteger): _default_qname = xsd_ns('positiveInteger') ## # Other def _parse_timezone(val): """Return a pytz.tzinfo object""" if not val: return if val == 'Z' or val == '+00:00': return pytz.utc negative = val.startswith('-') minutes = int(val[-2:]) minutes += int(val[1:3]) * 60 if negative: minutes = 0 - minutes return pytz.FixedOffset(minutes) def _unparse_timezone(tzinfo): if not tzinfo: return '' if tzinfo == pytz.utc: return 'Z' hours = math.floor(tzinfo._minutes / 60) minutes = tzinfo._minutes % 60 if hours > 0: return '+%02d:%02d' % (hours, minutes) return '-%02d:%02d' % (abs(hours), minutes) _types = [ # Primitive String, Boolean, Decimal, Float, Double, Duration, DateTime, Time, Date, gYearMonth, gYear, gMonthDay, gDay, gMonth, HexBinary, Base64Binary, AnyURI, QName, Notation, # Derived NormalizedString, Token, Language, NmToken, NmTokens, Name, NCName, ID, IDREF, IDREFS, Entity, Entities, Integer, NonPositiveInteger, # noqa NegativeInteger, Long, Int, Short, Byte, NonNegativeInteger, # noqa UnsignedByte, UnsignedInt, UnsignedLong, UnsignedShort, PositiveInteger, # Other AnyType, AnySimpleType, ] default_types = { cls._default_qname: cls(is_global=True) for cls in _types }
zeep-adv
/zeep-adv-1.4.4.tar.gz/zeep-adv-1.4.4/src/zeep/xsd/types/builtins.py
builtins.py
Authors ======= * Michael van Tellingen Contributors ============ * Kateryna Burda * Alexey Stepanov * Marco Vellinga * jaceksnet * Andrew Serong * vashek * Seppo Yli-Olli * Sam Denton * Dani Möller * Julien Delasoie * Christian González * bjarnagin * mcordes * Joeri Bekker * Bartek Wójcicki * jhorman * fiebiga * David Baumgold * Antonio Cuni * Alexandre de Mari * Nicolas Evrard * Eric Wong * Jason Vertrees * Falldog * Matt Grimm (mgrimm) * Marek Wywiał * btmanm * Caleb Salt * Ondřej Lanč * Jan Murre * Stefano Parmesan * Julien Marechal * Dave Wapstra * Mike Fiedler * Derek Harland * Bruno Duyé * Christoph Heuel * Ben Tucker * Eric Waller * Falk Schuetzenmeister * Jon Jenkins * OrangGeeGee * Raymond Piller * Zoltan Benedek * Øyvind Heddeland Instefjord
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/CONTRIBUTORS.rst
CONTRIBUTORS.rst
======================== Zeep: Python SOAP client ======================== This is a fork of (mvantellingen/python-zeep)[https://github.com/mvantellingen/python-zeep]. For now it just runs the plugins after signing when making the request, and before when processing the response. We did this because we needed to encrypt in those moments and we didn't saw a way to do it. So we used plugins to do it, and needed to encrypt after sign in the request and before in the response. Maybe in the future we could implement a "Encryption Plugin" and return the "Normal Plugin" execution where it belongs. A fast and modern Python SOAP client Highlights: * Compatible with Python 2.7, 3.3, 3.4, 3.5, 3.6, 3.7 and PyPy * Build on top of lxml and requests * Support for Soap 1.1, Soap 1.2 and HTTP bindings * Support for WS-Addressing headers * Support for WSSE (UserNameToken / x.509 signing) * Support for tornado async transport via gen.coroutine (Python 2.7+) * Support for asyncio via aiohttp (Python 3.5+) * Experimental support for XOP messages Please see for more information the documentation at http://docs.python-zeep.org/ .. start-no-pypi Status ------ .. image:: https://readthedocs.org/projects/python-zeep/badge/?version=latest :target: https://readthedocs.org/projects/python-zeep/ .. image:: https://dev.azure.com/mvantellingen/zeep/_apis/build/status/python-zeep?branchName=master :target: https://dev.azure.com/mvantellingen/zeep/_build?definitionId=1 .. image:: http://codecov.io/github/mvantellingen/python-zeep/coverage.svg?branch=master :target: http://codecov.io/github/mvantellingen/python-zeep?branch=master .. image:: https://img.shields.io/pypi/v/zeep.svg :target: https://pypi.python.org/pypi/zeep/ .. end-no-pypi Installation ------------ .. code-block:: bash pip install zeep Usage ----- .. code-block:: python from zeep import Client client = Client('tests/wsdl_files/example.rst') client.service.ping() To quickly inspect a WSDL file use:: python -m zeep <url-to-wsdl> Please see the documentation at http://docs.python-zeep.org for more information. Support ======= If you want to report a bug then please first read http://docs.python-zeep.org/en/master/reporting_bugs.html Please only report bugs and not support requests to the GitHub issue tracker.
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/README.rst
README.rst
from __future__ import absolute_import, print_function import argparse import logging import logging.config import time import requests from six.moves.urllib.parse import urlparse from zeep.cache import SqliteCache from zeep.client import Client from zeep.settings import Settings from zeep.transports import Transport logger = logging.getLogger("zeep") def parse_arguments(args=None): parser = argparse.ArgumentParser(description="Zeep: The SOAP client") parser.add_argument( "wsdl_file", type=str, help="Path or URL to the WSDL file", default=None ) parser.add_argument("--cache", action="store_true", help="Enable cache") parser.add_argument( "--no-verify", action="store_true", help="Disable SSL verification" ) parser.add_argument("--verbose", action="store_true", help="Enable verbose output") parser.add_argument( "--profile", help="Enable profiling and save output to given file" ) parser.add_argument( "--no-strict", action="store_true", default=False, help="Disable strict mode" ) return parser.parse_args(args) def main(args): if args.verbose: logging.config.dictConfig( { "version": 1, "formatters": {"verbose": {"format": "%(name)20s: %(message)s"}}, "handlers": { "console": { "level": "DEBUG", "class": "logging.StreamHandler", "formatter": "verbose", } }, "loggers": { "zeep": { "level": "DEBUG", "propagate": True, "handlers": ["console"], } }, } ) if args.profile: import cProfile profile = cProfile.Profile() profile.enable() cache = SqliteCache() if args.cache else None session = requests.Session() if args.no_verify: session.verify = False result = urlparse(args.wsdl_file) if result.username or result.password: session.auth = (result.username, result.password) transport = Transport(cache=cache, session=session) st = time.time() settings = Settings(strict=not args.no_strict) client = Client(args.wsdl_file, transport=transport, settings=settings) logger.debug("Loading WSDL took %sms", (time.time() - st) * 1000) if args.profile: profile.disable() profile.dump_stats(args.profile) client.wsdl.dump() if __name__ == "__main__": args = parse_arguments() main(args)
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/__main__.py
__main__.py
import threading from contextlib import contextmanager import attr @attr.s(slots=True) class Settings(object): """ :param strict: boolean to indicate if the lxml should be parsed a 'strict'. If false then the recover mode is enabled which tries to parse invalid XML as best as it can. :type strict: boolean :param raw_response: boolean to skip the parsing of the XML response by zeep but instead returning the raw data :param forbid_dtd: disallow XML with a <!DOCTYPE> processing instruction :type forbid_dtd: bool :param forbid_entities: disallow XML with <!ENTITY> declarations inside the DTD :type forbid_entities: bool :param forbid_external: disallow any access to remote or local resources in external entities or DTD and raising an ExternalReferenceForbidden exception when a DTD or entity references an external resource. :type forbid_entities: bool :param xml_huge_tree: disable lxml/libxml2 security restrictions and support very deep trees and very long text content :param force_https: Force all connections to HTTPS if the WSDL is also loaded from an HTTPS endpoint. (default: true) :type force_https: bool :param extra_http_headers: Additional HTTP headers to be sent to the transport. This can be used in combination with the context manager approach to add http headers for specific calls. :type extra_headers: list :param xsd_ignore_sequence_order: boolean to indicate whether to enforce sequence order when parsing complex types. This is a workaround for servers that don't respect sequence order. :type xsd_ignore_sequence_order: boolean """ strict = attr.ib(default=True) raw_response = attr.ib(default=False) # transport force_https = attr.ib(default=True) extra_http_headers = attr.ib(default=None) # lxml processing xml_huge_tree = attr.ib(default=False) forbid_dtd = attr.ib(default=False) forbid_entities = attr.ib(default=True) forbid_external = attr.ib(default=True) # xsd workarounds xsd_ignore_sequence_order = attr.ib(default=False) _tls = attr.ib(default=attr.Factory(threading.local)) @contextmanager def __call__(self, **options): current = {} for key, value in options.items(): current[key] = getattr(self, key) setattr(self._tls, key, value) yield for key, value in current.items(): default = getattr(self, key) if value == default: delattr(self._tls, key) else: setattr(self._tls, key, value) def __getattribute__(self, key): if key != "_tls" and hasattr(self._tls, key): return getattr(self._tls, key) return super(Settings, self).__getattribute__(key)
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/settings.py
settings.py
import base64 import datetime import errno import logging import os import threading from contextlib import contextmanager import appdirs import pytz import six # The sqlite3 is not available on Google App Engine so we handle the # ImportError here and set the sqlite3 var to None. # See https://github.com/mvantellingen/python-zeep/issues/243 try: import sqlite3 except ImportError: sqlite3 = None logger = logging.getLogger(__name__) class Base(object): def add(self, url, content): raise NotImplemented() def get(self, url): raise NotImplemented() class InMemoryCache(Base): """Simple in-memory caching using dict lookup with support for timeouts""" _cache = {} # global cache, thread-safe by default def __init__(self, timeout=3600): self._timeout = timeout def add(self, url, content): logger.debug("Caching contents of %s", url) if not isinstance(content, (str, bytes)): raise TypeError( "a bytes-like object is required, not {}".format(type(content).__name__) ) self._cache[url] = (datetime.datetime.utcnow(), content) def get(self, url): try: created, content = self._cache[url] except KeyError: pass else: if not _is_expired(created, self._timeout): logger.debug("Cache HIT for %s", url) return content logger.debug("Cache MISS for %s", url) return None class SqliteCache(Base): """Cache contents via an sqlite database on the filesystem""" _version = "1" def __init__(self, path=None, timeout=3600): if sqlite3 is None: raise RuntimeError("sqlite3 module is required for the SqliteCache") # No way we can support this when we want to achieve thread safety if path == ":memory:": raise ValueError( "The SqliteCache doesn't support :memory: since it is not " + "thread-safe. Please use zeep.cache.InMemoryCache()" ) self._lock = threading.RLock() self._timeout = timeout self._db_path = path if path else _get_default_cache_path() # Initialize db with self.db_connection() as conn: cursor = conn.cursor() cursor.execute( """ CREATE TABLE IF NOT EXISTS request (created timestamp, url text, content text) """ ) conn.commit() @contextmanager def db_connection(self): with self._lock: connection = sqlite3.connect( self._db_path, detect_types=sqlite3.PARSE_DECLTYPES ) yield connection connection.close() def add(self, url, content): logger.debug("Caching contents of %s", url) data = self._encode_data(content) with self.db_connection() as conn: cursor = conn.cursor() cursor.execute("DELETE FROM request WHERE url = ?", (url,)) cursor.execute( "INSERT INTO request (created, url, content) VALUES (?, ?, ?)", (datetime.datetime.utcnow(), url, data), ) conn.commit() def get(self, url): with self.db_connection() as conn: cursor = conn.cursor() cursor.execute("SELECT created, content FROM request WHERE url=?", (url,)) rows = cursor.fetchall() if rows: created, data = rows[0] if not _is_expired(created, self._timeout): logger.debug("Cache HIT for %s", url) return self._decode_data(data) logger.debug("Cache MISS for %s", url) def _encode_data(self, data): data = base64.b64encode(data) if six.PY2: return buffer(self._version_string + data) # noqa return self._version_string + data def _decode_data(self, data): if six.PY2: data = str(data) if data.startswith(self._version_string): return base64.b64decode(data[len(self._version_string) :]) @property def _version_string(self): prefix = u"$ZEEP:%s$" % self._version return bytes(prefix.encode("ascii")) def _is_expired(value, timeout): """Return boolean if the value is expired""" if timeout is None: return False now = datetime.datetime.utcnow().replace(tzinfo=pytz.utc) max_age = value.replace(tzinfo=pytz.utc) max_age += datetime.timedelta(seconds=timeout) return now > max_age def _get_default_cache_path(): path = appdirs.user_cache_dir("zeep", False) try: os.makedirs(path) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise return os.path.join(path, "cache.db")
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/cache.py
cache.py
import logging from zeep.proxy import ServiceProxy from zeep.settings import Settings from zeep.transports import Transport from zeep.wsdl import Document logger = logging.getLogger(__name__) class Factory(object): def __init__(self, types, kind, namespace): self._method = getattr(types, "get_%s" % kind) if namespace in types.namespaces: self._ns = namespace else: self._ns = types.get_ns_prefix(namespace) def __getattr__(self, key): """Return the complexType or simpleType for the given localname. :rtype: zeep.xsd.ComplexType or zeep.xsd.AnySimpleType """ return self[key] def __getitem__(self, key): """Return the complexType or simpleType for the given localname. :rtype: zeep.xsd.ComplexType or zeep.xsd.AnySimpleType """ return self._method("{%s}%s" % (self._ns, key)) class Client(object): """The zeep Client. :param wsdl: :param wsse: :param transport: Custom transport class. :param service_name: The service name for the service binding. Defaults to the first service in the WSDL document. :param port_name: The port name for the default binding. Defaults to the first port defined in the service element in the WSDL document. :param plugins: a list of Plugin instances :param settings: a zeep.Settings() object """ def __init__( self, wsdl, wsse=None, transport=None, service_name=None, port_name=None, plugins=None, settings=None, ): if not wsdl: raise ValueError("No URL given for the wsdl") self.settings = settings or Settings() self.transport = transport if transport is not None else Transport() self.wsdl = Document(wsdl, self.transport, settings=self.settings) self.wsse = wsse self.plugins = plugins if plugins is not None else [] self._default_service = None self._default_service_name = service_name self._default_port_name = port_name self._default_soapheaders = None @property def namespaces(self): return self.wsdl.types.prefix_map @property def service(self): """The default ServiceProxy instance :rtype: ServiceProxy """ if self._default_service: return self._default_service self._default_service = self.bind( service_name=self._default_service_name, port_name=self._default_port_name ) if not self._default_service: raise ValueError( "There is no default service defined. This is usually due to " "missing wsdl:service definitions in the WSDL" ) return self._default_service def bind(self, service_name=None, port_name=None): """Create a new ServiceProxy for the given service_name and port_name. The default ServiceProxy instance (`self.service`) always referes to the first service/port in the wsdl Document. Use this when a specific port is required. """ if not self.wsdl.services: return service = self._get_service(service_name) port = self._get_port(service, port_name) return ServiceProxy(self, port.binding, **port.binding_options) def create_service(self, binding_name, address): """Create a new ServiceProxy for the given binding name and address. :param binding_name: The QName of the binding :param address: The address of the endpoint """ try: binding = self.wsdl.bindings[binding_name] except KeyError: raise ValueError( "No binding found with the given QName. Available bindings " "are: %s" % (", ".join(self.wsdl.bindings.keys())) ) return ServiceProxy(self, binding, address=address) def create_message(self, service, operation_name, *args, **kwargs): """Create the payload for the given operation. :rtype: lxml.etree._Element """ envelope, http_headers = service._binding._create( operation_name, args, kwargs, client=self ) return envelope def type_factory(self, namespace): """Return a type factory for the given namespace. Example:: factory = client.type_factory('ns0') user = factory.User(name='John') :rtype: Factory """ return Factory(self.wsdl.types, "type", namespace) def get_type(self, name): """Return the type for the given qualified name. :rtype: zeep.xsd.ComplexType or zeep.xsd.AnySimpleType """ return self.wsdl.types.get_type(name) def get_element(self, name): """Return the element for the given qualified name. :rtype: zeep.xsd.Element """ return self.wsdl.types.get_element(name) def set_ns_prefix(self, prefix, namespace): """Set a shortcut for the given namespace. """ self.wsdl.types.set_ns_prefix(prefix, namespace) def set_default_soapheaders(self, headers): """Set the default soap headers which will be automatically used on all calls. Note that if you pass custom soapheaders using a list then you will also need to use that during the operations. Since mixing these use cases isn't supported (yet). """ self._default_soapheaders = headers def _get_port(self, service, name): if name: port = service.ports.get(name) if not port: raise ValueError("Port not found") else: port = list(service.ports.values())[0] return port def _get_service(self, name): if name: service = self.wsdl.services.get(name) if not service: raise ValueError("Service not found") else: service = next(iter(self.wsdl.services.values()), None) return service class CachingClient(Client): """Shortcut to create a caching client, for the lazy people. This enables the SqliteCache by default in the transport as was the default in earlier versions of zeep. """ def __init__(self, *args, **kwargs): # Don't use setdefault since we want to lazily init the Transport cls from zeep.cache import SqliteCache kwargs["transport"] = kwargs.get("transport") or Transport(cache=SqliteCache()) super(CachingClient, self).__init__(*args, **kwargs)
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/client.py
client.py
import copy import itertools import logging logger = logging.getLogger(__name__) class OperationProxy(object): def __init__(self, service_proxy, operation_name): self._proxy = service_proxy self._op_name = operation_name @property def __doc__(self): return str(self._proxy._binding._operations[self._op_name]) def __call__(self, *args, **kwargs): """Call the operation with the given args and kwargs. :rtype: zeep.xsd.CompoundValue """ # Merge the default _soapheaders with the passed _soapheaders if self._proxy._client._default_soapheaders: op_soapheaders = kwargs.get("_soapheaders") if op_soapheaders: soapheaders = copy.deepcopy(self._proxy._client._default_soapheaders) if type(op_soapheaders) != type(soapheaders): raise ValueError("Incompatible soapheaders definition") if isinstance(soapheaders, list): soapheaders.extend(op_soapheaders) else: soapheaders.update(op_soapheaders) else: soapheaders = self._proxy._client._default_soapheaders kwargs["_soapheaders"] = soapheaders return self._proxy._binding.send( self._proxy._client, self._proxy._binding_options, self._op_name, args, kwargs, ) class ServiceProxy(object): def __init__(self, client, binding, **binding_options): self._client = client self._binding_options = binding_options self._binding = binding self._operations = { name: OperationProxy(self, name) for name in self._binding.all() } def __getattr__(self, key): """Return the OperationProxy for the given key. :rtype: OperationProxy() """ return self[key] def __getitem__(self, key): """Return the OperationProxy for the given key. :rtype: OperationProxy() """ try: return self._operations[key] except KeyError: raise AttributeError("Service has no operation %r" % key) def __iter__(self): """ Return iterator over the services and their callables. """ return iter(self._operations.items()) def __dir__(self): """ Return the names of the operations. """ return list(itertools.chain(dir(super(ServiceProxy, self)), self._operations))
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/proxy.py
proxy.py
import os.path from defusedxml.lxml import fromstring from lxml import etree from six.moves.urllib.parse import urljoin, urlparse, urlunparse from zeep.exceptions import XMLSyntaxError from zeep.settings import Settings class ImportResolver(etree.Resolver): """Custom lxml resolve to use the transport object""" def __init__(self, transport): self.transport = transport def resolve(self, url, pubid, context): if urlparse(url).scheme in ("http", "https"): content = self.transport.load(url) return self.resolve_string(content, context) def parse_xml(content, transport, base_url=None, settings=None): """Parse an XML string and return the root Element. :param content: The XML string :type content: str :param transport: The transport instance to load imported documents :type transport: zeep.transports.Transport :param base_url: The base url of the document, used to make relative lookups absolute. :type base_url: str :param settings: A zeep.settings.Settings object containing parse settings. :type settings: zeep.settings.Settings :returns: The document root :rtype: lxml.etree._Element """ settings = settings or Settings() recover = not settings.strict parser = etree.XMLParser( remove_comments=True, resolve_entities=False, recover=recover, huge_tree=settings.xml_huge_tree, ) parser.resolvers.add(ImportResolver(transport)) try: return fromstring( content, parser=parser, base_url=base_url, forbid_dtd=settings.forbid_dtd, forbid_entities=settings.forbid_entities, ) except etree.XMLSyntaxError as exc: raise XMLSyntaxError( "Invalid XML content received (%s)" % exc.msg, content=content ) def load_external(url, transport, base_url=None, settings=None): """Load an external XML document. :param url: :param transport: :param base_url: :param settings: A zeep.settings.Settings object containing parse settings. :type settings: zeep.settings.Settings """ settings = settings or Settings() if hasattr(url, "read"): content = url.read() else: if base_url: url = absolute_location(url, base_url) content = transport.load(url) return parse_xml(content, transport, base_url, settings=settings) def normalize_location(settings, url, base_url): """Return a 'normalized' url for the given url. This will make the url absolute and force it to https when that setting is enabled. """ # Python 2.7 doesn't accept None to urlparse() calls, but Python 3 does. # So as a guard convert None to '' here so that we can't introduce errors in # Python 2.7 like #930. Can be removed when we drop Python 2 support. if url is None: url = "" if base_url: url = absolute_location(url, base_url) if base_url and settings.force_https: base_url_parts = urlparse(base_url) url_parts = urlparse(url) if ( base_url_parts.netloc == url_parts.netloc and base_url_parts.scheme != url_parts.scheme ): url = urlunparse(("https",) + url_parts[1:]) return url def absolute_location(location, base): """Make an url absolute (if it is optional) via the passed base url. :param location: The (relative) url :type location: str :param base: The base location :type base: str :returns: An absolute URL :rtype: str """ if location == base: return location if urlparse(location).scheme in ("http", "https", "file"): return location if base and urlparse(base).scheme in ("http", "https", "file"): return urljoin(base, location) else: if os.path.isabs(location): return location if base: return os.path.realpath(os.path.join(os.path.dirname(base), location)) return location def is_relative_path(value): """Check if the given value is a relative path :param value: The value :type value: str :returns: Boolean indicating if the url is relative. If it is absolute then False is returned. :rtype: boolean """ if urlparse(value).scheme in ("http", "https", "file"): return False return not os.path.isabs(value)
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/loader.py
loader.py
from collections import deque class Plugin(object): """Base plugin""" def ingress(self, envelope, http_headers, operation): """Override to update the envelope or http headers when receiving a message. :param envelope: The envelope as XML node :param http_headers: Dict with the HTTP headers """ return envelope, http_headers def egress(self, envelope, http_headers, operation, binding_options): """Override to update the envelope or http headers when sending a message. :param envelope: The envelope as XML node :param http_headers: Dict with the HTTP headers :param operation: The associated Operation instance :param binding_options: Binding specific options for the operation """ return envelope, http_headers def apply_egress(client, envelope, http_headers, operation, binding_options): for plugin in client.plugins: result = plugin.egress(envelope, http_headers, operation, binding_options) if result is not None: envelope, http_headers = result return envelope, http_headers def apply_ingress(client, envelope, http_headers, operation): for plugin in client.plugins: result = plugin.ingress(envelope, http_headers, operation) if result is not None: envelope, http_headers = result return envelope, http_headers class HistoryPlugin(object): def __init__(self, maxlen=1): self._buffer = deque([], maxlen) @property def last_sent(self): last_tx = self._buffer[-1] if last_tx: return last_tx["sent"] @property def last_received(self): last_tx = self._buffer[-1] if last_tx: return last_tx["received"] def ingress(self, envelope, http_headers, operation): last_tx = self._buffer[-1] last_tx["received"] = {"envelope": envelope, "http_headers": http_headers} def egress(self, envelope, http_headers, operation, binding_options): self._buffer.append( { "received": None, "sent": {"envelope": envelope, "http_headers": http_headers}, } )
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/plugins.py
plugins.py
import cgi import inspect from lxml import etree from zeep.exceptions import XMLParseError from zeep.ns import XSD def qname_attr(node, attr_name, target_namespace=None): value = node.get(attr_name) if value is not None: return as_qname(value, node.nsmap, target_namespace) def as_qname(value, nsmap, target_namespace=None): """Convert the given value to a QName""" value = value.strip() # some xsd's contain leading/trailing spaces if ":" in value: prefix, local = value.split(":") # The xml: prefix is always bound to the XML namespace, see # https://www.w3.org/TR/xml-names/ if prefix == "xml": namespace = "http://www.w3.org/XML/1998/namespace" else: namespace = nsmap.get(prefix) if not namespace: raise XMLParseError("No namespace defined for %r (%r)" % (prefix, value)) # Workaround for https://github.com/mvantellingen/python-zeep/issues/349 if not local: return etree.QName(XSD, "anyType") return etree.QName(namespace, local) if target_namespace: return etree.QName(target_namespace, value) if nsmap.get(None): return etree.QName(nsmap[None], value) return etree.QName(value) def findall_multiple_ns(node, name, namespace_sets): result = [] for nsmap in namespace_sets: result.extend(node.findall(name, namespaces=nsmap)) return result def get_version(): from zeep import __version__ # cyclic import return __version__ def get_base_class(objects): """Return the best base class for multiple objects. Implementation is quick and dirty, might be done better.. ;-) """ bases = [inspect.getmro(obj.__class__)[::-1] for obj in objects] num_objects = len(objects) max_mro = max(len(mro) for mro in bases) base_class = None for i in range(max_mro): try: if len({bases[j][i] for j in range(num_objects)}) > 1: break except IndexError: break base_class = bases[0][i] return base_class def detect_soap_env(envelope): root_tag = etree.QName(envelope) return root_tag.namespace def get_media_type(value): """Parse a HTTP content-type header and return the media-type""" main_value, parameters = cgi.parse_header(value) return main_value.lower()
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/utils.py
utils.py
import logging import os from contextlib import contextmanager import requests from six.moves.urllib.parse import urlparse from zeep.utils import get_media_type, get_version from zeep.wsdl.utils import etree_to_string class Transport(object): """The transport object handles all communication to the SOAP server. :param cache: The cache object to be used to cache GET requests :param timeout: The timeout for loading wsdl and xsd documents. :param operation_timeout: The timeout for operations (POST/GET). By default this is None (no timeout). :param session: A :py:class:`request.Session()` object (optional) """ def __init__(self, cache=None, timeout=300, operation_timeout=None, session=None): self.cache = cache self.load_timeout = timeout self.operation_timeout = operation_timeout self.logger = logging.getLogger(__name__) self.session = session or requests.Session() self.session.headers["User-Agent"] = "Zeep/%s (www.python-zeep.org)" % ( get_version() ) def get(self, address, params, headers): """Proxy to requests.get() :param address: The URL for the request :param params: The query parameters :param headers: a dictionary with the HTTP headers. """ response = self.session.get( address, params=params, headers=headers, timeout=self.operation_timeout ) return response def post(self, address, message, headers): """Proxy to requests.posts() :param address: The URL for the request :param message: The content for the body :param headers: a dictionary with the HTTP headers. """ if self.logger.isEnabledFor(logging.DEBUG): log_message = message if isinstance(log_message, bytes): log_message = log_message.decode("utf-8") self.logger.debug("HTTP Post to %s:\n%s", address, log_message) response = self.session.post( address, data=message, headers=headers, timeout=self.operation_timeout ) if self.logger.isEnabledFor(logging.DEBUG): media_type = get_media_type( response.headers.get("Content-Type", "text/xml") ) if media_type == "multipart/related": log_message = response.content else: log_message = response.content if isinstance(log_message, bytes): log_message = log_message.decode(response.encoding or "utf-8") self.logger.debug( "HTTP Response from %s (status: %d):\n%s", address, response.status_code, log_message, ) return response def post_xml(self, address, envelope, headers): """Post the envelope xml element to the given address with the headers. This method is intended to be overriden if you want to customize the serialization of the xml element. By default the body is formatted and encoded as utf-8. See ``zeep.wsdl.utils.etree_to_string``. """ message = etree_to_string(envelope) return self.post(address, message, headers) def load(self, url): """Load the content from the given URL""" if not url: raise ValueError("No url given to load") scheme = urlparse(url).scheme if scheme in ("http", "https"): if self.cache: response = self.cache.get(url) if response: return bytes(response) content = self._load_remote_data(url) if self.cache: self.cache.add(url, content) return content elif scheme == "file": if url.startswith("file://"): url = url[7:] with open(os.path.expanduser(url), "rb") as fh: return fh.read() def _load_remote_data(self, url): self.logger.debug("Loading remote data from: %s", url) response = self.session.get(url, timeout=self.load_timeout) response.raise_for_status() return response.content @contextmanager def settings(self, timeout=None): """Context manager to temporarily overrule options. Example:: transport = zeep.Transport() with transport.settings(timeout=10): client.service.fast_call() :param timeout: Set the timeout for POST/GET operations (not used for loading external WSDL or XSD documents) """ old_timeout = self.operation_timeout self.operation_timeout = timeout yield self.operation_timeout = old_timeout
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/transports.py
transports.py
class Error(Exception): def __init__(self, message=""): super(Exception, self).__init__(message) self.message = message def __repr__(self): return "%s(%r)" % (self.__class__.__name__, self.message) class XMLSyntaxError(Error): def __init__(self, *args, **kwargs): self.content = kwargs.pop("content", None) super(XMLSyntaxError, self).__init__(*args, **kwargs) class XMLParseError(Error): def __init__(self, *args, **kwargs): self.filename = kwargs.pop("filename", None) self.sourceline = kwargs.pop("sourceline", None) super(XMLParseError, self).__init__(*args, **kwargs) def __str__(self): location = None if self.filename and self.sourceline: location = "%s:%s" % (self.filename, self.sourceline) if location: return "%s (%s)" % (self.message, location) return self.message class UnexpectedElementError(Error): pass class WsdlSyntaxError(Error): pass class TransportError(Error): def __init__(self, message="", status_code=0, content=None): super(TransportError, self).__init__(message) self.status_code = status_code self.content = content class LookupError(Error): def __init__(self, *args, **kwargs): self.qname = kwargs.pop("qname", None) self.item_name = kwargs.pop("item_name", None) self.location = kwargs.pop("location", None) super(LookupError, self).__init__(*args, **kwargs) class NamespaceError(Error): pass class Fault(Error): def __init__(self, message, code=None, actor=None, detail=None, subcodes=None): super(Fault, self).__init__(message) self.message = message self.code = code self.actor = actor self.detail = detail self.subcodes = subcodes class ZeepWarning(RuntimeWarning): pass class ValidationError(Error): def __init__(self, *args, **kwargs): self.path = kwargs.pop("path", []) super(ValidationError, self).__init__(*args, **kwargs) def __str__(self): if self.path: path = ".".join(str(x) for x in self.path) return "%s (%s)" % (self.message, path) return self.message class SignatureVerificationFailed(Error): pass class IncompleteMessage(Error): pass class IncompleteOperation(Error): pass
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/exceptions.py
exceptions.py
from lxml import etree from zeep.exceptions import IncompleteMessage, LookupError, NamespaceError from zeep.utils import qname_attr from zeep.wsdl import definitions NSMAP = { "wsdl": "http://schemas.xmlsoap.org/wsdl/", "wsaw": "http://www.w3.org/2006/05/addressing/wsdl", "wsam": "http://www.w3.org/2007/05/addressing/metadata", } def parse_abstract_message(wsdl, xmlelement): """Create an AbstractMessage object from a xml element. Definition:: <definitions .... > <message name="nmtoken"> * <part name="nmtoken" element="qname"? type="qname"?/> * </message> </definitions> :param wsdl: The parent definition instance :type wsdl: zeep.wsdl.wsdl.Definition :param xmlelement: The XML node :type xmlelement: lxml.etree._Element :rtype: zeep.wsdl.definitions.AbstractMessage """ tns = wsdl.target_namespace message_name = qname_attr(xmlelement, "name", tns) parts = [] for part in xmlelement.findall("wsdl:part", namespaces=NSMAP): part_name = part.get("name") part_element = qname_attr(part, "element") part_type = qname_attr(part, "type") try: if part_element is not None: part_element = wsdl.types.get_element(part_element) if part_type is not None: part_type = wsdl.types.get_type(part_type) except (NamespaceError, LookupError): raise IncompleteMessage( ( "The wsdl:message for %r contains an invalid part (%r): " "invalid xsd type or elements" ) % (message_name.text, part_name) ) part = definitions.MessagePart(part_element, part_type) parts.append((part_name, part)) # Create the object, add the parts and return it msg = definitions.AbstractMessage(message_name) for part_name, part in parts: msg.add_part(part_name, part) return msg def parse_abstract_operation(wsdl, xmlelement): """Create an AbstractOperation object from a xml element. This is called from the parse_port_type function since the abstract operations are part of the port type element. Definition:: <wsdl:operation name="nmtoken">* <wsdl:documentation .... /> ? <wsdl:input name="nmtoken"? message="qname">? <wsdl:documentation .... /> ? </wsdl:input> <wsdl:output name="nmtoken"? message="qname">? <wsdl:documentation .... /> ? </wsdl:output> <wsdl:fault name="nmtoken" message="qname"> * <wsdl:documentation .... /> ? </wsdl:fault> </wsdl:operation> :param wsdl: The parent definition instance :type wsdl: zeep.wsdl.wsdl.Definition :param xmlelement: The XML node :type xmlelement: lxml.etree._Element :rtype: zeep.wsdl.definitions.AbstractOperation """ name = xmlelement.get("name") kwargs = {"fault_messages": {}} for msg_node in xmlelement: tag_name = etree.QName(msg_node.tag).localname if tag_name not in ("input", "output", "fault"): continue param_msg = qname_attr(msg_node, "message", wsdl.target_namespace) param_name = msg_node.get("name") try: param_value = wsdl.get("messages", param_msg.text) except IndexError: return if tag_name == "input": kwargs["input_message"] = param_value elif tag_name == "output": kwargs["output_message"] = param_value else: kwargs["fault_messages"][param_name] = param_value wsa_action = msg_node.get(etree.QName(NSMAP["wsam"], "Action")) if not wsa_action: wsa_action = msg_node.get(etree.QName(NSMAP["wsaw"], "Action")) param_value.wsa_action = wsa_action kwargs["name"] = name kwargs["parameter_order"] = xmlelement.get("parameterOrder") return definitions.AbstractOperation(**kwargs) def parse_port_type(wsdl, xmlelement): """Create a PortType object from a xml element. Definition:: <wsdl:definitions .... > <wsdl:portType name="nmtoken"> <wsdl:operation name="nmtoken" .... /> * </wsdl:portType> </wsdl:definitions> :param wsdl: The parent definition instance :type wsdl: zeep.wsdl.wsdl.Definition :param xmlelement: The XML node :type xmlelement: lxml.etree._Element :rtype: zeep.wsdl.definitions.PortType """ name = qname_attr(xmlelement, "name", wsdl.target_namespace) operations = {} for elm in xmlelement.findall("wsdl:operation", namespaces=NSMAP): operation = parse_abstract_operation(wsdl, elm) if operation: operations[operation.name] = operation return definitions.PortType(name, operations) def parse_port(wsdl, xmlelement): """Create a Port object from a xml element. This is called via the parse_service function since ports are part of the service xml elements. Definition:: <wsdl:port name="nmtoken" binding="qname"> * <wsdl:documentation .... /> ? <-- extensibility element --> </wsdl:port> :param wsdl: The parent definition instance :type wsdl: zeep.wsdl.wsdl.Definition :param xmlelement: The XML node :type xmlelement: lxml.etree._Element :rtype: zeep.wsdl.definitions.Port """ name = xmlelement.get("name") binding_name = qname_attr(xmlelement, "binding", wsdl.target_namespace) return definitions.Port(name, binding_name=binding_name, xmlelement=xmlelement) def parse_service(wsdl, xmlelement): """ Definition:: <wsdl:service name="nmtoken"> * <wsdl:documentation .... />? <wsdl:port name="nmtoken" binding="qname"> * <wsdl:documentation .... /> ? <-- extensibility element --> </wsdl:port> <-- extensibility element --> </wsdl:service> Example:: <service name="StockQuoteService"> <documentation>My first service</documentation> <port name="StockQuotePort" binding="tns:StockQuoteBinding"> <soap:address location="http://example.com/stockquote"/> </port> </service> :param wsdl: The parent definition instance :type wsdl: zeep.wsdl.wsdl.Definition :param xmlelement: The XML node :type xmlelement: lxml.etree._Element :rtype: zeep.wsdl.definitions.Service """ name = xmlelement.get("name") ports = [] for port_node in xmlelement.findall("wsdl:port", namespaces=NSMAP): port = parse_port(wsdl, port_node) if port: ports.append(port) obj = definitions.Service(name) for port in ports: obj.add_port(port) return obj
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/wsdl/parse.py
parse.py
from __future__ import print_function import logging import operator import os import warnings from collections import OrderedDict import six from lxml import etree from zeep.exceptions import IncompleteMessage from zeep.loader import absolute_location, is_relative_path, load_external from zeep.settings import Settings from zeep.utils import findall_multiple_ns from zeep.wsdl import parse from zeep.xsd import Schema NSMAP = {"wsdl": "http://schemas.xmlsoap.org/wsdl/"} logger = logging.getLogger(__name__) class Document(object): """A WSDL Document exists out of one or more definitions. There is always one 'root' definition which should be passed as the location to the Document. This definition can import other definitions. These imports are non-transitive, only the definitions defined in the imported document are available in the parent definition. This Document is mostly just a simple interface to the root definition. After all definitions are loaded the definitions are resolved. This resolves references which were not yet available during the initial parsing phase. :param location: Location of this WSDL :type location: string :param transport: The transport object to be used :type transport: zeep.transports.Transport :param base: The base location of this document :type base: str :param strict: Indicates if strict mode is enabled :type strict: bool """ def __init__(self, location, transport, base=None, settings=None): """Initialize a WSDL document. The root definition properties are exposed as entry points. """ self.settings = settings or Settings() if isinstance(location, six.string_types): if is_relative_path(location): location = os.path.abspath(location) self.location = location else: self.location = base self.transport = transport # Dict with all definition objects within this WSDL self._definitions = {} self.types = Schema( node=None, transport=self.transport, location=self.location, settings=self.settings, ) document = self._get_xml_document(location) root_definitions = Definition(self, document, self.location) root_definitions.resolve_imports() # Make the wsdl definitions public self.messages = root_definitions.messages self.port_types = root_definitions.port_types self.bindings = root_definitions.bindings self.services = root_definitions.services def __repr__(self): return "<WSDL(location=%r)>" % self.location def dump(self): print("") print("Prefixes:") for prefix, namespace in self.types.prefix_map.items(): print(" " * 4, "%s: %s" % (prefix, namespace)) print("") print("Global elements:") for elm_obj in sorted(self.types.elements, key=lambda k: k.qname): value = elm_obj.signature(schema=self.types) print(" " * 4, value) print("") print("Global types:") for type_obj in sorted(self.types.types, key=lambda k: k.qname or ""): value = type_obj.signature(schema=self.types) print(" " * 4, value) print("") print("Bindings:") for binding_obj in sorted( self.bindings.values(), key=lambda k: six.text_type(k) ): print(" " * 4, six.text_type(binding_obj)) print("") for service in self.services.values(): print(six.text_type(service)) for port in service.ports.values(): print(" " * 4, six.text_type(port)) print(" " * 8, "Operations:") operations = sorted( port.binding._operations.values(), key=operator.attrgetter("name") ) for operation in operations: print("%s%s" % (" " * 12, six.text_type(operation))) print("") def _get_xml_document(self, location): """Load the XML content from the given location and return an lxml.Element object. :param location: The URL of the document to load :type location: string """ return load_external( location, self.transport, self.location, settings=self.settings ) def _add_definition(self, definition): key = (definition.target_namespace, definition.location) self._definitions[key] = definition class Definition(object): """The Definition represents one wsdl:definition within a Document. :param wsdl: The wsdl """ def __init__(self, wsdl, doc, location): """fo :param wsdl: The wsdl """ logger.debug("Creating definition for %s", location) self.wsdl = wsdl self.location = location self.types = wsdl.types self.port_types = {} self.messages = {} self.bindings = {} self.services = OrderedDict() self.imports = {} self._resolved_imports = False self.target_namespace = doc.get("targetNamespace") self.wsdl._add_definition(self) self.nsmap = doc.nsmap # Process the definitions self.parse_imports(doc) self.parse_types(doc) self.messages = self.parse_messages(doc) self.port_types = self.parse_ports(doc) self.bindings = self.parse_binding(doc) self.services = self.parse_service(doc) def __repr__(self): return "<Definition(location=%r)>" % self.location def get(self, name, key, _processed=None): container = getattr(self, name) if key in container: return container[key] # Turns out that no one knows if the wsdl import statement is # transitive or not. WSDL/SOAP specs are awesome... So lets just do it. # TODO: refactor me into something more sane _processed = _processed or set() if self.target_namespace not in _processed: _processed.add(self.target_namespace) for definition in self.imports.values(): try: return definition.get(name, key, _processed) except IndexError: # Try to see if there is an item which has no namespace # but where the localname matches. This is basically for # #356 but in the future we should also ignore mismatching # namespaces as last fallback fallback_key = etree.QName(key).localname try: return definition.get(name, fallback_key, _processed) except IndexError: pass raise IndexError("No definition %r in %r found" % (key, name)) def resolve_imports(self): """Resolve all root elements (types, messages, etc).""" # Simple guard to protect against cyclic imports if self._resolved_imports: return self._resolved_imports = True for definition in self.imports.values(): definition.resolve_imports() for message in self.messages.values(): message.resolve(self) for port_type in self.port_types.values(): port_type.resolve(self) for binding in self.bindings.values(): binding.resolve(self) for service in self.services.values(): service.resolve(self) def parse_imports(self, doc): """Import other WSDL definitions in this document. Note that imports are non-transitive, so only import definitions which are defined in the imported document and ignore definitions imported in that document. This should handle recursive imports though: A -> B -> A A -> B -> C -> A :param doc: The source document :type doc: lxml.etree._Element """ for import_node in doc.findall("wsdl:import", namespaces=NSMAP): namespace = import_node.get("namespace") location = import_node.get("location") if not location: logger.debug( "Skipping import for namespace %s (empty location)", namespace ) continue location = absolute_location(location, self.location) key = (namespace, location) if key in self.wsdl._definitions: self.imports[key] = self.wsdl._definitions[key] else: document = self.wsdl._get_xml_document(location) if etree.QName(document.tag).localname == "schema": self.types.add_documents([document], location) else: wsdl = Definition(self.wsdl, document, location) self.imports[key] = wsdl def parse_types(self, doc): """Return an xsd.Schema() instance for the given wsdl:types element. If the wsdl:types contain multiple schema definitions then a new wrapping xsd.Schema is defined with xsd:import statements linking them together. If the wsdl:types doesn't container an xml schema then an empty schema is returned instead. Definition:: <definitions .... > <types> <xsd:schema .... />* </types> </definitions> :param doc: The source document :type doc: lxml.etree._Element """ namespace_sets = [ { "xsd": "http://www.w3.org/2001/XMLSchema", "wsdl": "http://schemas.xmlsoap.org/wsdl/", }, { "xsd": "http://www.w3.org/1999/XMLSchema", "wsdl": "http://schemas.xmlsoap.org/wsdl/", }, ] # Find xsd:schema elements (wsdl:types/xsd:schema) schema_nodes = findall_multiple_ns(doc, "wsdl:types/xsd:schema", namespace_sets) self.types.add_documents(schema_nodes, self.location) def parse_messages(self, doc): """ Definition:: <definitions .... > <message name="nmtoken"> * <part name="nmtoken" element="qname"? type="qname"?/> * </message> </definitions> :param doc: The source document :type doc: lxml.etree._Element """ result = {} for msg_node in doc.findall("wsdl:message", namespaces=NSMAP): try: msg = parse.parse_abstract_message(self, msg_node) except IncompleteMessage as exc: warnings.warn(str(exc)) else: result[msg.name.text] = msg logger.debug("Adding message: %s", msg.name.text) return result def parse_ports(self, doc): """Return dict with `PortType` instances as values Definition:: <wsdl:definitions .... > <wsdl:portType name="nmtoken"> <wsdl:operation name="nmtoken" .... /> * </wsdl:portType> </wsdl:definitions> :param doc: The source document :type doc: lxml.etree._Element """ result = {} for port_node in doc.findall("wsdl:portType", namespaces=NSMAP): port_type = parse.parse_port_type(self, port_node) result[port_type.name.text] = port_type logger.debug("Adding port: %s", port_type.name.text) return result def parse_binding(self, doc): """Parse the binding elements and return a dict of bindings. Currently supported bindings are Soap 1.1, Soap 1.2., HTTP Get and HTTP Post. The detection of the type of bindings is done by the bindings themselves using the introspection of the xml nodes. Definition:: <wsdl:definitions .... > <wsdl:binding name="nmtoken" type="qname"> * <-- extensibility element (1) --> * <wsdl:operation name="nmtoken"> * <-- extensibility element (2) --> * <wsdl:input name="nmtoken"? > ? <-- extensibility element (3) --> </wsdl:input> <wsdl:output name="nmtoken"? > ? <-- extensibility element (4) --> * </wsdl:output> <wsdl:fault name="nmtoken"> * <-- extensibility element (5) --> * </wsdl:fault> </wsdl:operation> </wsdl:binding> </wsdl:definitions> :param doc: The source document :type doc: lxml.etree._Element :returns: Dictionary with binding name as key and Binding instance as value :rtype: dict """ result = {} if not getattr(self.wsdl.transport, "binding_classes", None): from zeep.wsdl import bindings binding_classes = [ bindings.Soap11Binding, bindings.Soap12Binding, bindings.HttpGetBinding, bindings.HttpPostBinding, ] else: binding_classes = self.wsdl.transport.binding_classes for binding_node in doc.findall("wsdl:binding", namespaces=NSMAP): # Detect the binding type binding = None for binding_class in binding_classes: if binding_class.match(binding_node): try: binding = binding_class.parse(self, binding_node) except NotImplementedError as exc: logger.debug("Ignoring binding: %s", exc) continue logger.debug("Adding binding: %s", binding.name.text) result[binding.name.text] = binding break return result def parse_service(self, doc): """ Definition:: <wsdl:definitions .... > <wsdl:service .... > * <wsdl:port name="nmtoken" binding="qname"> * <-- extensibility element (1) --> </wsdl:port> </wsdl:service> </wsdl:definitions> :param doc: The source document :type doc: lxml.etree._Element """ result = OrderedDict() for service_node in doc.findall("wsdl:service", namespaces=NSMAP): service = parse.parse_service(self, service_node) result[service.name] = service logger.debug("Adding service: %s", service.name) return result
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/wsdl/wsdl.py
wsdl.py
import warnings from collections import OrderedDict, namedtuple from six import python_2_unicode_compatible from zeep.exceptions import IncompleteOperation MessagePart = namedtuple("MessagePart", ["element", "type"]) class AbstractMessage(object): """Messages consist of one or more logical parts. Each part is associated with a type from some type system using a message-typing attribute. The set of message-typing attributes is extensible. WSDL defines several such message-typing attributes for use with XSD: - element: Refers to an XSD element using a QName. - type: Refers to an XSD simpleType or complexType using a QName. """ def __init__(self, name): self.name = name self.parts = OrderedDict() def __repr__(self): return "<%s(name=%r)>" % (self.__class__.__name__, self.name.text) def resolve(self, definitions): pass def add_part(self, name, element): self.parts[name] = element class AbstractOperation(object): """Abstract operations are defined in the wsdl's portType elements.""" def __init__( self, name, input_message=None, output_message=None, fault_messages=None, parameter_order=None, ): """Initialize the abstract operation. :param name: The name of the operation :type name: str :param input_message: Message to generate the request XML :type input_message: AbstractMessage :param output_message: Message to process the response XML :type output_message: AbstractMessage :param fault_messages: Dict of messages to handle faults :type fault_messages: dict of str: AbstractMessage """ self.name = name self.input_message = input_message self.output_message = output_message self.fault_messages = fault_messages self.parameter_order = parameter_order class PortType(object): def __init__(self, name, operations): self.name = name self.operations = operations def __repr__(self): return "<%s(name=%r)>" % (self.__class__.__name__, self.name.text) def resolve(self, definitions): pass @python_2_unicode_compatible class Binding(object): """Base class for the various bindings (SoapBinding / HttpBinding) .. raw:: ascii Binding | +-> Operation | +-> ConcreteMessage | +-> AbstractMessage """ def __init__(self, wsdl, name, port_name): """Binding :param wsdl: :type wsdl: :param name: :type name: string :param port_name: :type port_name: string """ self.name = name self.port_name = port_name self.port_type = None self.wsdl = wsdl self._operations = {} def resolve(self, definitions): self.port_type = definitions.get("port_types", self.port_name.text) for name, operation in list(self._operations.items()): try: operation.resolve(definitions) except IncompleteOperation as exc: warnings.warn(str(exc)) del self._operations[name] def _operation_add(self, operation): # XXX: operation name is not unique self._operations[operation.name] = operation def __str__(self): return "%s: %s" % (self.__class__.__name__, self.name.text) def __repr__(self): return "<%s(name=%r, port_type=%r)>" % ( self.__class__.__name__, self.name.text, self.port_type, ) def all(self): return self._operations def get(self, key): try: return self._operations[key] except KeyError: raise ValueError("No such operation %r on %s" % (key, self.name)) @classmethod def match(cls, node): raise NotImplementedError() @classmethod def parse(cls, definitions, xmlelement): raise NotImplementedError() @python_2_unicode_compatible class Operation(object): """Concrete operation Contains references to the concrete messages """ def __init__(self, name, binding): self.name = name self.binding = binding self.abstract = None self.style = None self.input = None self.output = None self.faults = {} def resolve(self, definitions): try: self.abstract = self.binding.port_type.operations[self.name] except KeyError: raise IncompleteOperation( "The wsdl:operation %r was not found in the wsdl:portType %r" % (self.name, self.binding.port_type.name.text) ) def __repr__(self): return "<%s(name=%r, style=%r)>" % ( self.__class__.__name__, self.name, self.style, ) def __str__(self): if not self.input: return u"%s(missing input message)" % (self.name) retval = u"%s(%s)" % (self.name, self.input.signature()) if self.output: retval += u" -> %s" % (self.output.signature(as_output=True)) return retval def create(self, *args, **kwargs): return self.input.serialize(*args, **kwargs) def process_reply(self, envelope): raise NotImplementedError() @classmethod def parse(cls, wsdl, xmlelement, binding): """ Definition:: <wsdl:operation name="nmtoken"> * <-- extensibility element (2) --> * <wsdl:input name="nmtoken"? > ? <-- extensibility element (3) --> </wsdl:input> <wsdl:output name="nmtoken"? > ? <-- extensibility element (4) --> * </wsdl:output> <wsdl:fault name="nmtoken"> * <-- extensibility element (5) --> * </wsdl:fault> </wsdl:operation> """ raise NotImplementedError() @python_2_unicode_compatible class Port(object): """Specifies an address for a binding, thus defining a single communication endpoint. """ def __init__(self, name, binding_name, xmlelement): self.name = name self._resolve_context = {"binding_name": binding_name, "xmlelement": xmlelement} # Set during resolve() self.binding = None self.binding_options = {} def __repr__(self): return "<%s(name=%r, binding=%r, %r)>" % ( self.__class__.__name__, self.name, self.binding, self.binding_options, ) def __str__(self): return u"Port: %s (%s)" % (self.name, self.binding) def resolve(self, definitions): if self._resolve_context is None: return try: self.binding = definitions.get( "bindings", self._resolve_context["binding_name"].text ) except IndexError: return False if definitions.location and self.binding.wsdl.settings.force_https: force_https = definitions.location.startswith("https") else: force_https = False self.binding_options = self.binding.process_service_port( self._resolve_context["xmlelement"], force_https ) self._resolve_context = None return True @python_2_unicode_compatible class Service(object): """Used to aggregate a set of related ports. """ def __init__(self, name): self.ports = OrderedDict() self.name = name self._is_resolved = False def __str__(self): return u"Service: %s" % self.name def __repr__(self): return "<%s(name=%r, ports=%r)>" % ( self.__class__.__name__, self.name, self.ports, ) def resolve(self, definitions): if self._is_resolved: return unresolved = [] for name, port in self.ports.items(): is_resolved = port.resolve(definitions) if not is_resolved: unresolved.append(name) # Remove unresolved bindings (http etc) for name in unresolved: del self.ports[name] self._is_resolved = True def add_port(self, port): self.ports[port.name] = port
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/wsdl/definitions.py
definitions.py
import base64 from cached_property import cached_property from requests.structures import CaseInsensitiveDict class MessagePack(object): def __init__(self, parts): self._parts = parts def __repr__(self): return "<MessagePack(attachments=[%s])>" % ( ", ".join(repr(a) for a in self.attachments) ) @property def root(self): return self._root def _set_root(self, root): self._root = root @cached_property def attachments(self): """Return a list of attachments. :rtype: list of Attachment """ return [Attachment(part) for part in self._parts] def get_by_content_id(self, content_id): """get_by_content_id :param content_id: The content-id to return :type content_id: str :rtype: Attachment """ for attachment in self.attachments: if attachment.content_id == content_id: return attachment class Attachment(object): def __init__(self, part): encoding = part.encoding or "utf-8" self.headers = CaseInsensitiveDict( {k.decode(encoding): v.decode(encoding) for k, v in part.headers.items()} ) self.content_type = self.headers.get("Content-Type", None) self.content_id = self.headers.get("Content-ID", None) self.content_location = self.headers.get("Content-Location", None) self._part = part def __repr__(self): return "<Attachment(%r, %r)>" % (self.content_id, self.content_type) @cached_property def content(self): """Return the content of the attachment :rtype: bytes or str """ encoding = self.headers.get("Content-Transfer-Encoding", None) content = self._part.content if encoding == "base64": return base64.b64decode(content) elif encoding == "binary": return content.strip(b"\r\n") else: return content
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/wsdl/attachments.py
attachments.py
import six from defusedxml.lxml import fromstring from lxml import etree from zeep import ns, xsd from zeep.helpers import serialize_object from zeep.wsdl.messages.base import ConcreteMessage, SerializedMessage from zeep.wsdl.utils import etree_to_string __all__ = ["MimeContent", "MimeXML", "MimeMultipart"] class MimeMessage(ConcreteMessage): _nsmap = {"mime": ns.MIME} def __init__(self, wsdl, name, operation, part_name): super(MimeMessage, self).__init__(wsdl, name, operation) self.part_name = part_name def resolve(self, definitions, abstract_message): """Resolve the body element The specs are (again) not really clear how to handle the message parts in relation the message element vs type. The following strategy is chosen, which seem to work: - If the message part has a name and it maches then set it as body - If the message part has a name but it doesn't match but there are no other message parts, then just use that one. - If the message part has no name then handle it like an rpc call, in other words, each part is an argument. """ self.abstract = abstract_message if self.part_name and self.abstract.parts: if self.part_name in self.abstract.parts: message = self.abstract.parts[self.part_name] elif len(self.abstract.parts) == 1: message = list(self.abstract.parts.values())[0] else: raise ValueError( "Multiple parts for message %r while no matching part found" % self.part_name ) if message.element: self.body = message.element else: elm = xsd.Element(self.part_name, message.type) self.body = xsd.Element( self.operation.name, xsd.ComplexType(xsd.Sequence([elm])) ) else: children = [] for name, message in self.abstract.parts.items(): if message.element: elm = message.element.clone(name) else: elm = xsd.Element(name, message.type) children.append(elm) self.body = xsd.Element( self.operation.name, xsd.ComplexType(xsd.Sequence(children)) ) class MimeContent(MimeMessage): """WSDL includes a way to bind abstract types to concrete messages in some MIME format. Bindings for the following MIME types are defined: - multipart/related - text/xml - application/x-www-form-urlencoded - Others (by specifying the MIME type string) The set of defined MIME types is both large and evolving, so it is not a goal for WSDL to exhaustively define XML grammar for each MIME type. :param wsdl: The main wsdl document :type wsdl: zeep.wsdl.wsdl.Document :param name: :param operation: The operation to which this message belongs :type operation: zeep.wsdl.bindings.soap.SoapOperation :param part_name: :type type: str """ def __init__(self, wsdl, name, operation, content_type, part_name): super(MimeContent, self).__init__(wsdl, name, operation, part_name) self.content_type = content_type def serialize(self, *args, **kwargs): value = self.body(*args, **kwargs) headers = {"Content-Type": self.content_type} data = "" if self.content_type == "application/x-www-form-urlencoded": items = serialize_object(value) data = six.moves.urllib.parse.urlencode(items) elif self.content_type == "text/xml": document = etree.Element("root") self.body.render(document, value) data = etree_to_string(list(document)[0]) return SerializedMessage( path=self.operation.location, headers=headers, content=data ) def deserialize(self, node): node = fromstring(node) part = list(self.abstract.parts.values())[0] return part.type.parse_xmlelement(node) @classmethod def parse(cls, definitions, xmlelement, operation): name = xmlelement.get("name") part_name = content_type = None content_node = xmlelement.find("mime:content", namespaces=cls._nsmap) if content_node is not None: content_type = content_node.get("type") part_name = content_node.get("part") obj = cls(definitions.wsdl, name, operation, content_type, part_name) return obj class MimeXML(MimeMessage): """To specify XML payloads that are not SOAP compliant (do not have a SOAP Envelope), but do have a particular schema, the mime:mimeXml element may be used to specify that concrete schema. The part attribute refers to a message part defining the concrete schema of the root XML element. The part attribute MAY be omitted if the message has only a single part. The part references a concrete schema using the element attribute for simple parts or type attribute for composite parts :param wsdl: The main wsdl document :type wsdl: zeep.wsdl.wsdl.Document :param name: :param operation: The operation to which this message belongs :type operation: zeep.wsdl.bindings.soap.SoapOperation :param part_name: :type type: str """ def serialize(self, *args, **kwargs): raise NotImplementedError() def deserialize(self, node): node = fromstring(node) part = next(iter(self.abstract.parts.values()), None) return part.element.parse(node, self.wsdl.types) @classmethod def parse(cls, definitions, xmlelement, operation): name = xmlelement.get("name") part_name = None content_node = xmlelement.find("mime:mimeXml", namespaces=cls._nsmap) if content_node is not None: part_name = content_node.get("part") obj = cls(definitions.wsdl, name, operation, part_name) return obj class MimeMultipart(MimeMessage): """The multipart/related MIME type aggregates an arbitrary set of MIME formatted parts into one message using the MIME type "multipart/related". The mime:multipartRelated element describes the concrete format of such a message:: <mime:multipartRelated> <mime:part> * <-- mime element --> </mime:part> </mime:multipartRelated> The mime:part element describes each part of a multipart/related message. MIME elements appear within mime:part to specify the concrete MIME type for the part. If more than one MIME element appears inside a mime:part, they are alternatives. :param wsdl: The main wsdl document :type wsdl: zeep.wsdl.wsdl.Document :param name: :param operation: The operation to which this message belongs :type operation: zeep.wsdl.bindings.soap.SoapOperation :param part_name: :type type: str """ pass
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/wsdl/messages/mime.py
mime.py
import copy from collections import OrderedDict from lxml import etree from lxml.builder import ElementMaker from zeep import exceptions, xsd from zeep.utils import as_qname from zeep.wsdl.messages.base import ConcreteMessage, SerializedMessage from zeep.wsdl.messages.multiref import process_multiref from zeep.xsd.context import XmlParserContext __all__ = ["DocumentMessage", "RpcMessage"] class SoapMessage(ConcreteMessage): """Base class for the SOAP Document and RPC messages :param wsdl: The main wsdl document :type wsdl: zeep.wsdl.Document :param name: :param operation: The operation to which this message belongs :type operation: zeep.wsdl.bindings.soap.SoapOperation :param type: 'input' or 'output' :type type: str :param nsmap: The namespace mapping :type nsmap: dict """ def __init__(self, wsdl, name, operation, type, nsmap): super(SoapMessage, self).__init__(wsdl, name, operation) self.nsmap = nsmap self.abstract = None # Set during resolve() self.type = type self._is_body_wrapped = False self.body = None self.header = None self.envelope = None def serialize(self, *args, **kwargs): """Create a SerializedMessage for this message""" nsmap = {"soap-env": self.nsmap["soap-env"]} nsmap.update(self.wsdl.types._prefix_map_custom) soap = ElementMaker(namespace=self.nsmap["soap-env"], nsmap=nsmap) # Create the soap:envelope envelope = soap.Envelope() # Create the soap:header element headers_value = kwargs.pop("_soapheaders", None) header = self._serialize_header(headers_value, nsmap) if header is not None: envelope.append(header) # Create the soap:body element. The _is_body_wrapped attribute signals # that the self.body element is of type soap:body, so we don't have to # create it in that case. Otherwise we create a Element soap:body and # render the content into this. if self.body: body_value = self.body(*args, **kwargs) if self._is_body_wrapped: self.body.render(envelope, body_value) else: body = soap.Body() envelope.append(body) self.body.render(body, body_value) else: body = soap.Body() envelope.append(body) # XXX: This is only used in Soap 1.1 so should be moved to the the # Soap11Binding._set_http_headers(). But let's keep it like this for # now. headers = {"SOAPAction": '"%s"' % self.operation.soapaction} return SerializedMessage(path=None, headers=headers, content=envelope) def deserialize(self, envelope): """Deserialize the SOAP:Envelope and return a CompoundValue with the result. """ if not self.envelope: return None body = envelope.find("soap-env:Body", namespaces=self.nsmap) body_result = self._deserialize_body(body) header = envelope.find("soap-env:Header", namespaces=self.nsmap) headers_result = self._deserialize_headers(header) kwargs = body_result kwargs.update(headers_result) result = self.envelope(**kwargs) # If the message if self.header.type._element: return result result = result.body if result is None or len(result) == 0: return None elif len(result) > 1: return result # Check if we can remove the wrapping object to make the return value # easier to use. result = next(iter(result.__values__.values())) if isinstance(result, xsd.CompoundValue): children = result._xsd_type.elements attributes = result._xsd_type.attributes if len(children) == 1 and len(attributes) == 0: item_name, item_element = children[0] retval = getattr(result, item_name) return retval return result def signature(self, as_output=False): if not self.envelope: return None if as_output: if isinstance(self.envelope.type, xsd.ComplexType): try: if len(self.envelope.type.elements) == 1: return self.envelope.type.elements[0][1].type.signature( schema=self.wsdl.types, standalone=False ) except AttributeError: return None return self.envelope.type.signature( schema=self.wsdl.types, standalone=False ) if self.body: parts = [self.body.type.signature(schema=self.wsdl.types, standalone=False)] else: parts = [] if self.header.type._element: parts.append( "_soapheaders={%s}" % self.header.type.signature(schema=self.wsdl.types, standalone=False) ) return ", ".join(part for part in parts if part) @classmethod def parse(cls, definitions, xmlelement, operation, type, nsmap): """Parse a wsdl:binding/wsdl:operation/wsdl:operation for the SOAP implementation. Each wsdl:operation can contain three child nodes: - input - output - fault Definition for input/output:: <input> <soap:body parts="nmtokens"? use="literal|encoded" encodingStyle="uri-list"? namespace="uri"?> <soap:header message="qname" part="nmtoken" use="literal|encoded" encodingStyle="uri-list"? namespace="uri"?>* <soap:headerfault message="qname" part="nmtoken" use="literal|encoded" encodingStyle="uri-list"? namespace="uri"?/>* </soap:header> </input> And the definition for fault:: <soap:fault name="nmtoken" use="literal|encoded" encodingStyle="uri-list"? namespace="uri"?> """ name = xmlelement.get("name") obj = cls(definitions.wsdl, name, operation, nsmap=nsmap, type=type) body_data = None header_data = None # After some profiling it turns out that .find() and .findall() in this # case are twice as fast as the xpath method body = xmlelement.find("soap:body", namespaces=operation.binding.nsmap) if body is not None: body_data = cls._parse_body(body) # Parse soap:header (multiple) elements = xmlelement.findall("soap:header", namespaces=operation.binding.nsmap) header_data = cls._parse_header( elements, definitions.target_namespace, operation ) obj._resolve_info = {"body": body_data, "header": header_data} return obj @classmethod def _parse_body(cls, xmlelement): """Parse soap:body and return a dict with data to resolve it. <soap:body parts="nmtokens"? use="literal|encoded"? encodingStyle="uri-list"? namespace="uri"?> """ return { "part": xmlelement.get("part"), "use": xmlelement.get("use", "literal"), "encodingStyle": xmlelement.get("encodingStyle"), "namespace": xmlelement.get("namespace"), } @classmethod def _parse_header(cls, xmlelements, tns, operation): """Parse the soap:header and optionally included soap:headerfault elements <soap:header message="qname" part="nmtoken" use="literal|encoded" encodingStyle="uri-list"? namespace="uri"? />* The header can optionally contain one ore more soap:headerfault elements which can contain the same attributes as the soap:header:: <soap:headerfault message="qname" part="nmtoken" use="literal|encoded" encodingStyle="uri-list"? namespace="uri"?/>* """ result = [] for xmlelement in xmlelements: data = cls._parse_header_element(xmlelement, tns) # Add optional soap:headerfault elements data["faults"] = [] fault_elements = xmlelement.findall( "soap:headerfault", namespaces=operation.binding.nsmap ) for fault_element in fault_elements: fault_data = cls._parse_header_element(fault_element, tns) data["faults"].append(fault_data) result.append(data) return result @classmethod def _parse_header_element(cls, xmlelement, tns): attributes = xmlelement.attrib message_qname = as_qname(attributes["message"], xmlelement.nsmap, tns) try: return { "message": message_qname, "part": attributes["part"], "use": attributes["use"], "encodingStyle": attributes.get("encodingStyle"), "namespace": attributes.get("namespace"), } except KeyError: raise exceptions.WsdlSyntaxError("Invalid soap:header(fault)") def resolve(self, definitions, abstract_message): """Resolve the data in the self._resolve_info dict (set via parse()) This creates three xsd.Element objects: - self.header - self.body - self.envelope (combination of headers and body) XXX headerfaults are not implemented yet. """ info = self._resolve_info del self._resolve_info # If this message has no parts then we have nothing to do. This might # happen for output messages which don't return anything. if ( abstract_message is None or not abstract_message.parts ) and self.type != "input": return self.abstract = abstract_message parts = OrderedDict(self.abstract.parts) self.header = self._resolve_header(info["header"], definitions, parts) self.body = self._resolve_body(info["body"], definitions, parts) self.envelope = self._create_envelope_element() def _create_envelope_element(self): """Create combined `envelope` complexType which contains both the elements from the body and the headers. """ all_elements = xsd.Sequence([]) if self.header.type._element: all_elements.append( xsd.Element("{%s}header" % self.nsmap["soap-env"], self.header.type) ) all_elements.append( xsd.Element( "{%s}body" % self.nsmap["soap-env"], self.body.type if self.body else None, ) ) return xsd.Element( "{%s}envelope" % self.nsmap["soap-env"], xsd.ComplexType(all_elements) ) def _serialize_header(self, headers_value, nsmap): if not headers_value: return headers_value = copy.deepcopy(headers_value) soap = ElementMaker(namespace=self.nsmap["soap-env"], nsmap=nsmap) header = soap.Header() if isinstance(headers_value, list): for header_value in headers_value: if hasattr(header_value, "_xsd_elm"): header_value._xsd_elm.render(header, header_value) elif hasattr(header_value, "_xsd_type"): header_value._xsd_type.render(header, header_value) elif isinstance(header_value, etree._Element): header.append(header_value) else: raise ValueError("Invalid value given to _soapheaders") elif isinstance(headers_value, dict): if not self.header: raise ValueError( "_soapheaders only accepts a dictionary if the wsdl " "defines the headers." ) # Only render headers for which we have a value headers_value = self.header(**headers_value) for name, elm in self.header.type.elements: if name in headers_value and headers_value[name] is not None: elm.render(header, headers_value[name], ["header", name]) else: raise ValueError("Invalid value given to _soapheaders") return header def _deserialize_headers(self, xmlelement): """Deserialize the values in the SOAP:Header element""" if not self.header or xmlelement is None: return {} context = XmlParserContext(settings=self.wsdl.settings) result = self.header.parse(xmlelement, self.wsdl.types, context=context) if result is not None: return {"header": result} return {} def _resolve_header(self, info, definitions, parts): name = etree.QName(self.nsmap["soap-env"], "Header") container = xsd.All(consume_other=True) if not info: return xsd.Element(name, xsd.ComplexType(container)) for item in info: message_name = item["message"].text part_name = item["part"] message = definitions.get("messages", message_name) if message == self.abstract and part_name in parts: del parts[part_name] part = message.parts[part_name] if part.element: element = part.element.clone() element.attr_name = part_name else: element = xsd.Element(part_name, part.type) container.append(element) return xsd.Element(name, xsd.ComplexType(container)) class DocumentMessage(SoapMessage): """In the document message there are no additional wrappers, and the message parts appear directly under the SOAP Body element. .. inheritance-diagram:: zeep.wsdl.messages.soap.DocumentMessage :parts: 1 :param wsdl: The main wsdl document :type wsdl: zeep.wsdl.Document :param name: :param operation: The operation to which this message belongs :type operation: zeep.wsdl.bindings.soap.SoapOperation :param type: 'input' or 'output' :type type: str :param nsmap: The namespace mapping :type nsmap: dict """ def __init__(self, *args, **kwargs): super(DocumentMessage, self).__init__(*args, **kwargs) def _deserialize_body(self, xmlelement): if not self._is_body_wrapped: # TODO: For now we assume that the body only has one child since # only one part is specified in the wsdl. This should be handled # way better xmlelement = list(xmlelement)[0] context = XmlParserContext(settings=self.wsdl.settings) result = self.body.parse(xmlelement, self.wsdl.types, context=context) return {"body": result} def _resolve_body(self, info, definitions, parts): name = etree.QName(self.nsmap["soap-env"], "Body") if not info or not parts: return None # If the part name is omitted then all parts are available under # the soap:body tag. Otherwise only the part with the given name. if info["part"]: part_name = info["part"] sub_elements = [parts[part_name].element] else: sub_elements = [] for part_name, part in parts.items(): element = part.element.clone() element.attr_name = part_name or element.name sub_elements.append(element) if len(sub_elements) > 1: self._is_body_wrapped = True return xsd.Element(name, xsd.ComplexType(xsd.All(sub_elements))) else: self._is_body_wrapped = False return sub_elements[0] class RpcMessage(SoapMessage): """In RPC messages each part is a parameter or a return value and appears inside a wrapper element within the body. The wrapper element is named identically to the operation name and its namespace is the value of the namespace attribute. Each message part (parameter) appears under the wrapper, represented by an accessor named identically to the corresponding parameter of the call. Parts are arranged in the same order as the parameters of the call. .. inheritance-diagram:: zeep.wsdl.messages.soap.DocumentMessage :parts: 1 :param wsdl: The main wsdl document :type wsdl: zeep.wsdl.Document :param name: :param operation: The operation to which this message belongs :type operation: zeep.wsdl.bindings.soap.SoapOperation :param type: 'input' or 'output' :type type: str :param nsmap: The namespace mapping :type nsmap: dict """ def _resolve_body(self, info, definitions, parts): """Return an XSD element for the SOAP:Body. Each part is a parameter or a return value and appears inside a wrapper element within the body named identically to the operation name and its namespace is the value of the namespace attribute. """ if not info: return None namespace = info["namespace"] if self.type == "input": tag_name = etree.QName(namespace, self.operation.name) else: tag_name = etree.QName(namespace, self.abstract.name.localname) # Create the xsd element to create/parse the response. Each part # is a sub element of the root node (which uses the operation name) elements = [] for name, msg in parts.items(): if msg.element: elements.append(msg.element) else: elements.append(xsd.Element(name, msg.type)) return xsd.Element(tag_name, xsd.ComplexType(xsd.Sequence(elements))) def _deserialize_body(self, body_element): """The name of the wrapper element is not defined. The WS-I defines that it should be the operation name with the 'Response' string as suffix. But lets just do it really stupid for now and use the first element. """ process_multiref(body_element) response_element = list(body_element)[0] if self.body: context = XmlParserContext(self.wsdl.settings) result = self.body.parse(response_element, self.wsdl.types, context=context) return {"body": result} return {"body": None}
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/wsdl/messages/soap.py
soap.py
from zeep import xsd from zeep.wsdl.messages.base import ConcreteMessage, SerializedMessage __all__ = ["UrlEncoded", "UrlReplacement"] class HttpMessage(ConcreteMessage): """Base class for HTTP Binding messages""" def resolve(self, definitions, abstract_message): self.abstract = abstract_message children = [] for name, message in self.abstract.parts.items(): if message.element: elm = message.element.clone(name) else: elm = xsd.Element(name, message.type) children.append(elm) self.body = xsd.Element( self.operation.name, xsd.ComplexType(xsd.Sequence(children)) ) class UrlEncoded(HttpMessage): """The urlEncoded element indicates that all the message parts are encoded into the HTTP request URI using the standard URI-encoding rules (name1=value&name2=value...). The names of the parameters correspond to the names of the message parts. Each value contributed by the part is encoded using a name=value pair. This may be used with GET to specify URL encoding, or with POST to specify a FORM-POST. For GET, the "?" character is automatically appended as necessary. """ def serialize(self, *args, **kwargs): params = {key: None for key in self.abstract.parts.keys()} params.update(zip(self.abstract.parts.keys(), args)) params.update(kwargs) headers = {"Content-Type": "text/xml; charset=utf-8"} return SerializedMessage( path=self.operation.location, headers=headers, content=params ) @classmethod def parse(cls, definitions, xmlelement, operation): name = xmlelement.get("name") obj = cls(definitions.wsdl, name, operation) return obj class UrlReplacement(HttpMessage): """The http:urlReplacement element indicates that all the message parts are encoded into the HTTP request URI using a replacement algorithm. - The relative URI value of http:operation is searched for a set of search patterns. - The search occurs before the value of the http:operation is combined with the value of the location attribute from http:address. - There is one search pattern for each message part. The search pattern string is the name of the message part surrounded with parenthesis "(" and ")". - For each match, the value of the corresponding message part is substituted for the match at the location of the match. - Matches are performed before any values are replaced (replaced values do not trigger additional matches). Message parts MUST NOT have repeating values. <http:urlReplacement/> """ def serialize(self, *args, **kwargs): params = {key: None for key in self.abstract.parts.keys()} params.update(zip(self.abstract.parts.keys(), args)) params.update(kwargs) headers = {"Content-Type": "text/xml; charset=utf-8"} path = self.operation.location for key, value in params.items(): path = path.replace("(%s)" % key, value if value is not None else "") return SerializedMessage(path=path, headers=headers, content="") @classmethod def parse(cls, definitions, xmlelement, operation): name = xmlelement.get("name") obj = cls(definitions.wsdl, name, operation) return obj
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/wsdl/messages/http.py
http.py
import re from lxml import etree def process_multiref(node): """Iterate through the tree and replace the referened elements. This method replaces the nodes with an href attribute and replaces it with the elements it's referencing to (which have an id attribute).abs """ multiref_objects = {elm.attrib["id"]: elm for elm in node.xpath("*[@id]")} if not multiref_objects: return used_nodes = [] def process(node): """Recursive""" # TODO (In Soap 1.2 this is 'ref') href = node.attrib.get("href") if href and href.startswith("#"): obj = multiref_objects.get(href[1:]) if obj is not None: used_nodes.append(obj) node = _dereference_element(obj, node) for child in node: process(child) process(node) # Remove the old dereferenced nodes from the tree for node in used_nodes: parent = node.getparent() if parent is not None: parent.remove(node) def _dereference_element(source, target): """Move the referenced node (source) in the main response tree (target) :type source: lxml.etree._Element :type target: lxml.etree._Element :rtype target: lxml.etree._Element """ specific_nsmap = {k: v for k, v in source.nsmap.items() if k not in target.nsmap} new = _clone_element(source, target.tag, specific_nsmap) # Replace the node with the new dereferenced node parent = target.getparent() parent.insert(parent.index(target), new) parent.remove(target) # Update all descendants for obj in new.iter(): _prefix_node(obj) return new def _clone_element(node, tag_name=None, nsmap=None): """Clone the given node and return it. This is a recursive call since we want to clone the children the same way. :type source: lxml.etree._Element :type tag_name: str :type nsmap: dict :rtype source: lxml.etree._Element """ tag_name = tag_name or node.tag nsmap = node.nsmap if nsmap is None else nsmap new = etree.Element(tag_name, nsmap=nsmap) for child in node: new_child = _clone_element(child) new.append(new_child) new.text = node.text for key, value in _get_attributes(node): new.set(key, value) return new def _prefix_node(node): """Translate the internal attribute values back to prefixed tokens. This reverses the translation done in _get_attributes For example:: { 'foo:type': '{http://example.com}string' } will be converted to: { 'foo:type': 'example:string' } :type node: lxml.etree._Element """ reverse_nsmap = {v: k for k, v in node.nsmap.items()} prefix_re = re.compile("^{([^}]+)}(.*)") for key, value in node.attrib.items(): if value.startswith("{"): match = prefix_re.match(value) namespace, localname = match.groups() if namespace in reverse_nsmap: value = "%s:%s" % (reverse_nsmap.get(namespace), localname) node.set(key, value) def _get_attributes(node): """Return the node attributes where prefixed values are dereferenced. For example the following xml:: <foobar xmlns:xsi="foo" xmlns:ns0="bar" xsi:type="ns0:string"> will return the dict:: { 'foo:type': '{http://example.com}string' } :type node: lxml.etree._Element """ nsmap = node.nsmap result = {} for key, value in node.attrib.items(): if value.count(":") == 1: prefix, localname = value.split(":") if prefix in nsmap: namespace = nsmap[prefix] value = "{%s}%s" % (namespace, localname) result[key] = value return list(result.items())
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/wsdl/messages/multiref.py
multiref.py
import logging from lxml import etree from requests_toolbelt.multipart.decoder import MultipartDecoder from zeep import ns, plugins, wsa from zeep.exceptions import Fault, TransportError, XMLSyntaxError from zeep.loader import parse_xml from zeep.utils import as_qname, get_media_type, qname_attr from zeep.wsdl.attachments import MessagePack from zeep.wsdl.definitions import Binding, Operation from zeep.wsdl.messages import DocumentMessage, RpcMessage from zeep.wsdl.messages.xop import process_xop from zeep.wsdl.utils import etree_to_string, url_http_to_https logger = logging.getLogger(__name__) class SoapBinding(Binding): """Soap 1.1/1.2 binding""" def __init__(self, wsdl, name, port_name, transport, default_style): """The SoapBinding is the base class for the Soap11Binding and Soap12Binding. :param wsdl: :type wsdl: :param name: :type name: string :param port_name: :type port_name: string :param transport: :type transport: zeep.transports.Transport :param default_style: """ super(SoapBinding, self).__init__(wsdl, name, port_name) self.transport = transport self.default_style = default_style @classmethod def match(cls, node): """Check if this binding instance should be used to parse the given node. :param node: The node to match against :type node: lxml.etree._Element """ soap_node = node.find("soap:binding", namespaces=cls.nsmap) return soap_node is not None def create_message(self, operation, *args, **kwargs): envelope, http_headers = self._create(operation, args, kwargs) return envelope def _create(self, operation, args, kwargs, client=None, options=None): """Create the XML document to send to the server. Note that this generates the soap envelope without the wsse applied. """ operation_obj = self.get(operation) if not operation_obj: raise ValueError("Operation %r not found" % operation) # Create the SOAP envelope serialized = operation_obj.create(*args, **kwargs) self._set_http_headers(serialized, operation_obj) envelope = serialized.content http_headers = serialized.headers # Apply ws-addressing if client: if not options: options = client.service._binding_options if operation_obj.abstract.input_message.wsa_action: envelope, http_headers = wsa.WsAddressingPlugin().egress( envelope, http_headers, operation_obj, options ) # Apply WSSE if client.wsse: if isinstance(client.wsse, list): for wsse in client.wsse: envelope, http_headers = wsse.apply(envelope, http_headers) else: envelope, http_headers = client.wsse.apply(envelope, http_headers) # Apply plugins envelope, http_headers = plugins.apply_egress( client, envelope, http_headers, operation_obj, options ) # Add extra http headers from the setings object if client.settings.extra_http_headers: http_headers.update(client.settings.extra_http_headers) return envelope, http_headers def send(self, client, options, operation, args, kwargs): """Called from the service :param client: The client with which the operation was called :type client: zeep.client.Client :param options: The binding options :type options: dict :param operation: The operation object from which this is a reply :type operation: zeep.wsdl.definitions.Operation :param args: The args to pass to the operation :type args: tuple :param kwargs: The kwargs to pass to the operation :type kwargs: dict """ envelope, http_headers = self._create( operation, args, kwargs, client=client, options=options ) response = client.transport.post_xml(options["address"], envelope, http_headers) operation_obj = self.get(operation) # If the client wants to return the raw data then let's do that. if client.settings.raw_response: return response return self.process_reply(client, operation_obj, response) def process_reply(self, client, operation, response): """Process the XML reply from the server. :param client: The client with which the operation was called :type client: zeep.client.Client :param operation: The operation object from which this is a reply :type operation: zeep.wsdl.definitions.Operation :param response: The response object returned by the remote server :type response: requests.Response """ if response.status_code in (201, 202) and not response.content: return None elif response.status_code != 200 and not response.content: raise TransportError( u"Server returned HTTP status %d (no content available)" % response.status_code, status_code=response.status_code, ) content_type = response.headers.get("Content-Type", "text/xml") media_type = get_media_type(content_type) message_pack = None # If the reply is a multipart/related then we need to retrieve all the # parts if media_type == "multipart/related": decoder = MultipartDecoder( response.content, content_type, response.encoding or "utf-8" ) content = decoder.parts[0].content if len(decoder.parts) > 1: message_pack = MessagePack(parts=decoder.parts[1:]) else: content = response.content try: doc = parse_xml(content, self.transport, settings=client.settings) except XMLSyntaxError as exc: raise TransportError( "Server returned response (%s) with invalid XML: %s.\nContent: %r" % (response.status_code, exc, response.content), status_code=response.status_code, content=response.content, ) # Check if this is an XOP message which we need to decode first if message_pack: if process_xop(doc, message_pack): message_pack = None doc, http_headers = plugins.apply_ingress( client, doc, response.headers, operation ) if client.wsse: if not isinstance(client.wsse, list): client.wsse.verify_response(doc) else: for wsse_item in (wsse_item for wsse_item in client.wsse if "verify_response" in dir(wsse_item)): wsse_item.verify_response(doc) # If the response code is not 200 or if there is a Fault node available # then assume that an error occured. fault_node = doc.find("soap-env:Body/soap-env:Fault", namespaces=self.nsmap) if response.status_code != 200 or fault_node is not None: return self.process_error(doc, operation) result = operation.process_reply(doc) if message_pack: message_pack._set_root(result) return message_pack return result def process_error(self, doc, operation): raise NotImplementedError def process_service_port(self, xmlelement, force_https=False): address_node = xmlelement.find("soap:address", namespaces=self.nsmap) if address_node is None: logger.debug("No valid soap:address found for service") return # Force the usage of HTTPS when the force_https boolean is true location = address_node.get("location") if force_https and location: location = url_http_to_https(location) if location != address_node.get("location"): logger.warning("Forcing soap:address location to HTTPS") return {"address": location} @classmethod def parse(cls, definitions, xmlelement): """ Definition:: <wsdl:binding name="nmtoken" type="qname"> * <-- extensibility element (1) --> * <wsdl:operation name="nmtoken"> * <-- extensibility element (2) --> * <wsdl:input name="nmtoken"? > ? <-- extensibility element (3) --> </wsdl:input> <wsdl:output name="nmtoken"? > ? <-- extensibility element (4) --> * </wsdl:output> <wsdl:fault name="nmtoken"> * <-- extensibility element (5) --> * </wsdl:fault> </wsdl:operation> </wsdl:binding> """ name = qname_attr(xmlelement, "name", definitions.target_namespace) port_name = qname_attr(xmlelement, "type", definitions.target_namespace) # The soap:binding element contains the transport method and # default style attribute for the operations. soap_node = xmlelement.find("soap:binding", namespaces=cls.nsmap) transport = soap_node.get("transport") supported_transports = [ "http://schemas.xmlsoap.org/soap/http", "http://www.w3.org/2003/05/soap/bindings/HTTP/", ] if transport not in supported_transports: raise NotImplementedError( "The binding transport %s is not supported (only soap/http)" % (transport) ) default_style = soap_node.get("style", "document") obj = cls(definitions.wsdl, name, port_name, transport, default_style) for node in xmlelement.findall("wsdl:operation", namespaces=cls.nsmap): operation = SoapOperation.parse(definitions, node, obj, nsmap=cls.nsmap) obj._operation_add(operation) return obj class Soap11Binding(SoapBinding): nsmap = { "soap": ns.SOAP_11, "soap-env": ns.SOAP_ENV_11, "wsdl": ns.WSDL, "xsd": ns.XSD, } def process_error(self, doc, operation): fault_node = doc.find("soap-env:Body/soap-env:Fault", namespaces=self.nsmap) if fault_node is None: raise Fault( message="Unknown fault occured", code=None, actor=None, detail=etree_to_string(doc), ) def get_text(name): child = fault_node.find(name) if child is not None: return child.text raise Fault( message=get_text("faultstring"), code=get_text("faultcode"), actor=get_text("faultactor"), detail=fault_node.find("detail"), ) def _set_http_headers(self, serialized, operation): serialized.headers["Content-Type"] = "text/xml; charset=utf-8" class Soap12Binding(SoapBinding): nsmap = { "soap": ns.SOAP_12, "soap-env": ns.SOAP_ENV_12, "wsdl": ns.WSDL, "xsd": ns.XSD, } def process_error(self, doc, operation): fault_node = doc.find("soap-env:Body/soap-env:Fault", namespaces=self.nsmap) if fault_node is None: raise Fault( message="Unknown fault occured", code=None, actor=None, detail=etree_to_string(doc), ) def get_text(name): child = fault_node.find(name) if child is not None: return child.text message = fault_node.findtext( "soap-env:Reason/soap-env:Text", namespaces=self.nsmap ) code = fault_node.findtext( "soap-env:Code/soap-env:Value", namespaces=self.nsmap ) # Extract the fault subcodes. These can be nested, as in subcodes can # also contain other subcodes. subcodes = [] subcode_element = fault_node.find( "soap-env:Code/soap-env:Subcode", namespaces=self.nsmap ) while subcode_element is not None: subcode_value_element = subcode_element.find( "soap-env:Value", namespaces=self.nsmap ) subcode_qname = as_qname( subcode_value_element.text, subcode_value_element.nsmap, None ) subcodes.append(subcode_qname) subcode_element = subcode_element.find( "soap-env:Subcode", namespaces=self.nsmap ) # TODO: We should use the fault message as defined in the wsdl. detail_node = fault_node.find("soap-env:Detail", namespaces=self.nsmap) raise Fault( message=message, code=code, actor=None, detail=detail_node, subcodes=subcodes, ) def _set_http_headers(self, serialized, operation): serialized.headers["Content-Type"] = "; ".join( [ "application/soap+xml", "charset=utf-8", 'action="%s"' % operation.soapaction, ] ) class SoapOperation(Operation): """Represent's an operation within a specific binding.""" def __init__(self, name, binding, nsmap, soapaction, style): super(SoapOperation, self).__init__(name, binding) self.nsmap = nsmap self.soapaction = soapaction self.style = style def process_reply(self, envelope): envelope_qname = etree.QName(self.nsmap["soap-env"], "Envelope") if envelope.tag != envelope_qname: raise XMLSyntaxError( ( "The XML returned by the server does not contain a valid " + "{%s}Envelope root element. The root element found is %s " ) % (envelope_qname.namespace, envelope.tag) ) if self.output: return self.output.deserialize(envelope) @classmethod def parse(cls, definitions, xmlelement, binding, nsmap): """ Definition:: <wsdl:operation name="nmtoken"> * <soap:operation soapAction="uri"? style="rpc|document"?>? <wsdl:input name="nmtoken"? > ? <soap:body use="literal"/> </wsdl:input> <wsdl:output name="nmtoken"? > ? <-- extensibility element (4) --> * </wsdl:output> <wsdl:fault name="nmtoken"> * <-- extensibility element (5) --> * </wsdl:fault> </wsdl:operation> Example:: <wsdl:operation name="GetLastTradePrice"> <soap:operation soapAction="http://example.com/GetLastTradePrice"/> <wsdl:input> <soap:body use="literal"/> </wsdl:input> <wsdl:output> </wsdl:output> <wsdl:fault name="dataFault"> <soap:fault name="dataFault" use="literal"/> </wsdl:fault> </operation> """ name = xmlelement.get("name") # The soap:operation element is required for soap/http bindings # and may be omitted for other bindings. soap_node = xmlelement.find("soap:operation", namespaces=binding.nsmap) action = None if soap_node is not None: action = soap_node.get("soapAction") style = soap_node.get("style", binding.default_style) else: style = binding.default_style obj = cls(name, binding, nsmap, action, style) if style == "rpc": message_class = RpcMessage else: message_class = DocumentMessage for node in xmlelement: tag_name = etree.QName(node.tag).localname if tag_name not in ("input", "output", "fault"): continue msg = message_class.parse( definitions=definitions, xmlelement=node, operation=obj, nsmap=nsmap, type=tag_name, ) if tag_name == "fault": obj.faults[msg.name] = msg else: setattr(obj, tag_name, msg) return obj def resolve(self, definitions): super(SoapOperation, self).resolve(definitions) for name, fault in self.faults.items(): if name in self.abstract.fault_messages: fault.resolve(definitions, self.abstract.fault_messages[name]) if self.output: self.output.resolve(definitions, self.abstract.output_message) if self.input: self.input.resolve(definitions, self.abstract.input_message)
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/wsdl/bindings/soap.py
soap.py
import logging import six from lxml import etree from zeep import ns from zeep.exceptions import Fault from zeep.utils import qname_attr from zeep.wsdl import messages from zeep.wsdl.definitions import Binding, Operation logger = logging.getLogger(__name__) NSMAP = {"http": ns.HTTP, "wsdl": ns.WSDL, "mime": ns.MIME} class HttpBinding(Binding): def create_message(self, operation, *args, **kwargs): if isinstance(operation, six.string_types): operation = self.get(operation) if not operation: raise ValueError("Operation not found") return operation.create(*args, **kwargs) def process_service_port(self, xmlelement, force_https=False): address_node = xmlelement.find("http:address", namespaces=NSMAP) if address_node is None: raise ValueError("No `http:address` node found") # Force the usage of HTTPS when the force_https boolean is true location = address_node.get("location") if force_https and location and location.startswith("http://"): logger.warning("Forcing http:address location to HTTPS") location = "https://" + location[8:] return {"address": location} @classmethod def parse(cls, definitions, xmlelement): name = qname_attr(xmlelement, "name", definitions.target_namespace) port_name = qname_attr(xmlelement, "type", definitions.target_namespace) obj = cls(definitions.wsdl, name, port_name) for node in xmlelement.findall("wsdl:operation", namespaces=NSMAP): operation = HttpOperation.parse(definitions, node, obj) obj._operation_add(operation) return obj def process_reply(self, client, operation, response): if response.status_code != 200: return self.process_error(response.content) raise NotImplementedError("No error handling yet!") return operation.process_reply(response.content) def process_error(self, doc): raise Fault(message=doc) class HttpPostBinding(HttpBinding): def send(self, client, options, operation, args, kwargs): """Called from the service""" operation_obj = self.get(operation) if not operation_obj: raise ValueError("Operation %r not found" % operation) serialized = operation_obj.create(*args, **kwargs) url = options["address"] + serialized.path response = client.transport.post( url, serialized.content, headers=serialized.headers ) return self.process_reply(client, operation_obj, response) @classmethod def match(cls, node): """Check if this binding instance should be used to parse the given node. :param node: The node to match against :type node: lxml.etree._Element """ http_node = node.find(etree.QName(NSMAP["http"], "binding")) return http_node is not None and http_node.get("verb") == "POST" class HttpGetBinding(HttpBinding): def send(self, client, options, operation, args, kwargs): """Called from the service""" operation_obj = self.get(operation) if not operation_obj: raise ValueError("Operation %r not found" % operation) serialized = operation_obj.create(*args, **kwargs) url = options["address"] + serialized.path response = client.transport.get( url, serialized.content, headers=serialized.headers ) return self.process_reply(client, operation_obj, response) @classmethod def match(cls, node): """Check if this binding instance should be used to parse the given node. :param node: The node to match against :type node: lxml.etree._Element """ http_node = node.find(etree.QName(ns.HTTP, "binding")) return http_node is not None and http_node.get("verb") == "GET" class HttpOperation(Operation): def __init__(self, name, binding, location): super(HttpOperation, self).__init__(name, binding) self.location = location def process_reply(self, envelope): return self.output.deserialize(envelope) @classmethod def parse(cls, definitions, xmlelement, binding): """ <wsdl:operation name="GetLastTradePrice"> <http:operation location="GetLastTradePrice"/> <wsdl:input> <mime:content type="application/x-www-form-urlencoded"/> </wsdl:input> <wsdl:output> <mime:mimeXml/> </wsdl:output> </wsdl:operation> """ name = xmlelement.get("name") http_operation = xmlelement.find("http:operation", namespaces=NSMAP) location = http_operation.get("location") obj = cls(name, binding, location) for node in xmlelement: tag_name = etree.QName(node.tag).localname if tag_name not in ("input", "output"): continue # XXX Multiple mime types may be declared as alternatives message_node = None nodes = list(node) if len(nodes) > 0: message_node = nodes[0] message_class = None if message_node is not None: if message_node.tag == etree.QName(ns.HTTP, "urlEncoded"): message_class = messages.UrlEncoded elif message_node.tag == etree.QName(ns.HTTP, "urlReplacement"): message_class = messages.UrlReplacement elif message_node.tag == etree.QName(ns.MIME, "content"): message_class = messages.MimeContent elif message_node.tag == etree.QName(ns.MIME, "mimeXml"): message_class = messages.MimeXML if message_class: msg = message_class.parse(definitions, node, obj) assert msg setattr(obj, tag_name, msg) return obj def resolve(self, definitions): super(HttpOperation, self).resolve(definitions) if self.output: self.output.resolve(definitions, self.abstract.output_message) if self.input: self.input.resolve(definitions, self.abstract.input_message)
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/wsdl/bindings/http.py
http.py
import base64 import hashlib import os from zeep import ns from zeep.wsse import utils class UsernameToken(object): """UsernameToken Profile 1.1 https://docs.oasis-open.org/wss/v1.1/wss-v1.1-spec-os-UsernameTokenProfile.pdf Example response using PasswordText:: <wsse:Security> <wsse:UsernameToken> <wsse:Username>scott</wsse:Username> <wsse:Password Type="wsse:PasswordText">password</wsse:Password> </wsse:UsernameToken> </wsse:Security> Example using PasswordDigest:: <wsse:Security> <wsse:UsernameToken> <wsse:Username>NNK</wsse:Username> <wsse:Password Type="wsse:PasswordDigest"> weYI3nXd8LjMNVksCKFV8t3rgHh3Rw== </wsse:Password> <wsse:Nonce>WScqanjCEAC4mQoBE07sAQ==</wsse:Nonce> <wsu:Created>2003-07-16T01:24:32Z</wsu:Created> </wsse:UsernameToken> </wsse:Security> """ username_token_profile_ns = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0" # noqa soap_message_secutity_ns = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0" # noqa def __init__( self, username, password=None, password_digest=None, use_digest=False, nonce=None, created=None, timestamp_token=None, ): self.username = username self.password = password self.password_digest = password_digest self.nonce = nonce self.created = created self.use_digest = use_digest self.timestamp_token = timestamp_token def apply(self, envelope, headers): security = utils.get_security_header(envelope) # The token placeholder might already exists since it is specified in # the WSDL. token = security.find("{%s}UsernameToken" % ns.WSSE) if token is None: token = utils.WSSE.UsernameToken() security.append(token) if self.timestamp_token is not None: security.append(self.timestamp_token) # Create the sub elements of the UsernameToken element elements = [utils.WSSE.Username(self.username)] if self.password is not None or self.password_digest is not None: if self.use_digest: elements.extend(self._create_password_digest()) else: elements.extend(self._create_password_text()) token.extend(elements) return envelope, headers def verify(self, envelope): pass def _create_password_text(self): return [ utils.WSSE.Password( self.password, Type="%s#PasswordText" % self.username_token_profile_ns ) ] def _create_password_digest(self): if self.nonce: nonce = self.nonce.encode("utf-8") else: nonce = os.urandom(16) timestamp = utils.get_timestamp(self.created) # digest = Base64 ( SHA-1 ( nonce + created + password ) ) if not self.password_digest: digest = base64.b64encode( hashlib.sha1( nonce + timestamp.encode("utf-8") + self.password.encode("utf-8") ).digest() ).decode("ascii") else: digest = self.password_digest return [ utils.WSSE.Password( digest, Type="%s#PasswordDigest" % self.username_token_profile_ns ), utils.WSSE.Nonce( base64.b64encode(nonce).decode("utf-8"), EncodingType="%s#Base64Binary" % self.soap_message_secutity_ns, ), utils.WSU.Created(timestamp), ]
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/wsse/username.py
username.py
from lxml import etree from lxml.etree import QName from zeep import ns from zeep.exceptions import SignatureVerificationFailed from zeep.utils import detect_soap_env from zeep.wsse.utils import ensure_id, get_security_header try: import xmlsec except ImportError: xmlsec = None # SOAP envelope SOAP_NS = "http://schemas.xmlsoap.org/soap/envelope/" def _read_file(f_name): with open(f_name, "rb") as f: return f.read() def _make_sign_key(key_data, cert_data, password): key = xmlsec.Key.from_memory(key_data, xmlsec.KeyFormat.PEM, password) key.load_cert_from_memory(cert_data, xmlsec.KeyFormat.PEM) return key def _make_verify_key(cert_data): key = xmlsec.Key.from_memory(cert_data, xmlsec.KeyFormat.CERT_PEM, None) return key class MemorySignature(object): """Sign given SOAP envelope with WSSE sig using given key and cert.""" def __init__( self, key_data, cert_data, res_cert_data, password=None, signature_method=None, digest_method=None, ): check_xmlsec_import() self.key_data = key_data self.cert_data = cert_data self.res_cert_data = res_cert_data self.password = password self.digest_method = digest_method self.signature_method = signature_method def apply(self, envelope, headers): key = _make_sign_key(self.key_data, self.cert_data, self.password) _sign_envelope_with_key( envelope, key, self.signature_method, self.digest_method ) return envelope, headers def verify(self, envelope): key = _make_verify_key(self.cert_data) _verify_envelope_with_key(envelope, key) return envelope def verify_response(self, envelope): key = _make_verify_key(self.res_cert_data) _verify_envelope_with_key(envelope, key) return envelope class Signature(MemorySignature): """Sign given SOAP envelope with WSSE sig using given key file and cert file.""" def __init__( self, key_file, certfile, response_certfile, password=None, signature_method=None, digest_method=None, ): super(Signature, self).__init__( _read_file(key_file), _read_file(certfile), _read_file(response_certfile), password, signature_method, digest_method, ) class BinarySignature(Signature): """Sign given SOAP envelope with WSSE sig using given key file and cert file. Place the key information into BinarySecurityElement.""" def apply(self, envelope, headers): key = _make_sign_key(self.key_data, self.cert_data, self.password) _sign_envelope_with_key_binary( envelope, key, self.signature_method, self.digest_method ) return envelope, headers def check_xmlsec_import(): if xmlsec is None: raise ImportError( "The xmlsec module is required for wsse.Signature()\n" + "You can install xmlsec with: pip install xmlsec\n" + "or install zeep via: pip install zeep[xmlsec]\n" ) def sign_envelope( envelope, keyfile, certfile, password=None, signature_method=None, digest_method=None, ): """Sign given SOAP envelope with WSSE sig using given key and cert. Sign the wsu:Timestamp node in the wsse:Security header and the soap:Body; both must be present. Add a ds:Signature node in the wsse:Security header containing the signature. Use EXCL-C14N transforms to normalize the signed XML (so that irrelevant whitespace or attribute ordering changes don't invalidate the signature). Use SHA1 signatures. Expects to sign an incoming document something like this (xmlns attributes omitted for readability): <soap:Envelope> <soap:Header> <wsse:Security mustUnderstand="true"> <wsu:Timestamp> <wsu:Created>2015-06-25T21:53:25.246276+00:00</wsu:Created> <wsu:Expires>2015-06-25T21:58:25.246276+00:00</wsu:Expires> </wsu:Timestamp> </wsse:Security> </soap:Header> <soap:Body> ... </soap:Body> </soap:Envelope> After signing, the sample document would look something like this (note the added wsu:Id attr on the soap:Body and wsu:Timestamp nodes, and the added ds:Signature node in the header, with ds:Reference nodes with URI attribute referencing the wsu:Id of the signed nodes): <soap:Envelope> <soap:Header> <wsse:Security mustUnderstand="true"> <Signature xmlns="http://www.w3.org/2000/09/xmldsig#"> <SignedInfo> <CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/> <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/> <Reference URI="#id-d0f9fd77-f193-471f-8bab-ba9c5afa3e76"> <Transforms> <Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/> </Transforms> <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/> <DigestValue>nnjjqTKxwl1hT/2RUsBuszgjTbI=</DigestValue> </Reference> <Reference URI="#id-7c425ac1-534a-4478-b5fe-6cae0690f08d"> <Transforms> <Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/> </Transforms> <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/> <DigestValue>qAATZaSqAr9fta9ApbGrFWDuCCQ=</DigestValue> </Reference> </SignedInfo> <SignatureValue>Hz8jtQb...bOdT6ZdTQ==</SignatureValue> <KeyInfo> <wsse:SecurityTokenReference> <X509Data> <X509Certificate>MIIDnzC...Ia2qKQ==</X509Certificate> <X509IssuerSerial> <X509IssuerName>...</X509IssuerName> <X509SerialNumber>...</X509SerialNumber> </X509IssuerSerial> </X509Data> </wsse:SecurityTokenReference> </KeyInfo> </Signature> <wsu:Timestamp wsu:Id="id-7c425ac1-534a-4478-b5fe-6cae0690f08d"> <wsu:Created>2015-06-25T22:00:29.821700+00:00</wsu:Created> <wsu:Expires>2015-06-25T22:05:29.821700+00:00</wsu:Expires> </wsu:Timestamp> </wsse:Security> </soap:Header> <soap:Body wsu:Id="id-d0f9fd77-f193-471f-8bab-ba9c5afa3e76"> ... </soap:Body> </soap:Envelope> """ # Load the signing key and certificate. key = _make_sign_key(_read_file(keyfile), _read_file(certfile), password) return _sign_envelope_with_key(envelope, key, signature_method, digest_method) def _signature_prepare(envelope, key, signature_method, digest_method): """Prepare envelope and sign.""" soap_env = detect_soap_env(envelope) # Create the Signature node. signature = xmlsec.template.create( envelope, xmlsec.Transform.EXCL_C14N, signature_method or xmlsec.Transform.RSA_SHA1, ) # Add a KeyInfo node with X509Data child to the Signature. XMLSec will fill # in this template with the actual certificate details when it signs. key_info = xmlsec.template.ensure_key_info(signature) x509_data = xmlsec.template.add_x509_data(key_info) xmlsec.template.x509_data_add_issuer_serial(x509_data) xmlsec.template.x509_data_add_certificate(x509_data) # Insert the Signature node in the wsse:Security header. security = get_security_header(envelope) security.insert(0, signature) # Perform the actual signing. ctx = xmlsec.SignatureContext() ctx.key = key _sign_node(ctx, signature, envelope.find(QName(soap_env, "Body")), digest_method) timestamp = security.find(QName(ns.WSU, "Timestamp")) if timestamp != None: _sign_node(ctx, signature, timestamp, digest_method) ctx.sign(signature) # Place the X509 data inside a WSSE SecurityTokenReference within # KeyInfo. The recipient expects this structure, but we can't rearrange # like this until after signing, because otherwise xmlsec won't populate # the X509 data (because it doesn't understand WSSE). sec_token_ref = etree.SubElement(key_info, QName(ns.WSSE, "SecurityTokenReference")) return security, sec_token_ref, x509_data def _sign_envelope_with_key(envelope, key, signature_method, digest_method): _, sec_token_ref, x509_data = _signature_prepare( envelope, key, signature_method, digest_method ) sec_token_ref.append(x509_data) def _sign_envelope_with_key_binary(envelope, key, signature_method, digest_method): security, sec_token_ref, x509_data = _signature_prepare( envelope, key, signature_method, digest_method ) ref = etree.SubElement( sec_token_ref, QName(ns.WSSE, "Reference"), { "ValueType": "http://docs.oasis-open.org/wss/2004/01/" "oasis-200401-wss-x509-token-profile-1.0#X509v3" }, ) bintok = etree.Element( QName(ns.WSSE, "BinarySecurityToken"), { "ValueType": "http://docs.oasis-open.org/wss/2004/01/" "oasis-200401-wss-x509-token-profile-1.0#X509v3", "EncodingType": "http://docs.oasis-open.org/wss/2004/01/" "oasis-200401-wss-soap-message-security-1.0#Base64Binary", }, ) ref.attrib["URI"] = "#" + ensure_id(bintok) bintok.text = x509_data.find(QName(ns.DS, "X509Certificate")).text security.insert(1, bintok) x509_data.getparent().remove(x509_data) def verify_envelope(envelope, certfile): """Verify WS-Security signature on given SOAP envelope with given cert. Expects a document like that found in the sample XML in the ``sign()`` docstring. Raise SignatureVerificationFailed on failure, silent on success. """ key = _make_verify_key(_read_file(certfile)) return _verify_envelope_with_key(envelope, key) def _verify_envelope_with_key(envelope, key): soap_env = detect_soap_env(envelope) header = envelope.find(QName(soap_env, "Header")) if header is None: raise SignatureVerificationFailed() security = header.find(QName(ns.WSSE, "Security")) signature = security.find(QName(ns.DS, "Signature")) ctx = xmlsec.SignatureContext() # Find each signed element and register its ID with the signing context. refs = signature.xpath("ds:SignedInfo/ds:Reference", namespaces={"ds": ns.DS}) for ref in refs: # Get the reference URI and cut off the initial '#' referenced_id = ref.get("URI")[1:] referenced = envelope.xpath( "//*[@wsu:Id='%s']" % referenced_id, namespaces={"wsu": ns.WSU} )[0] ctx.register_id(referenced, "Id", ns.WSU) ctx.key = key try: ctx.verify(signature) except xmlsec.Error: # Sadly xmlsec gives us no details about the reason for the failure, so # we have nothing to pass on except that verification failed. raise SignatureVerificationFailed() def _sign_node(ctx, signature, target, digest_method=None): """Add sig for ``target`` in ``signature`` node, using ``ctx`` context. Doesn't actually perform the signing; ``ctx.sign(signature)`` should be called later to do that. Adds a Reference node to the signature with URI attribute pointing to the target node, and registers the target node's ID so XMLSec will be able to find the target node by ID when it signs. """ # Ensure the target node has a wsu:Id attribute and get its value. node_id = ensure_id(target) # Unlike HTML, XML doesn't have a single standardized Id. WSSE suggests the # use of the wsu:Id attribute for this purpose, but XMLSec doesn't # understand that natively. So for XMLSec to be able to find the referenced # node by id, we have to tell xmlsec about it using the register_id method. ctx.register_id(target, "Id", ns.WSU) # Add reference to signature with URI attribute pointing to that ID. ref = xmlsec.template.add_reference( signature, digest_method or xmlsec.Transform.SHA1, uri="#" + node_id ) # This is an XML normalization transform which will be performed on the # target node contents before signing. This ensures that changes to # irrelevant whitespace, attribute ordering, etc won't invalidate the # signature. xmlsec.template.add_transform(ref, xmlsec.Transform.EXCL_C14N)
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/wsse/signature.py
signature.py
import asyncio import logging import aiohttp from requests import Response from zeep.asyncio import bindings from zeep.exceptions import TransportError from zeep.transports import Transport from zeep.utils import get_version from zeep.wsdl.utils import etree_to_string try: from async_timeout import timeout as aio_timeout # Python 3.6+ except ImportError: from aiohttp import Timeout as aio_timeout # Python 3.5, aiohttp < 3 __all__ = ["AsyncTransport"] class AsyncTransport(Transport): """Asynchronous Transport class using aiohttp.""" binding_classes = [bindings.AsyncSoap11Binding, bindings.AsyncSoap12Binding] def __init__( self, loop, cache=None, timeout=300, operation_timeout=None, session=None, verify_ssl=True, proxy=None, ): self.loop = loop if loop else asyncio.get_event_loop() self.cache = cache self.load_timeout = timeout self.operation_timeout = operation_timeout self.logger = logging.getLogger(__name__) self.verify_ssl = verify_ssl self.proxy = proxy self.session = session or aiohttp.ClientSession(loop=self.loop) self._close_session = session is None self.session._default_headers[ "User-Agent" ] = "Zeep/%s (www.python-zeep.org)" % (get_version()) def __del__(self): if self._close_session: # aiohttp.ClientSession.close() is async, # call the underlying sync function instead. if self.session.connector is not None: self.session.connector.close() def _load_remote_data(self, url): result = None if self.loop.is_running(): raise RuntimeError( "WSDL loading is not asynchronous yet. " "Instantiate the zeep client outside the asyncio event loop." ) async def _load_remote_data_async(): nonlocal result with aio_timeout(self.load_timeout): response = await self.session.get(url) result = await response.read() try: response.raise_for_status() except aiohttp.ClientError as exc: raise TransportError( message=str(exc), status_code=response.status, content=result ).with_traceback(exc.__traceback__) from exc # Block until we have the data self.loop.run_until_complete(_load_remote_data_async()) return result async def post(self, address, message, headers): self.logger.debug("HTTP Post to %s:\n%s", address, message) with aio_timeout(self.operation_timeout): response = await self.session.post( address, data=message, headers=headers, verify_ssl=self.verify_ssl, proxy=self.proxy, ) self.logger.debug( "HTTP Response from %s (status: %d):\n%s", address, response.status, await response.read(), ) return response async def post_xml(self, address, envelope, headers): message = etree_to_string(envelope) response = await self.post(address, message, headers) return await self.new_response(response) async def get(self, address, params, headers): with aio_timeout(self.operation_timeout): response = await self.session.get( address, params=params, headers=headers, verify_ssl=self.verify_ssl, proxy=self.proxy, ) return await self.new_response(response) async def new_response(self, response): """Convert an aiohttp.Response object to a requests.Response object""" new = Response() new._content = await response.read() new.status_code = response.status new.headers = response.headers new.cookies = response.cookies new.encoding = response.charset return new
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/asyncio/transport.py
transport.py
import logging import urllib from requests import Response, Session from requests.auth import HTTPBasicAuth, HTTPDigestAuth from tornado import gen, httpclient from zeep.tornado import bindings from zeep.transports import Transport from zeep.utils import get_version from zeep.wsdl.utils import etree_to_string __all__ = ["TornadoAsyncTransport"] class TornadoAsyncTransport(Transport): """Asynchronous Transport class using tornado gen.""" binding_classes = [bindings.AsyncSoap11Binding, bindings.AsyncSoap12Binding] def __init__(self, cache=None, timeout=300, operation_timeout=None, session=None): self.cache = cache self.load_timeout = timeout self.operation_timeout = operation_timeout self.logger = logging.getLogger(__name__) self.session = session or Session() self.session.headers["User-Agent"] = "Zeep/%s (www.python-zeep.org)" % ( get_version() ) def _load_remote_data(self, url): client = httpclient.HTTPClient() kwargs = { "method": "GET", "connect_timeout": self.load_timeout, "request_timeout": self.load_timeout, } http_req = httpclient.HTTPRequest(url, **kwargs) response = client.fetch(http_req) return response.body @gen.coroutine def post(self, address, message, headers): response = yield self.fetch(address, "POST", headers, message) raise gen.Return(response) @gen.coroutine def post_xml(self, address, envelope, headers): message = etree_to_string(envelope) response = yield self.post(address, message, headers) raise gen.Return(response) @gen.coroutine def get(self, address, params, headers): if params: address += "?" + urllib.urlencode(params) response = yield self.fetch(address, "GET", headers) raise gen.Return(response) @gen.coroutine def fetch(self, address, method, headers, message=None): async_client = httpclient.AsyncHTTPClient() # extracting auth auth_username = None auth_password = None auth_mode = None if self.session.auth: if type(self.session.auth) is tuple: auth_username = self.session.auth[0] auth_password = self.session.auth[1] auth_mode = "basic" elif type(self.session.auth) is HTTPBasicAuth: auth_username = self.session.username auth_password = self.session.password auth_mode = "basic" elif type(self.session.auth) is HTTPDigestAuth: auth_username = self.session.username auth_password = self.session.password auth_mode = "digest" else: raise Exception("Not supported authentication.") # extracting client cert client_cert = None client_key = None ca_certs = None if self.session.cert: if type(self.session.cert) is str: ca_certs = self.session.cert elif type(self.session.cert) is tuple: client_cert = self.session.cert[0] client_key = self.session.cert[1] session_headers = dict(self.session.headers.items()) kwargs = { "method": method, "connect_timeout": self.operation_timeout, "request_timeout": self.operation_timeout, "headers": dict(headers, **session_headers), "auth_username": auth_username, "auth_password": auth_password, "auth_mode": auth_mode, "validate_cert": bool(self.session.verify), "ca_certs": ca_certs, "client_key": client_key, "client_cert": client_cert, } if message: kwargs["body"] = message http_req = httpclient.HTTPRequest(address, **kwargs) response = yield async_client.fetch(http_req, raise_error=False) raise gen.Return(self.new_response(response)) @staticmethod def new_response(response): """Convert an tornado.HTTPResponse object to a requests.Response object""" new = Response() new._content = response.body new.status_code = response.code new.headers = dict(response.headers.get_all()) return new
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/tornado/transport.py
transport.py
import logging from collections import OrderedDict from lxml import etree from zeep import exceptions, ns from zeep.loader import load_external from zeep.settings import Settings from zeep.xsd import const from zeep.xsd.elements import builtins as xsd_builtins_elements from zeep.xsd.types import builtins as xsd_builtins_types from zeep.xsd.visitor import SchemaVisitor logger = logging.getLogger(__name__) class Schema(object): """A schema is a collection of schema documents.""" def __init__(self, node=None, transport=None, location=None, settings=None): """ :param node: :param transport: :param location: :param settings: The settings object """ self.settings = settings or Settings() self._transport = transport self.documents = _SchemaContainer() self._prefix_map_auto = {} self._prefix_map_custom = {} self._load_default_documents() if not isinstance(node, list): nodes = [node] if node is not None else [] else: nodes = node self.add_documents(nodes, location) def __repr__(self): main_doc = self.root_document if main_doc: return "<Schema(location=%r, tns=%r)>" % ( main_doc._location, main_doc._target_namespace, ) return "<Schema()>" @property def prefix_map(self): retval = {} retval.update(self._prefix_map_custom) retval.update( {k: v for k, v in self._prefix_map_auto.items() if v not in retval.values()} ) return retval @property def root_document(self): return next((doc for doc in self.documents if not doc._is_internal), None) @property def is_empty(self): """Boolean to indicate if this schema contains any types or elements""" return all(document.is_empty for document in self.documents) @property def namespaces(self): return self.documents.get_all_namespaces() @property def elements(self): """Yield all globla xsd.Type objects :rtype: Iterable of zeep.xsd.Element """ seen = set() for document in self.documents: for element in document._elements.values(): if element.qname not in seen: yield element seen.add(element.qname) @property def types(self): """Yield all global xsd.Type objects :rtype: Iterable of zeep.xsd.ComplexType """ seen = set() for document in self.documents: for type_ in document._types.values(): if type_.qname not in seen: yield type_ seen.add(type_.qname) def add_documents(self, schema_nodes, location): """ :type schema_nodes: List[lxml.etree._Element] :type location: str :type target_namespace: Optional[str] """ resolve_queue = [] for node in schema_nodes: document = self.create_new_document(node, location) resolve_queue.append(document) for document in resolve_queue: document.resolve() self._prefix_map_auto = self._create_prefix_map() def add_document_by_url(self, url): schema_node = load_external(url, self._transport, settings=self.settings) document = self.create_new_document(schema_node, url=url) document.resolve() def get_element(self, qname): """Return a global xsd.Element object with the given qname :rtype: zeep.xsd.Group """ qname = self._create_qname(qname) return self._get_instance(qname, "get_element", "element") def get_type(self, qname, fail_silently=False): """Return a global xsd.Type object with the given qname :rtype: zeep.xsd.ComplexType or zeep.xsd.AnySimpleType """ qname = self._create_qname(qname) try: return self._get_instance(qname, "get_type", "type") except exceptions.NamespaceError as exc: if fail_silently: logger.debug(str(exc)) else: raise def get_group(self, qname): """Return a global xsd.Group object with the given qname. :rtype: zeep.xsd.Group """ return self._get_instance(qname, "get_group", "group") def get_attribute(self, qname): """Return a global xsd.attributeGroup object with the given qname :rtype: zeep.xsd.Attribute """ return self._get_instance(qname, "get_attribute", "attribute") def get_attribute_group(self, qname): """Return a global xsd.attributeGroup object with the given qname :rtype: zeep.xsd.AttributeGroup """ return self._get_instance(qname, "get_attribute_group", "attributeGroup") def set_ns_prefix(self, prefix, namespace): self._prefix_map_custom[prefix] = namespace def get_ns_prefix(self, prefix): try: try: return self._prefix_map_custom[prefix] except KeyError: return self._prefix_map_auto[prefix] except KeyError: raise ValueError("No such prefix %r" % prefix) def get_shorthand_for_ns(self, namespace): for prefix, other_namespace in self._prefix_map_auto.items(): if namespace == other_namespace: return prefix for prefix, other_namespace in self._prefix_map_custom.items(): if namespace == other_namespace: return prefix if namespace == "http://schemas.xmlsoap.org/soap/envelope/": return "soap-env" return namespace def create_new_document(self, node, url, base_url=None, target_namespace=None): """ :rtype: zeep.xsd.schema.SchemaDocument """ namespace = node.get("targetNamespace") if node is not None else None if not namespace: namespace = target_namespace if base_url is None: base_url = url schema = SchemaDocument(namespace, url, base_url) self.documents.add(schema) schema.load(self, node) return schema def merge(self, schema): """Merge an other XSD schema in this one""" for document in schema.documents: self.documents.add(document) self._prefix_map_auto = self._create_prefix_map() def deserialize(self, node): elm = self.get_element(node.tag) return elm.parse(node, schema=self) def _load_default_documents(self): schema = SchemaDocument(ns.XSD, None, None) for cls in xsd_builtins_types._types: instance = cls(is_global=True) schema.register_type(cls._default_qname, instance) for cls in xsd_builtins_elements._elements: instance = cls() schema.register_element(cls.qname, instance) schema._is_internal = True self.documents.add(schema) return schema def _get_instance(self, qname, method_name, name): """Return an object from one of the SchemaDocument's""" qname = self._create_qname(qname) try: last_exception = None for schema in self._get_schema_documents(qname.namespace): method = getattr(schema, method_name) try: return method(qname) except exceptions.LookupError as exc: last_exception = exc continue raise last_exception except exceptions.NamespaceError: raise exceptions.NamespaceError( ( "Unable to resolve %s %s. " + "No schema available for the namespace %r." ) % (name, qname.text, qname.namespace) ) def _create_qname(self, name): """Create an `lxml.etree.QName()` object for the given qname string. This also expands the shorthand notation. :rtype: lxml.etree.QNaame """ if isinstance(name, etree.QName): return name if not name.startswith("{") and ":" in name and self._prefix_map_auto: prefix, localname = name.split(":", 1) if prefix in self._prefix_map_custom: return etree.QName(self._prefix_map_custom[prefix], localname) elif prefix in self._prefix_map_auto: return etree.QName(self._prefix_map_auto[prefix], localname) else: raise ValueError("No namespace defined for the prefix %r" % prefix) else: return etree.QName(name) def _create_prefix_map(self): prefix_map = {"xsd": "http://www.w3.org/2001/XMLSchema"} i = 0 for namespace in self.documents.get_all_namespaces(): if namespace is None or namespace in prefix_map.values(): continue prefix_map["ns%d" % i] = namespace i += 1 return prefix_map def _get_schema_documents(self, namespace, fail_silently=False): """Return a list of SchemaDocument's for the given namespace. :rtype: list of SchemaDocument """ if ( not self.documents.has_schema_document_for_ns(namespace) and namespace in const.AUTO_IMPORT_NAMESPACES ): logger.debug("Auto importing missing known schema: %s", namespace) self.add_document_by_url(namespace) return self.documents.get_by_namespace(namespace, fail_silently) class _SchemaContainer(object): """Container instances to store multiple SchemaDocument objects per namespace. """ def __init__(self): self._instances = OrderedDict() def __iter__(self): for document in self.values(): yield document def add(self, document): """Append a schema document :param document: zeep.xsd.schema.SchemaDocument """ logger.debug( "Add document with tns %s to schema %s", document.namespace, id(self) ) documents = self._instances.setdefault(document.namespace, []) documents.append(document) def get_all_namespaces(self): return self._instances.keys() def get_by_namespace(self, namespace, fail_silently): if namespace not in self._instances: if fail_silently: return [] raise exceptions.NamespaceError( "No schema available for the namespace %r" % namespace ) return self._instances[namespace] def get_by_namespace_and_location(self, namespace, location): """Return list of SchemaDocument's for the given namespace AND location. :rtype: zeep.xsd.schema.SchemaDocument """ documents = self.get_by_namespace(namespace, fail_silently=True) for document in documents: if document._location == location: return document def has_schema_document_for_ns(self, namespace): """Return a boolean if there is a SchemaDocument for the namespace. :rtype: boolean """ return namespace in self._instances def values(self): for documents in self._instances.values(): for document in documents: yield document class SchemaDocument(object): """A Schema Document consists of a set of schema components for a specific target namespace. """ def __init__(self, namespace, location, base_url): logger.debug("Init schema document for %r", location) # Internal self._base_url = base_url or location self._location = location self._target_namespace = namespace self._is_internal = False self._has_empty_import = False # Containers for specific types self._attribute_groups = {} self._attributes = {} self._elements = {} self._groups = {} self._types = {} self._imports = OrderedDict() self._element_form = "unqualified" self._attribute_form = "unqualified" self._resolved = False # self._xml_schema = None def __repr__(self): return "<SchemaDocument(location=%r, tns=%r, is_empty=%r)>" % ( self._location, self._target_namespace, self.is_empty, ) @property def namespace(self): return self._target_namespace @property def is_empty(self): return not bool(self._imports or self._types or self._elements) def load(self, schema, node): """Load the XML Schema passed in via the node attribute. :type schema: zeep.xsd.schema.Schema :type node: etree._Element """ if node is None: return if not schema.documents.has_schema_document_for_ns(self._target_namespace): raise RuntimeError( "The document needs to be registered in the schema before " + "it can be loaded" ) # Disable XML schema validation for now # if len(node) > 0: # self.xml_schema = etree.XMLSchema(node) visitor = SchemaVisitor(schema, self) visitor.visit_schema(node) def resolve(self): logger.debug("Resolving in schema %s", self) if self._resolved: return self._resolved = True for schemas in self._imports.values(): for schema in schemas: schema.resolve() def _resolve_dict(val): try: for key, obj in val.items(): new = obj.resolve() assert new is not None, "resolve() should return an object" val[key] = new except exceptions.LookupError as exc: raise exceptions.LookupError( ( "Unable to resolve %(item_name)s %(qname)s in " "%(file)s. (via %(parent)s)" ) % { "item_name": exc.item_name, "qname": exc.qname, "file": exc.location, "parent": obj.qname, } ) _resolve_dict(self._attribute_groups) _resolve_dict(self._attributes) _resolve_dict(self._elements) _resolve_dict(self._groups) _resolve_dict(self._types) def register_import(self, namespace, schema): """Register an import for an other schema document. :type namespace: str :type schema: zeep.xsd.schema.SchemaDocument """ schemas = self._imports.setdefault(namespace, []) schemas.append(schema) def is_imported(self, namespace): return namespace in self._imports def register_type(self, qname, value): """Register a xsd.Type in this schema :type qname: str or etree.QName :type value: zeep.xsd.Type """ self._add_component(qname, value, self._types, "type") def register_element(self, qname, value): """Register a xsd.Element in this schema :type qname: str or etree.QName :type value: zeep.xsd.Element """ self._add_component(qname, value, self._elements, "element") def register_group(self, qname, value): """Register a xsd.Element in this schema :type qname: str or etree.QName :type value: zeep.xsd.Element """ self._add_component(qname, value, self._groups, "group") def register_attribute(self, qname, value): """Register a xsd.Element in this schema :type qname: str or etree.QName :type value: zeep.xsd.Attribute """ self._add_component(qname, value, self._attributes, "attribute") def register_attribute_group(self, qname, value): """Register a xsd.Element in this schema :type qname: str or etree.QName :type value: zeep.xsd.Group """ self._add_component(qname, value, self._attribute_groups, "attribute_group") def get_type(self, qname): """Return a xsd.Type object from this schema :rtype: zeep.xsd.ComplexType or zeep.xsd.AnySimpleType """ return self._get_component(qname, self._types, "type") def get_element(self, qname): """Return a xsd.Element object from this schema :rtype: zeep.xsd.Element """ return self._get_component(qname, self._elements, "element") def get_group(self, qname): """Return a xsd.Group object from this schema. :rtype: zeep.xsd.Group """ return self._get_component(qname, self._groups, "group") def get_attribute(self, qname): """Return a xsd.Attribute object from this schema :rtype: zeep.xsd.Attribute """ return self._get_component(qname, self._attributes, "attribute") def get_attribute_group(self, qname): """Return a xsd.AttributeGroup object from this schema :rtype: zeep.xsd.AttributeGroup """ return self._get_component(qname, self._attribute_groups, "attributeGroup") def _add_component(self, name, value, items, item_name): if isinstance(name, etree.QName): name = name.text logger.debug("register_%s(%r, %r)", item_name, name, value) items[name] = value def _get_component(self, qname, items, item_name): try: return items[qname] except KeyError: known_items = ", ".join(items.keys()) raise exceptions.LookupError( ( "No %(item_name)s '%(localname)s' in namespace %(namespace)s. " + "Available %(item_name_plural)s are: %(known_items)s" ) % { "item_name": item_name, "item_name_plural": item_name + "s", "localname": qname.localname, "namespace": qname.namespace, "known_items": known_items or " - ", }, qname=qname, item_name=item_name, location=self._location, )
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/xsd/schema.py
schema.py
from collections import OrderedDict from six import StringIO class PrettyPrinter(object): """Cleaner pprint output. Heavily inspired by the Python pprint module, but more basic for now. """ def pformat(self, obj): stream = StringIO() self._format(obj, stream) return stream.getvalue() def _format(self, obj, stream, indent=4, level=1): _repr = getattr(type(obj), "__repr__", None) write = stream.write if (isinstance(obj, dict) and _repr is dict.__repr__) or ( isinstance(obj, OrderedDict) and _repr == OrderedDict.__repr__ ): write("{\n") num = len(obj) if num > 0: for i, (key, value) in enumerate(obj.items()): write(" " * (indent * level)) write("'%s'" % key) write(": ") self._format(value, stream, level=level + 1) if i < num - 1: write(",") write("\n") write(" " * (indent * (level - 1))) write("}") elif isinstance(obj, list) and _repr is list.__repr__: write("[") num = len(obj) if num > 0: write("\n") for i, value in enumerate(obj): write(" " * (indent * level)) self._format(value, stream, level=level + 1) if i < num - 1: write(",") write("\n") write(" " * (indent * (level - 1))) write("]") else: value = repr(obj) if "\n" in value: lines = value.split("\n") num = len(lines) for i, line in enumerate(lines): if i > 0: write(" " * (indent * (level - 1))) write(line) if i < num - 1: write("\n") else: write(value)
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/xsd/printer.py
printer.py
import keyword import logging import re from lxml import etree from zeep.exceptions import XMLParseError from zeep.loader import absolute_location, load_external, normalize_location from zeep.utils import as_qname, qname_attr from zeep.xsd import elements as xsd_elements from zeep.xsd import types as xsd_types from zeep.xsd.const import AUTO_IMPORT_NAMESPACES, xsd_ns from zeep.xsd.types.unresolved import UnresolvedCustomType, UnresolvedType logger = logging.getLogger(__name__) class tags(object): pass for name in [ "schema", "import", "include", "annotation", "element", "simpleType", "complexType", "simpleContent", "complexContent", "sequence", "group", "choice", "all", "list", "union", "attribute", "any", "anyAttribute", "attributeGroup", "restriction", "extension", "notation", ]: attr = name if name not in keyword.kwlist else name + "_" setattr(tags, attr, xsd_ns(name)) class SchemaVisitor(object): """Visitor which processes XSD files and registers global elements and types in the given schema. :param schema: :type schema: zeep.xsd.schema.Schema :param document: :type document: zeep.xsd.schema.SchemaDocument """ def __init__(self, schema, document): self.document = document self.schema = schema self._includes = set() def register_element(self, qname, instance): self.document.register_element(qname, instance) def register_attribute(self, name, instance): self.document.register_attribute(name, instance) def register_type(self, qname, instance): self.document.register_type(qname, instance) def register_group(self, qname, instance): self.document.register_group(qname, instance) def register_attribute_group(self, qname, instance): self.document.register_attribute_group(qname, instance) def register_import(self, namespace, document): self.document.register_import(namespace, document) def process(self, node, parent): visit_func = self.visitors.get(node.tag) if not visit_func: raise ValueError("No visitor defined for %r" % node.tag) result = visit_func(self, node, parent) return result def process_ref_attribute(self, node, array_type=None): ref = qname_attr(node, "ref") if ref: ref = self._create_qname(ref) # Some wsdl's reference to xs:schema, we ignore that for now. It # might be better in the future to process the actual schema file # so that it is handled correctly if ref.namespace == "http://www.w3.org/2001/XMLSchema": return return xsd_elements.RefAttribute( node.tag, ref, self.schema, array_type=array_type ) def process_reference(self, node, **kwargs): ref = qname_attr(node, "ref") if not ref: return ref = self._create_qname(ref) if node.tag == tags.element: cls = xsd_elements.RefElement elif node.tag == tags.attribute: cls = xsd_elements.RefAttribute elif node.tag == tags.group: cls = xsd_elements.RefGroup elif node.tag == tags.attributeGroup: cls = xsd_elements.RefAttributeGroup return cls(node.tag, ref, self.schema, **kwargs) def visit_schema(self, node): """Visit the xsd:schema element and process all the child elements Definition:: <schema attributeFormDefault = (qualified | unqualified): unqualified blockDefault = (#all | List of (extension | restriction | substitution) : '' elementFormDefault = (qualified | unqualified): unqualified finalDefault = (#all | List of (extension | restriction | list | union): '' id = ID targetNamespace = anyURI version = token xml:lang = language {any attributes with non-schema Namespace}...> Content: ( (include | import | redefine | annotation)*, (((simpleType | complexType | group | attributeGroup) | element | attribute | notation), annotation*)*) </schema> :param node: The XML node :type node: lxml.etree._Element """ assert node is not None # A schema should always have a targetNamespace attribute, otherwise # it is called a chameleon schema. In that case the schema will inherit # the namespace of the enclosing schema/node. tns = node.get("targetNamespace") if tns: self.document._target_namespace = tns self.document._element_form = node.get("elementFormDefault", "unqualified") self.document._attribute_form = node.get("attributeFormDefault", "unqualified") for child in node: self.process(child, parent=node) def visit_import(self, node, parent): """ Definition:: <import id = ID namespace = anyURI schemaLocation = anyURI {any attributes with non-schema Namespace}...> Content: (annotation?) </import> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ schema_node = None namespace = node.get("namespace") location = node.get("schemaLocation") if location: location = normalize_location( self.schema.settings, location, self.document._base_url ) if not namespace and not self.document._target_namespace: raise XMLParseError( "The attribute 'namespace' must be existent if the " "importing schema has no target namespace.", filename=self._document.location, sourceline=node.sourceline, ) # We found an empty <import/> statement, this needs to trigger 4.1.2 # from https://www.w3.org/TR/2012/REC-xmlschema11-1-20120405/#src-resolve # for QName resolving. # In essence this means we will resolve QNames without a namespace to no # namespace instead of the target namespace. # The following code snippet works because imports have to occur before we # visit elements. if not namespace and not location: self.document._has_empty_import = True # Check if the schema is already imported before based on the # namespace. Schema's without namespace are registered as 'None' document = self.schema.documents.get_by_namespace_and_location( namespace, location ) if document: logger.debug("Returning existing schema: %r", location) self.register_import(namespace, document) return document # Hardcode the mapping between the xml namespace and the xsd for now. # This seems to fix issues with exchange wsdl's, see #220 if not location and namespace == "http://www.w3.org/XML/1998/namespace": location = "https://www.w3.org/2001/xml.xsd" # Silently ignore import statements which we can't resolve via the # namespace and doesn't have a schemaLocation attribute. if not location: logger.debug( "Ignoring import statement for namespace %r " + "(missing schemaLocation)", namespace, ) return # Load the XML schema_node = load_external( location, transport=self.schema._transport, base_url=self.document._location, settings=self.schema.settings, ) # Check if the xsd:import namespace matches the targetNamespace. If # the xsd:import statement didn't specify a namespace then make sure # that the targetNamespace wasn't declared by another schema yet. schema_tns = schema_node.get("targetNamespace") if namespace and schema_tns and namespace != schema_tns: raise XMLParseError( ( "The namespace defined on the xsd:import doesn't match the " "imported targetNamespace located at %r " ) % (location), filename=self.document._location, sourceline=node.sourceline, ) # If the imported schema doesn't define a target namespace and the # node doesn't specify it either then inherit the existing target # namespace. elif not schema_tns and not namespace: namespace = self.document._target_namespace schema = self.schema.create_new_document( schema_node, location, target_namespace=namespace ) self.register_import(namespace, schema) return schema def visit_include(self, node, parent): """ Definition:: <include id = ID schemaLocation = anyURI {any attributes with non-schema Namespace}...> Content: (annotation?) </include> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ if not node.get("schemaLocation"): raise NotImplementedError("schemaLocation is required") location = node.get("schemaLocation") if location in self._includes: return schema_node = load_external( location, self.schema._transport, base_url=self.document._base_url, settings=self.schema.settings, ) self._includes.add(location) # When the included document has no default namespace defined but the # parent document does have this then we should (atleast for #360) # transfer the default namespace to the included schema. We can't # update the nsmap of elements in lxml so we create a new schema with # the correct nsmap and move all the content there. # Included schemas must have targetNamespace equal to parent schema (the including) or None. # If included schema doesn't have default ns, then it should be set to parent's targetNs. # See Chameleon Inclusion https://www.w3.org/TR/xmlschema11-1/#chameleon-xslt if not schema_node.nsmap.get(None) and ( node.nsmap.get(None) or parent.attrib.get("targetNamespace") ): nsmap = {None: node.nsmap.get(None) or parent.attrib["targetNamespace"]} nsmap.update(schema_node.nsmap) new = etree.Element(schema_node.tag, nsmap=nsmap) for child in schema_node: new.append(child) for key, value in schema_node.attrib.items(): new.set(key, value) if not new.attrib.get("targetNamespace"): new.attrib["targetNamespace"] = parent.attrib["targetNamespace"] schema_node = new # Use the element/attribute form defaults from the schema while # processing the nodes. element_form_default = self.document._element_form attribute_form_default = self.document._attribute_form base_url = self.document._base_url self.document._element_form = schema_node.get( "elementFormDefault", "unqualified" ) self.document._attribute_form = schema_node.get( "attributeFormDefault", "unqualified" ) self.document._base_url = absolute_location(location, self.document._base_url) # Iterate directly over the children. for child in schema_node: self.process(child, parent=schema_node) self.document._element_form = element_form_default self.document._attribute_form = attribute_form_default self.document._base_url = base_url def visit_element(self, node, parent): """ Definition:: <element abstract = Boolean : false block = (#all | List of (extension | restriction | substitution)) default = string final = (#all | List of (extension | restriction)) fixed = string form = (qualified | unqualified) id = ID maxOccurs = (nonNegativeInteger | unbounded) : 1 minOccurs = nonNegativeInteger : 1 name = NCName nillable = Boolean : false ref = QName substitutionGroup = QName type = QName {any attributes with non-schema Namespace}...> Content: (annotation?, ( (simpleType | complexType)?, (unique | key | keyref)*)) </element> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ is_global = parent.tag == tags.schema # minOccurs / maxOccurs are not allowed on global elements if not is_global: min_occurs, max_occurs = _process_occurs_attrs(node) else: max_occurs = 1 min_occurs = 1 # If the element has a ref attribute then all other attributes cannot # be present. Short circuit that here. # Ref is prohibited on global elements (parent = schema) if not is_global: # Naive workaround to mark fields which are part of a choice element # as optional if parent.tag == tags.choice: min_occurs = 0 result = self.process_reference( node, min_occurs=min_occurs, max_occurs=max_occurs ) if result: return result element_form = node.get("form", self.document._element_form) if element_form == "qualified" or is_global: qname = qname_attr(node, "name", self.document._target_namespace) else: qname = etree.QName(node.get("name").strip()) children = list(node) xsd_type = None if children: value = None for child in children: if child.tag == tags.annotation: continue elif child.tag in (tags.simpleType, tags.complexType): assert not value xsd_type = self.process(child, node) if not xsd_type: node_type = qname_attr(node, "type") if node_type: xsd_type = self._get_type(node_type.text) else: xsd_type = xsd_types.AnyType() nillable = node.get("nillable") == "true" default = node.get("default") element = xsd_elements.Element( name=qname, type_=xsd_type, min_occurs=min_occurs, max_occurs=max_occurs, nillable=nillable, default=default, is_global=is_global, ) # Only register global elements if is_global: self.register_element(qname, element) return element def visit_attribute(self, node, parent): """Declares an attribute. Definition:: <attribute default = string fixed = string form = (qualified | unqualified) id = ID name = NCName ref = QName type = QName use = (optional | prohibited | required): optional {any attributes with non-schema Namespace...}> Content: (annotation?, (simpleType?)) </attribute> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ is_global = parent.tag == tags.schema # Check of wsdl:arayType array_type = node.get("{http://schemas.xmlsoap.org/wsdl/}arrayType") if array_type: match = re.match(r"([^\[]+)", array_type) if match: array_type = match.groups()[0] qname = as_qname(array_type, node.nsmap) array_type = UnresolvedType(qname, self.schema) # If the elment has a ref attribute then all other attributes cannot # be present. Short circuit that here. # Ref is prohibited on global elements (parent = schema) if not is_global: result = self.process_ref_attribute(node, array_type=array_type) if result: return result attribute_form = node.get("form", self.document._attribute_form) if attribute_form == "qualified" or is_global: name = qname_attr(node, "name", self.document._target_namespace) else: name = etree.QName(node.get("name")) annotation, items = self._pop_annotation(list(node)) if items: xsd_type = self.visit_simple_type(items[0], node) else: node_type = qname_attr(node, "type") if node_type: xsd_type = self._get_type(node_type) else: xsd_type = xsd_types.AnyType() # TODO: We ignore 'prohobited' for now required = node.get("use") == "required" default = node.get("default") attr = xsd_elements.Attribute( name, type_=xsd_type, default=default, required=required ) # Only register global elements if is_global: self.register_attribute(name, attr) return attr def visit_simple_type(self, node, parent): """ Definition:: <simpleType final = (#all | (list | union | restriction)) id = ID name = NCName {any attributes with non-schema Namespace}...> Content: (annotation?, (restriction | list | union)) </simpleType> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ if parent.tag == tags.schema: name = node.get("name") is_global = True else: name = parent.get("name", "Anonymous") is_global = False base_type = "{http://www.w3.org/2001/XMLSchema}string" qname = as_qname(name, node.nsmap, self.document._target_namespace) annotation, items = self._pop_annotation(list(node)) child = items[0] if child.tag == tags.restriction: base_type = self.visit_restriction_simple_type(child, node) xsd_type = UnresolvedCustomType(qname, base_type, self.schema) elif child.tag == tags.list: xsd_type = self.visit_list(child, node) elif child.tag == tags.union: xsd_type = self.visit_union(child, node) else: raise AssertionError("Unexpected child: %r" % child.tag) assert xsd_type is not None if is_global: self.register_type(qname, xsd_type) return xsd_type def visit_complex_type(self, node, parent): """ Definition:: <complexType abstract = Boolean : false block = (#all | List of (extension | restriction)) final = (#all | List of (extension | restriction)) id = ID mixed = Boolean : false name = NCName {any attributes with non-schema Namespace...}> Content: (annotation?, (simpleContent | complexContent | ((group | all | choice | sequence)?, ((attribute | attributeGroup)*, anyAttribute?)))) </complexType> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ children = [] base_type = "{http://www.w3.org/2001/XMLSchema}anyType" # If the complexType's parent is an element then this type is # anonymous and should have no name defined. Otherwise it's global if parent.tag == tags.schema: name = node.get("name") is_global = True else: name = parent.get("name") is_global = False qname = as_qname(name, node.nsmap, self.document._target_namespace) cls_attributes = {"__module__": "zeep.xsd.dynamic_types", "_xsd_name": qname} xsd_cls = type(name, (xsd_types.ComplexType,), cls_attributes) xsd_type = None # Process content annotation, children = self._pop_annotation(list(node)) first_tag = children[0].tag if children else None if first_tag == tags.simpleContent: base_type, attributes = self.visit_simple_content(children[0], node) xsd_type = xsd_cls( attributes=attributes, extension=base_type, qname=qname, is_global=is_global, ) elif first_tag == tags.complexContent: kwargs = self.visit_complex_content(children[0], node) xsd_type = xsd_cls(qname=qname, is_global=is_global, **kwargs) elif first_tag: element = None if first_tag in (tags.group, tags.all, tags.choice, tags.sequence): child = children.pop(0) element = self.process(child, node) attributes = self._process_attributes(node, children) xsd_type = xsd_cls( element=element, attributes=attributes, qname=qname, is_global=is_global ) else: xsd_type = xsd_cls(qname=qname, is_global=is_global) if is_global: self.register_type(qname, xsd_type) return xsd_type def visit_complex_content(self, node, parent): """The complexContent element defines extensions or restrictions on a complex type that contains mixed content or elements only. Definition:: <complexContent id = ID mixed = Boolean {any attributes with non-schema Namespace}...> Content: (annotation?, (restriction | extension)) </complexContent> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ children = list(node) child = children[-1] if child.tag == tags.restriction: base, element, attributes = self.visit_restriction_complex_content( child, node ) return {"attributes": attributes, "element": element, "restriction": base} elif child.tag == tags.extension: base, element, attributes = self.visit_extension_complex_content( child, node ) return {"attributes": attributes, "element": element, "extension": base} def visit_simple_content(self, node, parent): """Contains extensions or restrictions on a complexType element with character data or a simpleType element as content and contains no elements. Definition:: <simpleContent id = ID {any attributes with non-schema Namespace}...> Content: (annotation?, (restriction | extension)) </simpleContent> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ children = list(node) child = children[-1] if child.tag == tags.restriction: return self.visit_restriction_simple_content(child, node) elif child.tag == tags.extension: return self.visit_extension_simple_content(child, node) raise AssertionError("Expected restriction or extension") def visit_restriction_simple_type(self, node, parent): """ Definition:: <restriction base = QName id = ID {any attributes with non-schema Namespace}...> Content: (annotation?, (simpleType?, ( minExclusive | minInclusive | maxExclusive | maxInclusive | totalDigits |fractionDigits | length | minLength | maxLength | enumeration | whiteSpace | pattern)*)) </restriction> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ base_name = qname_attr(node, "base") if base_name: return self._get_type(base_name) annotation, children = self._pop_annotation(list(node)) if children[0].tag == tags.simpleType: return self.visit_simple_type(children[0], node) def visit_restriction_simple_content(self, node, parent): """ Definition:: <restriction base = QName id = ID {any attributes with non-schema Namespace}...> Content: (annotation?, (simpleType?, ( minExclusive | minInclusive | maxExclusive | maxInclusive | totalDigits |fractionDigits | length | minLength | maxLength | enumeration | whiteSpace | pattern)* )?, ((attribute | attributeGroup)*, anyAttribute?)) </restriction> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ base_name = qname_attr(node, "base") base_type = self._get_type(base_name) return base_type, [] def visit_restriction_complex_content(self, node, parent): """ Definition:: <restriction base = QName id = ID {any attributes with non-schema Namespace}...> Content: (annotation?, (group | all | choice | sequence)?, ((attribute | attributeGroup)*, anyAttribute?)) </restriction> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ base_name = qname_attr(node, "base") base_type = self._get_type(base_name) annotation, children = self._pop_annotation(list(node)) element = None attributes = [] if children: child = children[0] if child.tag in (tags.group, tags.all, tags.choice, tags.sequence): children.pop(0) element = self.process(child, node) attributes = self._process_attributes(node, children) return base_type, element, attributes def visit_extension_complex_content(self, node, parent): """ Definition:: <extension base = QName id = ID {any attributes with non-schema Namespace}...> Content: (annotation?, ( (group | all | choice | sequence)?, ((attribute | attributeGroup)*, anyAttribute?))) </extension> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ base_name = qname_attr(node, "base") base_type = self._get_type(base_name) annotation, children = self._pop_annotation(list(node)) element = None attributes = [] if children: child = children[0] if child.tag in (tags.group, tags.all, tags.choice, tags.sequence): children.pop(0) element = self.process(child, node) attributes = self._process_attributes(node, children) return base_type, element, attributes def visit_extension_simple_content(self, node, parent): """ Definition:: <extension base = QName id = ID {any attributes with non-schema Namespace}...> Content: (annotation?, ((attribute | attributeGroup)*, anyAttribute?)) </extension> """ base_name = qname_attr(node, "base") base_type = self._get_type(base_name) annotation, children = self._pop_annotation(list(node)) attributes = self._process_attributes(node, children) return base_type, attributes def visit_annotation(self, node, parent): """Defines an annotation. Definition:: <annotation id = ID {any attributes with non-schema Namespace}...> Content: (appinfo | documentation)* </annotation> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ return def visit_any(self, node, parent): """ Definition:: <any id = ID maxOccurs = (nonNegativeInteger | unbounded) : 1 minOccurs = nonNegativeInteger : 1 namespace = "(##any | ##other) | List of (anyURI | (##targetNamespace | ##local))) : ##any processContents = (lax | skip | strict) : strict {any attributes with non-schema Namespace...}> Content: (annotation?) </any> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ min_occurs, max_occurs = _process_occurs_attrs(node) process_contents = node.get("processContents", "strict") return xsd_elements.Any( max_occurs=max_occurs, min_occurs=min_occurs, process_contents=process_contents, ) def visit_sequence(self, node, parent): """ Definition:: <sequence id = ID maxOccurs = (nonNegativeInteger | unbounded) : 1 minOccurs = nonNegativeInteger : 1 {any attributes with non-schema Namespace}...> Content: (annotation?, (element | group | choice | sequence | any)*) </sequence> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ sub_types = [ tags.annotation, tags.any, tags.choice, tags.element, tags.group, tags.sequence, ] min_occurs, max_occurs = _process_occurs_attrs(node) result = xsd_elements.Sequence(min_occurs=min_occurs, max_occurs=max_occurs) annotation, children = self._pop_annotation(list(node)) for child in children: if child.tag not in sub_types: raise self._create_error( "Unexpected element %s in xsd:sequence" % child.tag, child ) item = self.process(child, node) assert item is not None result.append(item) assert None not in result return result def visit_all(self, node, parent): """Allows the elements in the group to appear (or not appear) in any order in the containing element. Definition:: <all id = ID maxOccurs= 1: 1 minOccurs= (0 | 1): 1 {any attributes with non-schema Namespace...}> Content: (annotation?, element*) </all> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ sub_types = [tags.annotation, tags.element] result = xsd_elements.All() annotation, children = self._pop_annotation(list(node)) for child in children: assert child.tag in sub_types, child item = self.process(child, node) result.append(item) assert None not in result return result def visit_group(self, node, parent): """Groups a set of element declarations so that they can be incorporated as a group into complex type definitions. Definition:: <group name= NCName id = ID maxOccurs = (nonNegativeInteger | unbounded) : 1 minOccurs = nonNegativeInteger : 1 name = NCName ref = QName {any attributes with non-schema Namespace}...> Content: (annotation?, (all | choice | sequence)) </group> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ min_occurs, max_occurs = _process_occurs_attrs(node) result = self.process_reference( node, min_occurs=min_occurs, max_occurs=max_occurs ) if result: return result qname = qname_attr(node, "name", self.document._target_namespace) # There should be only max nodes, first node (annotation) is irrelevant annotation, children = self._pop_annotation(list(node)) child = children[0] item = self.process(child, parent) elm = xsd_elements.Group(name=qname, child=item) if parent.tag == tags.schema: self.register_group(qname, elm) return elm def visit_list(self, node, parent): """ Definition:: <list id = ID itemType = QName {any attributes with non-schema Namespace}...> Content: (annotation?, (simpleType?)) </list> The use of the simpleType element child and the itemType attribute is mutually exclusive. :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ item_type = qname_attr(node, "itemType") if item_type: sub_type = self._get_type(item_type.text) else: subnodes = list(node) child = subnodes[-1] # skip annotation sub_type = self.visit_simple_type(child, node) return xsd_types.ListType(sub_type) def visit_choice(self, node, parent): """ Definition:: <choice id = ID maxOccurs= (nonNegativeInteger | unbounded) : 1 minOccurs= nonNegativeInteger : 1 {any attributes with non-schema Namespace}...> Content: (annotation?, (element | group | choice | sequence | any)*) </choice> """ min_occurs, max_occurs = _process_occurs_attrs(node) annotation, children = self._pop_annotation(list(node)) choices = [] for child in children: elm = self.process(child, node) choices.append(elm) return xsd_elements.Choice( choices, min_occurs=min_occurs, max_occurs=max_occurs ) def visit_union(self, node, parent): """Defines a collection of multiple simpleType definitions. Definition:: <union id = ID memberTypes = List of QNames {any attributes with non-schema Namespace}...> Content: (annotation?, (simpleType*)) </union> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ # TODO members = node.get("memberTypes") types = [] if members: for member in members.split(): qname = as_qname(member, node.nsmap) xsd_type = self._get_type(qname) types.append(xsd_type) else: annotation, types = self._pop_annotation(list(node)) types = [self.visit_simple_type(t, node) for t in types] return xsd_types.UnionType(types) def visit_unique(self, node, parent): """Specifies that an attribute or element value (or a combination of attribute or element values) must be unique within the specified scope. The value must be unique or nil. Definition:: <unique id = ID name = NCName {any attributes with non-schema Namespace}...> Content: (annotation?, (selector, field+)) </unique> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ # TODO pass def visit_attribute_group(self, node, parent): """ Definition:: <attributeGroup id = ID name = NCName ref = QName {any attributes with non-schema Namespace...}> Content: (annotation?), ((attribute | attributeGroup)*, anyAttribute?)) </attributeGroup> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ ref = self.process_reference(node) if ref: return ref qname = qname_attr(node, "name", self.document._target_namespace) annotation, children = self._pop_annotation(list(node)) attributes = self._process_attributes(node, children) attribute_group = xsd_elements.AttributeGroup(qname, attributes) self.register_attribute_group(qname, attribute_group) def visit_any_attribute(self, node, parent): """ Definition:: <anyAttribute id = ID namespace = ((##any | ##other) | List of (anyURI | (##targetNamespace | ##local))) : ##any processContents = (lax | skip | strict): strict {any attributes with non-schema Namespace...}> Content: (annotation?) </anyAttribute> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ process_contents = node.get("processContents", "strict") return xsd_elements.AnyAttribute(process_contents=process_contents) def visit_notation(self, node, parent): """Contains the definition of a notation to describe the format of non-XML data within an XML document. An XML Schema notation declaration is a reconstruction of XML 1.0 NOTATION declarations. Definition:: <notation id = ID name = NCName public = Public identifier per ISO 8879 system = anyURI {any attributes with non-schema Namespace}...> Content: (annotation?) </notation> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ pass def _get_type(self, name): assert name is not None name = self._create_qname(name) return UnresolvedType(name, self.schema) def _create_qname(self, name): if not isinstance(name, etree.QName): name = etree.QName(name) # Handle reserved namespace if name.namespace == "xml": name = etree.QName("http://www.w3.org/XML/1998/namespace", name.localname) # Various xsd builders assume that some schema's are available by # default (actually this is mostly just the soap-enc ns). So live with # that fact and handle it by auto-importing the schema if it is # referenced. if name.namespace in AUTO_IMPORT_NAMESPACES and not self.document.is_imported( name.namespace ): logger.debug("Auto importing missing known schema: %s", name.namespace) import_node = etree.Element( tags.import_, namespace=name.namespace, schemaLocation=name.namespace ) self.visit_import(import_node, None) if ( not name.namespace and self.document._element_form == "qualified" and self.document._target_namespace and not self.document._has_empty_import ): name = etree.QName(self.document._target_namespace, name.localname) return name def _pop_annotation(self, items): if not len(items): return None, [] if items[0].tag == tags.annotation: annotation = self.visit_annotation(items[0], None) return annotation, items[1:] return None, items def _process_attributes(self, node, items): attributes = [] for child in items: if child.tag in (tags.attribute, tags.attributeGroup, tags.anyAttribute): attribute = self.process(child, node) attributes.append(attribute) else: raise self._create_error("Unexpected tag `%s`" % (child.tag), node) return attributes def _create_error(self, message, node): return XMLParseError( message, filename=self.document._location, sourceline=node.sourceline ) visitors = { tags.any: visit_any, tags.element: visit_element, tags.choice: visit_choice, tags.simpleType: visit_simple_type, tags.anyAttribute: visit_any_attribute, tags.complexType: visit_complex_type, tags.simpleContent: None, tags.complexContent: None, tags.sequence: visit_sequence, tags.all: visit_all, tags.group: visit_group, tags.attribute: visit_attribute, tags.import_: visit_import, tags.include: visit_include, tags.annotation: visit_annotation, tags.attributeGroup: visit_attribute_group, tags.notation: visit_notation, } def _process_occurs_attrs(node): """Process the min/max occurrence indicators""" max_occurs = node.get("maxOccurs", "1") min_occurs = int(node.get("minOccurs", "1")) if max_occurs == "unbounded": max_occurs = "unbounded" else: max_occurs = int(max_occurs) return min_occurs, max_occurs
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/xsd/visitor.py
visitor.py
import copy from collections import OrderedDict from zeep.xsd.printer import PrettyPrinter __all__ = ["AnyObject", "CompoundValue"] class AnyObject(object): """Create an any object :param xsd_object: the xsd type :param value: The value """ def __init__(self, xsd_object, value): self.xsd_obj = xsd_object self.value = value def __repr__(self): return "<%s(type=%r, value=%r)>" % ( self.__class__.__name__, self.xsd_elm, self.value, ) def __deepcopy__(self, memo): return type(self)(self.xsd_elm, copy.deepcopy(self.value)) @property def xsd_type(self): return self.xsd_obj @property def xsd_elm(self): return self.xsd_obj def _unpickle_compound_value(name, values): """Helper function to recreate pickled CompoundValue. See CompoundValue.__reduce__ """ cls = type( name, (CompoundValue,), {"_xsd_type": None, "__module__": "zeep.objects"} ) obj = cls() obj.__values__ = values return obj class ArrayValue(list): def __init__(self, items): super(ArrayValue, self).__init__(items) def as_value_object(self): anon_type = type( self.__class__.__name__, (CompoundValue,), {"_xsd_type": self._xsd_type, "__module__": "zeep.objects"}, ) return anon_type(list(self)) @classmethod def from_value_object(cls, obj): items = next(iter(obj.__values__.values())) return cls(items or []) class CompoundValue(object): """Represents a data object for a specific xsd:complexType.""" def __init__(self, *args, **kwargs): values = OrderedDict() # Can be done after unpickle if self._xsd_type is None: return # Set default values for container_name, container in self._xsd_type.elements_nested: elm_values = container.default_value if isinstance(elm_values, dict): values.update(elm_values) else: values[container_name] = elm_values # Set attributes for attribute_name, attribute in self._xsd_type.attributes: values[attribute_name] = attribute.default_value # Set elements items = _process_signature(self._xsd_type, args, kwargs) for key, value in items.items(): values[key] = value self.__values__ = values def __reduce__(self): return (_unpickle_compound_value, (self.__class__.__name__, self.__values__)) def __contains__(self, key): return self.__values__.__contains__(key) def __eq__(self, other): if self.__class__ != other.__class__: return False other_values = {key: other[key] for key in other} return other_values == self.__values__ def __len__(self): return self.__values__.__len__() def __iter__(self): return self.__values__.__iter__() def __dir__(self): return list(self.__values__.keys()) def __repr__(self): return PrettyPrinter().pformat(self.__values__) def __delitem__(self, key): return self.__values__.__delitem__(key) def __getitem__(self, key): return self.__values__[key] def __setitem__(self, key, value): self.__values__[key] = value def __setattr__(self, key, value): if key.startswith("__") or key in ("_xsd_type", "_xsd_elm"): return super(CompoundValue, self).__setattr__(key, value) self.__values__[key] = value def __getattribute__(self, key): if key.startswith("__") or key in ("_xsd_type", "_xsd_elm"): return super(CompoundValue, self).__getattribute__(key) try: return self.__values__[key] except KeyError: raise AttributeError( "%s instance has no attribute '%s'" % (self.__class__.__name__, key) ) def __deepcopy__(self, memo): new = type(self)() new.__values__ = copy.deepcopy(self.__values__) for attr, value in self.__dict__.items(): if attr != "__values__": setattr(new, attr, value) return new def __json__(self): return self.__values__ def _process_signature(xsd_type, args, kwargs): """Return a dict with the args/kwargs mapped to the field name. Special handling is done for Choice elements since we need to record which element the user intends to use. :param fields: List of tuples (name, element) :type fields: list :param args: arg tuples :type args: tuple :param kwargs: kwargs :type kwargs: dict """ result = OrderedDict() # Process the positional arguments. args is currently still modified # in-place here if args: args = list(args) num_args = len(args) index = 0 for element_name, element in xsd_type.elements_nested: values, args, index = element.parse_args(args, index) if not values: break result.update(values) for attribute_name, attribute in xsd_type.attributes: if num_args <= index: break result[attribute_name] = args[index] index += 1 if num_args > index: raise TypeError( "__init__() takes at most %s positional arguments (%s given)" % (len(result), num_args) ) # Process the named arguments (sequence/group/all/choice). The # available_kwargs set is modified in-place. available_kwargs = set(kwargs.keys()) for element_name, element in xsd_type.elements_nested: if element.accepts_multiple: values = element.parse_kwargs(kwargs, element_name, available_kwargs) else: values = element.parse_kwargs(kwargs, None, available_kwargs) if values is not None: for key, value in values.items(): if key not in result: result[key] = value # Process the named arguments for attributes if available_kwargs: for attribute_name, attribute in xsd_type.attributes: if attribute_name in available_kwargs: available_kwargs.remove(attribute_name) result[attribute_name] = kwargs[attribute_name] # _raw_elements is a special kwarg used for unexpected unparseable xml # elements (e.g. for soap:header or when strict is disabled) if "_raw_elements" in available_kwargs and kwargs["_raw_elements"]: result["_raw_elements"] = kwargs["_raw_elements"] available_kwargs.remove("_raw_elements") if available_kwargs: raise TypeError( ("%s() got an unexpected keyword argument %r. " + "Signature: `%s`") % ( xsd_type.qname or "ComplexType", next(iter(available_kwargs)), xsd_type.signature(standalone=False), ) ) return result
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/xsd/valueobjects.py
valueobjects.py
import copy import operator from collections import OrderedDict, defaultdict, deque from cached_property import threaded_cached_property from zeep.exceptions import UnexpectedElementError, ValidationError from zeep.xsd.const import NotSet, SkipValue from zeep.xsd.elements import Any, Element from zeep.xsd.elements.base import Base from zeep.xsd.utils import ( NamePrefixGenerator, UniqueNameGenerator, create_prefixed_name, max_occurs_iter) __all__ = ["All", "Choice", "Group", "Sequence"] class Indicator(Base): """Base class for the other indicators""" def __repr__(self): return "<%s(%s)>" % (self.__class__.__name__, super(Indicator, self).__repr__()) @property def default_value(self): values = OrderedDict( [(name, element.default_value) for name, element in self.elements] ) if self.accepts_multiple: return {"_value_1": values} return values def clone(self, name, min_occurs=1, max_occurs=1): raise NotImplementedError() class OrderIndicator(Indicator, list): """Base class for All, Choice and Sequence classes.""" name = None def __init__(self, elements=None, min_occurs=1, max_occurs=1): self.min_occurs = min_occurs self.max_occurs = max_occurs super(OrderIndicator, self).__init__() if elements is not None: self.extend(elements) def clone(self, name, min_occurs=1, max_occurs=1): return self.__class__( elements=list(self), min_occurs=min_occurs, max_occurs=max_occurs ) @threaded_cached_property def elements(self): """List of tuples containing the element name and the element""" result = [] for name, elm in self.elements_nested: if name is None: result.extend(elm.elements) else: result.append((name, elm)) return result @threaded_cached_property def elements_nested(self): """List of tuples containing the element name and the element""" result = [] generator = NamePrefixGenerator() generator_2 = UniqueNameGenerator() for elm in self: if isinstance(elm, (All, Choice, Group, Sequence)): if elm.accepts_multiple: result.append((generator.get_name(), elm)) else: for sub_name, sub_elm in elm.elements: sub_name = generator_2.create_name(sub_name) result.append((None, elm)) elif isinstance(elm, (Any, Choice)): result.append((generator.get_name(), elm)) else: name = generator_2.create_name(elm.attr_name) result.append((name, elm)) return result def accept(self, values): """Return the number of values which are accepted by this choice. If not all required elements are available then 0 is returned. """ if not self.accepts_multiple: values = [values] results = set() for value in values: num = 0 for name, element in self.elements_nested: if isinstance(element, Element): if element.name in value and value[element.name] is not None: num += 1 else: num += element.accept(value) results.add(num) return max(results) def parse_args(self, args, index=0): # If the sequence contains an choice element then we can't convert # the args to kwargs since Choice elements don't work with position # arguments for name, elm in self.elements_nested: if isinstance(elm, Choice): raise TypeError("Choice elements only work with keyword arguments") result = {} for name, element in self.elements: if index >= len(args): break result[name] = args[index] index += 1 return result, args, index def parse_kwargs(self, kwargs, name, available_kwargs): """Apply the given kwarg to the element. The available_kwargs is modified in-place. Returns a dict with the result. :param kwargs: The kwargs :type kwargs: dict :param name: The name as which this type is registered in the parent :type name: str :param available_kwargs: The kwargs keys which are still available, modified in place :type available_kwargs: set :rtype: dict """ if self.accepts_multiple: assert name if name: if name not in available_kwargs: return {} assert self.accepts_multiple # Make sure we have a list, lame lame item_kwargs = kwargs.get(name) if not isinstance(item_kwargs, list): item_kwargs = [item_kwargs] result = [] for item_value in max_occurs_iter(self.max_occurs, item_kwargs): try: item_kwargs = set(item_value.keys()) except AttributeError: raise TypeError( "A list of dicts is expected for unbounded Sequences" ) subresult = OrderedDict() for item_name, element in self.elements: value = element.parse_kwargs(item_value, item_name, item_kwargs) if value is not None: subresult.update(value) if item_kwargs: raise TypeError( ("%s() got an unexpected keyword argument %r.") % (self, list(item_kwargs)[0]) ) result.append(subresult) result = {name: result} # All items consumed if not any(filter(None, item_kwargs)): available_kwargs.remove(name) return result else: assert not self.accepts_multiple result = OrderedDict() for elm_name, element in self.elements_nested: sub_result = element.parse_kwargs(kwargs, elm_name, available_kwargs) if sub_result: result.update(sub_result) return result def resolve(self): for i, elm in enumerate(self): self[i] = elm.resolve() return self def render(self, parent, value, render_path): """Create subelements in the given parent object.""" if not isinstance(value, list): values = [value] else: values = value self.validate(values, render_path) for value in max_occurs_iter(self.max_occurs, values): for name, element in self.elements_nested: if name: if name in value: element_value = value[name] child_path = render_path + [name] else: element_value = NotSet child_path = render_path else: element_value = value child_path = render_path if element_value is SkipValue: continue if element_value is not None or not element.is_optional: element.render(parent, element_value, child_path) def validate(self, value, render_path): for item in value: if item is NotSet: raise ValidationError("No value set", path=render_path) def signature(self, schema=None, standalone=True): parts = [] for name, element in self.elements_nested: if isinstance(element, Indicator): parts.append(element.signature(schema, standalone=False)) else: value = element.signature(schema, standalone=False) parts.append("%s: %s" % (name, value)) part = ", ".join(parts) if self.accepts_multiple: return "[%s]" % (part,) return part class All(OrderIndicator): """Allows the elements in the group to appear (or not appear) in any order in the containing element. """ def __init__(self, elements=None, min_occurs=1, max_occurs=1, consume_other=False): super(All, self).__init__(elements, min_occurs, max_occurs) self._consume_other = consume_other def parse_xmlelements(self, xmlelements, schema, name=None, context=None): """Consume matching xmlelements :param xmlelements: Dequeue of XML element objects :type xmlelements: collections.deque of lxml.etree._Element :param schema: The parent XML schema :type schema: zeep.xsd.Schema :param name: The name of the parent element :type name: str :param context: Optional parsing context (for inline schemas) :type context: zeep.xsd.context.XmlParserContext :rtype: dict or None """ result = OrderedDict() expected_tags = {element.qname for __, element in self.elements} consumed_tags = set() values = defaultdict(deque) for i, elm in enumerate(xmlelements): if elm.tag in expected_tags: consumed_tags.add(i) values[elm.tag].append(elm) # Remove the consumed tags from the xmlelements for i in sorted(consumed_tags, reverse=True): del xmlelements[i] for name, element in self.elements: sub_elements = values.get(element.qname) if sub_elements: result[name] = element.parse_xmlelements( sub_elements, schema, context=context ) if self._consume_other and xmlelements: result["_raw_elements"] = list(xmlelements) xmlelements.clear() return result class Choice(OrderIndicator): """Permits one and only one of the elements contained in the group.""" def parse_args(self, args, index=0): if args: raise TypeError("Choice elements only work with keyword arguments") @property def is_optional(self): return True @property def default_value(self): return OrderedDict() def parse_xmlelements(self, xmlelements, schema, name=None, context=None): """Consume matching xmlelements :param xmlelements: Dequeue of XML element objects :type xmlelements: collections.deque of lxml.etree._Element :param schema: The parent XML schema :type schema: zeep.xsd.Schema :param name: The name of the parent element :type name: str :param context: Optional parsing context (for inline schemas) :type context: zeep.xsd.context.XmlParserContext :rtype: dict or None """ result = [] for _unused in max_occurs_iter(self.max_occurs): if not xmlelements: break # Choose out of multiple options = [] for element_name, element in self.elements_nested: local_xmlelements = copy.copy(xmlelements) try: sub_result = element.parse_xmlelements( xmlelements=local_xmlelements, schema=schema, name=element_name, context=context, ) except UnexpectedElementError: continue if isinstance(element, Element): sub_result = {element_name: sub_result} num_consumed = len(xmlelements) - len(local_xmlelements) if num_consumed: options.append((num_consumed, sub_result)) if not options: xmlelements = [] break # Sort on least left options = sorted(options, key=operator.itemgetter(0), reverse=True) if options: result.append(options[0][1]) for i in range(options[0][0]): xmlelements.popleft() else: break if self.accepts_multiple: result = {name: result} else: result = result[0] if result else {} return result def parse_kwargs(self, kwargs, name, available_kwargs): """Processes the kwargs for this choice element. Returns a dict containing the values found. This handles two distinct initialization methods: 1. Passing the choice elements directly to the kwargs (unnested) 2. Passing the choice elements into the `name` kwarg (_value_1) (nested). This case is required when multiple choice elements are given. :param name: Name of the choice element (_value_1) :type name: str :param element: Choice element object :type element: zeep.xsd.Choice :param kwargs: dict (or list of dicts) of kwargs for initialization :type kwargs: list / dict """ if name and name in available_kwargs: assert self.accepts_multiple values = kwargs[name] or [] available_kwargs.remove(name) result = [] if isinstance(values, dict): values = [values] # TODO: Use most greedy choice instead of first matching for value in values: for element in self: if isinstance(element, OrderIndicator): choice_value = value[name] if name in value else value if element.accept(choice_value): result.append(choice_value) break else: if isinstance(element, Any): result.append(value) break elif element.name in value: choice_value = value.get(element.name) result.append({element.name: choice_value}) break else: raise TypeError( "No complete xsd:Sequence found for the xsd:Choice %r.\n" "The signature is: %s" % (name, self.signature()) ) if not self.accepts_multiple: result = result[0] if result else None else: # Direct use-case isn't supported when maxOccurs > 1 if self.accepts_multiple: return {} result = {} # When choice elements are specified directly in the kwargs found = False for name, choice in self.elements_nested: temp_kwargs = copy.copy(available_kwargs) subresult = choice.parse_kwargs(kwargs, name, temp_kwargs) if subresult: if not any(subresult.values()): available_kwargs.intersection_update(temp_kwargs) result.update(subresult) elif not found: available_kwargs.intersection_update(temp_kwargs) result.update(subresult) found = True if found: for choice_name, choice in self.elements: result.setdefault(choice_name, None) else: result = {} if name and self.accepts_multiple: result = {name: result} return result def render(self, parent, value, render_path): """Render the value to the parent element tree node. This is a bit more complex then the order render methods since we need to search for the best matching choice element. """ if not self.accepts_multiple: value = [value] self.validate(value, render_path) for item in value: result = self._find_element_to_render(item) if result: element, choice_value = result element.render(parent, choice_value, render_path) def validate(self, value, render_path): found = 0 for item in value: result = self._find_element_to_render(item) if result: found += 1 if not found and not self.is_optional: raise ValidationError("Missing choice values", path=render_path) def accept(self, values): """Return the number of values which are accepted by this choice. If not all required elements are available then 0 is returned. """ nums = set() for name, element in self.elements_nested: if isinstance(element, Element): if self.accepts_multiple: if all(name in item and item[name] for item in values): nums.add(1) else: if name in values and values[name]: nums.add(1) else: num = element.accept(values) nums.add(num) return max(nums) if nums else 0 def _find_element_to_render(self, value): """Return a tuple (element, value) for the best matching choice. This is used to decide which choice child is best suitable for rendering the available data. """ matches = [] for name, element in self.elements_nested: if isinstance(element, Element): if element.name in value: try: choice_value = value[element.name] except KeyError: choice_value = value if choice_value is not None: matches.append((1, element, choice_value)) else: if name is not None: try: choice_value = value[name] except (KeyError, TypeError): choice_value = value else: choice_value = value score = element.accept(choice_value) if score: matches.append((score, element, choice_value)) if matches: matches = sorted(matches, key=operator.itemgetter(0), reverse=True) return matches[0][1:] def signature(self, schema=None, standalone=True): parts = [] for name, element in self.elements_nested: if isinstance(element, OrderIndicator): parts.append("{%s}" % (element.signature(schema, standalone=False))) else: parts.append( "{%s: %s}" % (name, element.signature(schema, standalone=False)) ) part = "(%s)" % " | ".join(parts) if self.accepts_multiple: return "%s[]" % (part,) return part class Sequence(OrderIndicator): """Requires the elements in the group to appear in the specified sequence within the containing element. """ def parse_xmlelements(self, xmlelements, schema, name=None, context=None): """Consume matching xmlelements :param xmlelements: Dequeue of XML element objects :type xmlelements: collections.deque of lxml.etree._Element :param schema: The parent XML schema :type schema: zeep.xsd.Schema :param name: The name of the parent element :type name: str :param context: Optional parsing context (for inline schemas) :type context: zeep.xsd.context.XmlParserContext :rtype: dict or None """ result = [] if self.accepts_multiple: assert name for _unused in max_occurs_iter(self.max_occurs): if not xmlelements: break item_result = OrderedDict() for elm_name, element in self.elements: try: item_subresult = element.parse_xmlelements( xmlelements, schema, name, context=context ) except UnexpectedElementError: if schema.settings.strict: raise item_subresult = None # Unwrap if allowed if isinstance(element, OrderIndicator): item_result.update(item_subresult) else: item_result[elm_name] = item_subresult if not xmlelements: break if item_result: result.append(item_result) if not self.accepts_multiple: return result[0] if result else None return {name: result} class Group(Indicator): """Groups a set of element declarations so that they can be incorporated as a group into complex type definitions. """ def __init__(self, name, child, max_occurs=1, min_occurs=1): super(Group, self).__init__() self.child = child self.qname = name self.name = name.localname if name else None self.max_occurs = max_occurs self.min_occurs = min_occurs def __str__(self): return self.signature() def __iter__(self, *args, **kwargs): for item in self.child: yield item @threaded_cached_property def elements(self): if self.accepts_multiple: return [("_value_1", self.child)] return self.child.elements def clone(self, name, min_occurs=1, max_occurs=1): return self.__class__( name=None, child=self.child, min_occurs=min_occurs, max_occurs=max_occurs ) def accept(self, values): """Return the number of values which are accepted by this choice. If not all required elements are available then 0 is returned. """ return self.child.accept(values) def parse_args(self, args, index=0): return self.child.parse_args(args, index) def parse_kwargs(self, kwargs, name, available_kwargs): if self.accepts_multiple: if name not in kwargs: return {} available_kwargs.remove(name) item_kwargs = kwargs[name] result = [] sub_name = "_value_1" if self.child.accepts_multiple else None for sub_kwargs in max_occurs_iter(self.max_occurs, item_kwargs): available_sub_kwargs = set(sub_kwargs.keys()) subresult = self.child.parse_kwargs( sub_kwargs, sub_name, available_sub_kwargs ) if available_sub_kwargs: raise TypeError( ("%s() got an unexpected keyword argument %r.") % (self, list(available_sub_kwargs)[0]) ) if subresult: result.append(subresult) if result: result = {name: result} else: result = self.child.parse_kwargs(kwargs, name, available_kwargs) return result def parse_xmlelements(self, xmlelements, schema, name=None, context=None): """Consume matching xmlelements :param xmlelements: Dequeue of XML element objects :type xmlelements: collections.deque of lxml.etree._Element :param schema: The parent XML schema :type schema: zeep.xsd.Schema :param name: The name of the parent element :type name: str :param context: Optional parsing context (for inline schemas) :type context: zeep.xsd.context.XmlParserContext :rtype: dict or None """ result = [] for _unused in max_occurs_iter(self.max_occurs): result.append( self.child.parse_xmlelements(xmlelements, schema, name, context=context) ) if not xmlelements: break if not self.accepts_multiple and result: return result[0] return {name: result} def render(self, parent, value, render_path): if not isinstance(value, list): values = [value] else: values = value for value in values: self.child.render(parent, value, render_path) def resolve(self): self.child = self.child.resolve() return self def signature(self, schema=None, standalone=True): name = create_prefixed_name(self.qname, schema) if standalone: return "%s(%s)" % (name, self.child.signature(schema, standalone=False)) else: return self.child.signature(schema, standalone=False)
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/xsd/elements/indicators.py
indicators.py
import logging from lxml import etree from zeep import exceptions, ns from zeep.utils import qname_attr from zeep.xsd.const import NotSet, xsi_ns from zeep.xsd.elements.base import Base from zeep.xsd.utils import max_occurs_iter from zeep.xsd.valueobjects import AnyObject logger = logging.getLogger(__name__) __all__ = ["Any", "AnyAttribute"] class Any(Base): name = None def __init__( self, max_occurs=1, min_occurs=1, process_contents="strict", restrict=None ): """ :param process_contents: Specifies how the XML processor should handle validation against the elements specified by this any element :type process_contents: str (strict, lax, skip) """ super(Any, self).__init__() self.max_occurs = max_occurs self.min_occurs = min_occurs self.restrict = restrict self.process_contents = process_contents # cyclic import from zeep.xsd import AnyType self.type = AnyType() def __call__(self, any_object): return any_object def __repr__(self): return "<%s(name=%r)>" % (self.__class__.__name__, self.name) def accept(self, value): return True def parse(self, xmlelement, schema, context=None): if self.process_contents == "skip": return xmlelement # If a schema was passed inline then check for a matching one qname = etree.QName(xmlelement.tag) if context and context.schemas: for context_schema in context.schemas: if context_schema.documents.has_schema_document_for_ns(qname.namespace): schema = context_schema break else: # Try to parse the any result by iterating all the schemas for context_schema in context.schemas: try: data = context_schema.deserialize(list(xmlelement)[0]) return data except LookupError: continue # Lookup type via xsi:type attribute xsd_type = qname_attr(xmlelement, xsi_ns("type")) if xsd_type is not None: xsd_type = schema.get_type(xsd_type) return xsd_type.parse_xmlelement(xmlelement, schema, context=context) # Check if a restrict is used if self.restrict: return self.restrict.parse_xmlelement(xmlelement, schema, context=context) try: element = schema.get_element(xmlelement.tag) return element.parse(xmlelement, schema, context=context) except (exceptions.NamespaceError, exceptions.LookupError): return xmlelement def parse_kwargs(self, kwargs, name, available_kwargs): if name in available_kwargs: available_kwargs.remove(name) value = kwargs[name] return {name: value} return {} def parse_xmlelements(self, xmlelements, schema, name=None, context=None): """Consume matching xmlelements and call parse() on each of them :param xmlelements: Dequeue of XML element objects :type xmlelements: collections.deque of lxml.etree._Element :param schema: The parent XML schema :type schema: zeep.xsd.Schema :param name: The name of the parent element :type name: str :param context: Optional parsing context (for inline schemas) :type context: zeep.xsd.context.XmlParserContext :return: dict or None """ result = [] for _unused in max_occurs_iter(self.max_occurs): if xmlelements: xmlelement = xmlelements.popleft() item = self.parse(xmlelement, schema, context=context) if item is not None: result.append(item) else: break if not self.accepts_multiple: result = result[0] if result else None return result def render(self, parent, value, render_path=None): assert parent is not None self.validate(value, render_path) if self.accepts_multiple and isinstance(value, list): from zeep.xsd import AnySimpleType if isinstance(self.restrict, AnySimpleType): for val in value: node = etree.SubElement(parent, "item") node.set(xsi_ns("type"), self.restrict.qname) self._render_value_item(node, val, render_path) elif self.restrict: for val in value: node = etree.SubElement(parent, self.restrict.name) # node.set(xsi_ns('type'), self.restrict.qname) self._render_value_item(node, val, render_path) else: for val in value: self._render_value_item(parent, val, render_path) else: self._render_value_item(parent, value, render_path) def _render_value_item(self, parent, value, render_path): if value in (None, NotSet): # can be an lxml element return elif isinstance(value, etree._Element): parent.append(value) elif self.restrict: if isinstance(value, list): for val in value: self.restrict.render(parent, val, None, render_path) else: self.restrict.render(parent, value, None, render_path) else: if isinstance(value.value, list): for val in value.value: value.xsd_elm.render(parent, val, render_path) else: value.xsd_elm.render(parent, value.value, render_path) def validate(self, value, render_path): if self.accepts_multiple and isinstance(value, list): # Validate bounds if len(value) < self.min_occurs: raise exceptions.ValidationError( "Expected at least %d items (minOccurs check)" % self.min_occurs ) if self.max_occurs != "unbounded" and len(value) > self.max_occurs: raise exceptions.ValidationError( "Expected at most %d items (maxOccurs check)" % self.min_occurs ) for val in value: self._validate_item(val, render_path) else: if not self.is_optional and value in (None, NotSet): raise exceptions.ValidationError("Missing element for Any") self._validate_item(value, render_path) def _validate_item(self, value, render_path): if value is None: # can be an lxml element return # Check if we received a proper value object. If we receive the wrong # type then return a nice error message if self.restrict: expected_types = (etree._Element, dict) + self.restrict.accepted_types else: expected_types = (etree._Element, dict, AnyObject) if value in (None, NotSet): if not self.is_optional: raise exceptions.ValidationError( "Missing element %s" % (self.name), path=render_path ) elif not isinstance(value, expected_types): type_names = ["%s.%s" % (t.__module__, t.__name__) for t in expected_types] err_message = "Any element received object of type %r, expected %s" % ( type(value).__name__, " or ".join(type_names), ) raise TypeError( "\n".join( ( err_message, "See http://docs.python-zeep.org/en/master/datastructures.html" "#any-objects for more information", ) ) ) def resolve(self): return self def signature(self, schema=None, standalone=True): if self.restrict: base = self.restrict.name else: base = "ANY" if self.accepts_multiple: return "%s[]" % base return base class AnyAttribute(Base): name = None _ignore_attributes = [etree.QName(ns.XSI, "type")] def __init__(self, process_contents="strict"): self.qname = None self.process_contents = process_contents def parse(self, attributes, context=None): result = {} for key, value in attributes.items(): if key not in self._ignore_attributes: result[key] = value return result def resolve(self): return self def render(self, parent, value, render_path=None): if value in (None, NotSet): return for name, val in value.items(): parent.set(name, val) def signature(self, schema=None, standalone=True): return "{}"
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/xsd/elements/any.py
any.py
import copy import logging from lxml import etree from zeep import exceptions from zeep.exceptions import UnexpectedElementError from zeep.utils import qname_attr from zeep.xsd.const import Nil, NotSet, xsi_ns from zeep.xsd.context import XmlParserContext from zeep.xsd.elements.base import Base from zeep.xsd.utils import create_prefixed_name, max_occurs_iter logger = logging.getLogger(__name__) __all__ = ["Element"] class Element(Base): def __init__( self, name, type_=None, min_occurs=1, max_occurs=1, nillable=False, default=None, is_global=False, attr_name=None, ): if name is None: raise ValueError("name cannot be None", self.__class__) if not isinstance(name, etree.QName): name = etree.QName(name) self.name = name.localname if name else None self.qname = name self.type = type_ self.min_occurs = min_occurs self.max_occurs = max_occurs self.nillable = nillable self.is_global = is_global self.default = default self.attr_name = attr_name or self.name # assert type_ def __str__(self): if self.type: if self.type.is_global: return "%s(%s)" % (self.name, self.type.qname) else: return "%s(%s)" % (self.name, self.type.signature()) return "%s()" % self.name def __call__(self, *args, **kwargs): instance = self.type(*args, **kwargs) if hasattr(instance, "_xsd_type"): instance._xsd_elm = self return instance def __repr__(self): return "<%s(name=%r, type=%r)>" % ( self.__class__.__name__, self.name, self.type, ) def __eq__(self, other): return ( other is not None and self.__class__ == other.__class__ and self.__dict__ == other.__dict__ ) def get_prefixed_name(self, schema): return create_prefixed_name(self.qname, schema) @property def default_value(self): if self.accepts_multiple: return [] if self.is_optional: return None return self.default def clone(self, name=None, min_occurs=1, max_occurs=1): new = copy.copy(self) if name: if not isinstance(name, etree.QName): name = etree.QName(name) new.name = name.localname new.qname = name new.attr_name = new.name new.min_occurs = min_occurs new.max_occurs = max_occurs return new def parse(self, xmlelement, schema, allow_none=False, context=None): """Process the given xmlelement. If it has an xsi:type attribute then use that for further processing. This should only be done for subtypes of the defined type but for now we just accept everything. This is the entrypoint for parsing an xml document. :param xmlelement: The XML element to parse :type xmlelements: lxml.etree._Element :param schema: The parent XML schema :type schema: zeep.xsd.Schema :param allow_none: Allow none :type allow_none: bool :param context: Optional parsing context (for inline schemas) :type context: zeep.xsd.context.XmlParserContext :return: dict or None """ context = context or XmlParserContext() instance_type = qname_attr(xmlelement, xsi_ns("type")) xsd_type = None if instance_type: xsd_type = schema.get_type(instance_type, fail_silently=True) xsd_type = xsd_type or self.type return xsd_type.parse_xmlelement( xmlelement, schema, allow_none=allow_none, context=context, schema_type=self.type, ) def parse_kwargs(self, kwargs, name, available_kwargs): return self.type.parse_kwargs(kwargs, name or self.attr_name, available_kwargs) def parse_xmlelements(self, xmlelements, schema, name=None, context=None): """Consume matching xmlelements and call parse() on each of them :param xmlelements: Dequeue of XML element objects :type xmlelements: collections.deque of lxml.etree._Element :param schema: The parent XML schema :type schema: zeep.xsd.Schema :param name: The name of the parent element :type name: str :param context: Optional parsing context (for inline schemas) :type context: zeep.xsd.context.XmlParserContext :return: dict or None """ result = [] num_matches = 0 for _unused in max_occurs_iter(self.max_occurs): if not xmlelements: break # Workaround for SOAP servers which incorrectly use unqualified # or qualified elements in the responses (#170, #176). To make the # best of it we compare the full uri's if both elements have a # namespace. If only one has a namespace then only compare the # localname. # If both elements have a namespace and they don't match then skip element_tag = etree.QName(xmlelements[0].tag) if ( element_tag.namespace and self.qname.namespace and element_tag.namespace != self.qname.namespace and schema.settings.strict ): break # Only compare the localname if element_tag.localname == self.qname.localname: xmlelement = xmlelements.popleft() num_matches += 1 item = self.parse(xmlelement, schema, allow_none=True, context=context) result.append(item) elif ( schema is not None and schema.settings.xsd_ignore_sequence_order and list( filter( lambda elem: etree.QName(elem.tag).localname == self.qname.localname, xmlelements, ) ) ): # Search for the field in remaining elements, not only the leftmost xmlelement = list( filter( lambda elem: etree.QName(elem.tag).localname == self.qname.localname, xmlelements, ) )[0] xmlelements.remove(xmlelement) num_matches += 1 item = self.parse(xmlelement, schema, allow_none=True, context=context) result.append(item) else: # If the element passed doesn't match and the current one is # not optional then throw an error if num_matches == 0 and not self.is_optional: raise UnexpectedElementError( "Unexpected element %r, expected %r" % (element_tag.text, self.qname.text) ) break if not self.accepts_multiple: result = result[0] if result else None return result def render(self, parent, value, render_path=None): """Render the value(s) on the parent lxml.Element. This actually just calls _render_value_item for each value. """ if not render_path: render_path = [self.qname.localname] assert parent is not None self.validate(value, render_path) if self.accepts_multiple and isinstance(value, list): for val in value: self._render_value_item(parent, val, render_path) else: self._render_value_item(parent, value, render_path) def _render_value_item(self, parent, value, render_path): """Render the value on the parent lxml.Element""" if value is Nil: elm = etree.SubElement(parent, self.qname) elm.set(xsi_ns("nil"), "true") return if value is None or value is NotSet: if self.is_optional: return elm = etree.SubElement(parent, self.qname) if self.nillable: elm.set(xsi_ns("nil"), "true") return node = etree.SubElement(parent, self.qname) xsd_type = getattr(value, "_xsd_type", self.type) if xsd_type != self.type: return value._xsd_type.render(node, value, xsd_type, render_path) return self.type.render(node, value, None, render_path) def validate(self, value, render_path=None): """Validate that the value is valid""" if self.accepts_multiple and isinstance(value, list): # Validate bounds if len(value) < self.min_occurs: raise exceptions.ValidationError( "Expected at least %d items (minOccurs check) %d items found." % (self.min_occurs, len(value)), path=render_path, ) elif self.max_occurs != "unbounded" and len(value) > self.max_occurs: raise exceptions.ValidationError( "Expected at most %d items (maxOccurs check) %d items found." % (self.max_occurs, len(value)), path=render_path, ) for val in value: self._validate_item(val, render_path) else: if not self.is_optional and not self.nillable and value in (None, NotSet): raise exceptions.ValidationError( "Missing element %s" % (self.name), path=render_path ) self._validate_item(value, render_path) def _validate_item(self, value, render_path): if self.nillable and value in (None, NotSet): return try: self.type.validate(value, required=True) except exceptions.ValidationError as exc: raise exceptions.ValidationError( "The element %s is not valid: %s" % (self.qname, exc.message), path=render_path, ) def resolve_type(self): self.type = self.type.resolve() def resolve(self): self.resolve_type() return self def signature(self, schema=None, standalone=True): from zeep.xsd import ComplexType if self.type.is_global or (not standalone and self.is_global): value = self.type.get_prefixed_name(schema) else: value = self.type.signature(schema, standalone=False) if not standalone and isinstance(self.type, ComplexType): value = "{%s}" % value if standalone: value = "%s(%s)" % (self.get_prefixed_name(schema), value) if self.accepts_multiple: return "%s[]" % value return value
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/xsd/elements/element.py
element.py
import logging from lxml import etree from zeep import exceptions from zeep.xsd.const import NotSet from zeep.xsd.elements.element import Element logger = logging.getLogger(__name__) __all__ = ["Attribute", "AttributeGroup"] class Attribute(Element): def __init__(self, name, type_=None, required=False, default=None): super(Attribute, self).__init__(name=name, type_=type_, default=default) self.required = required self.array_type = None def parse(self, value): try: return self.type.pythonvalue(value) except (TypeError, ValueError): logger.exception("Error during xml -> python translation") return None def render(self, parent, value, render_path=None): if value in (None, NotSet) and not self.required: return self.validate(value, render_path) value = self.type.xmlvalue(value) parent.set(self.qname, value) def validate(self, value, render_path): try: self.type.validate(value, required=self.required) except exceptions.ValidationError as exc: raise exceptions.ValidationError( "The attribute %s is not valid: %s" % (self.qname, exc.message), path=render_path, ) def clone(self, *args, **kwargs): array_type = kwargs.pop("array_type", None) new = super(Attribute, self).clone(*args, **kwargs) new.array_type = array_type return new def resolve(self): retval = super(Attribute, self).resolve() self.type = self.type.resolve() if self.array_type: retval.array_type = self.array_type.resolve() return retval class AttributeGroup(object): def __init__(self, name, attributes): if not isinstance(name, etree.QName): name = etree.QName(name) self.name = name.localname self.qname = name self.type = None self._attributes = attributes self.is_global = True @property def attributes(self): result = [] for attr in self._attributes: if isinstance(attr, AttributeGroup): result.extend(attr.attributes) else: result.append(attr) return result def resolve(self): resolved = [] for attribute in self._attributes: value = attribute.resolve() assert value is not None if isinstance(value, list): resolved.extend(value) else: resolved.append(value) self._attributes = resolved return self def signature(self, schema=None, standalone=True): return ", ".join(attr.signature(schema) for attr in self._attributes)
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/xsd/elements/attribute.py
attribute.py
import logging import six from lxml import etree from zeep.exceptions import ValidationError from zeep.xsd.const import Nil, xsd_ns, xsi_ns from zeep.xsd.types.any import AnyType logger = logging.getLogger(__name__) __all__ = ["AnySimpleType"] @six.python_2_unicode_compatible class AnySimpleType(AnyType): _default_qname = xsd_ns("anySimpleType") def __init__(self, qname=None, is_global=False): super(AnySimpleType, self).__init__( qname or etree.QName(self._default_qname), is_global ) def __call__(self, *args, **kwargs): """Return the xmlvalue for the given value. Expects only one argument 'value'. The args, kwargs handling is done here manually so that we can return readable error messages instead of only '__call__ takes x arguments' """ num_args = len(args) + len(kwargs) if num_args != 1: raise TypeError( ( "%s() takes exactly 1 argument (%d given). " + "Simple types expect only a single value argument" ) % (self.__class__.__name__, num_args) ) if kwargs and "value" not in kwargs: raise TypeError( ( "%s() got an unexpected keyword argument %r. " + "Simple types expect only a single value argument" ) % (self.__class__.__name__, next(six.iterkeys(kwargs))) ) value = args[0] if args else kwargs["value"] return self.xmlvalue(value) def __eq__(self, other): return ( other is not None and self.__class__ == other.__class__ and self.__dict__ == other.__dict__ ) def __str__(self): return "%s(value)" % (self.__class__.__name__) def parse_xmlelement( self, xmlelement, schema=None, allow_none=True, context=None, schema_type=None ): if xmlelement.text is None: return try: return self.pythonvalue(xmlelement.text) except (TypeError, ValueError): logger.exception("Error during xml -> python translation") return None def pythonvalue(self, xmlvalue): raise NotImplementedError( "%s.pytonvalue() not implemented" % self.__class__.__name__ ) def render(self, parent, value, xsd_type=None, render_path=None): if value is Nil: parent.set(xsi_ns("nil"), "true") return parent.text = self.xmlvalue(value) def signature(self, schema=None, standalone=True): return self.get_prefixed_name(schema) def validate(self, value, required=False): if required and value is None: raise ValidationError("Value is required")
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/xsd/types/simple.py
simple.py
from zeep.utils import get_base_class from zeep.xsd.types.simple import AnySimpleType __all__ = ["ListType", "UnionType"] class ListType(AnySimpleType): """Space separated list of simpleType values""" def __init__(self, item_type): self.item_type = item_type super(ListType, self).__init__() def __call__(self, value): return value def render(self, parent, value, xsd_type=None, render_path=None): parent.text = self.xmlvalue(value) def resolve(self): self.item_type = self.item_type.resolve() self.base_class = self.item_type.__class__ return self def xmlvalue(self, value): item_type = self.item_type return " ".join(item_type.xmlvalue(v) for v in value) def pythonvalue(self, value): if not value: return [] item_type = self.item_type return [item_type.pythonvalue(v) for v in value.split()] def signature(self, schema=None, standalone=True): return self.item_type.signature(schema) + "[]" class UnionType(AnySimpleType): """Simple type existing out of multiple other types""" def __init__(self, item_types): self.item_types = item_types self.item_class = None assert item_types super(UnionType, self).__init__(None) def resolve(self): self.item_types = [item.resolve() for item in self.item_types] base_class = get_base_class(self.item_types) if issubclass(base_class, AnySimpleType) and base_class != AnySimpleType: self.item_class = base_class return self def signature(self, schema=None, standalone=True): return "" def parse_xmlelement( self, xmlelement, schema=None, allow_none=True, context=None, schema_type=None ): if self.item_class: return self.item_class().parse_xmlelement( xmlelement, schema, allow_none, context ) return xmlelement.text def pythonvalue(self, value): if self.item_class: return self.item_class().pythonvalue(value) return value def xmlvalue(self, value): if self.item_class: return self.item_class().xmlvalue(value) return value
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/xsd/types/collection.py
collection.py
import copy import logging from collections import OrderedDict, deque from itertools import chain from cached_property import threaded_cached_property from zeep.exceptions import UnexpectedElementError, XMLParseError from zeep.xsd.const import NotSet, SkipValue, Nil, xsi_ns from zeep.xsd.elements import ( Any, AnyAttribute, AttributeGroup, Choice, Element, Group, Sequence) from zeep.xsd.elements.indicators import OrderIndicator from zeep.xsd.types.any import AnyType from zeep.xsd.types.simple import AnySimpleType from zeep.xsd.utils import NamePrefixGenerator from zeep.xsd.valueobjects import ArrayValue, CompoundValue logger = logging.getLogger(__name__) __all__ = ["ComplexType"] class ComplexType(AnyType): _xsd_name = None def __init__( self, element=None, attributes=None, restriction=None, extension=None, qname=None, is_global=False, ): if element and type(element) == list: element = Sequence(element) self.name = self.__class__.__name__ if qname else None self._element = element self._attributes = attributes or [] self._restriction = restriction self._extension = extension self._extension_types = tuple() super(ComplexType, self).__init__(qname=qname, is_global=is_global) def __call__(self, *args, **kwargs): if self._array_type: return self._array_class(*args, **kwargs) return self._value_class(*args, **kwargs) @property def accepted_types(self): return (self._value_class,) + self._extension_types @threaded_cached_property def _array_class(self): assert self._array_type return type( self.__class__.__name__, (ArrayValue,), {"_xsd_type": self, "__module__": "zeep.objects"}, ) @threaded_cached_property def _value_class(self): return type( self.__class__.__name__, (CompoundValue,), {"_xsd_type": self, "__module__": "zeep.objects"}, ) def __str__(self): return "%s(%s)" % (self.__class__.__name__, self.signature()) @threaded_cached_property def attributes(self): generator = NamePrefixGenerator(prefix="_attr_") result = [] elm_names = {name for name, elm in self.elements if name is not None} for attr in self._attributes_unwrapped: if attr.name is None: name = generator.get_name() elif attr.name in elm_names: name = "attr__%s" % attr.name else: name = attr.name result.append((name, attr)) return result @threaded_cached_property def _attributes_unwrapped(self): attributes = [] for attr in self._attributes: if isinstance(attr, AttributeGroup): attributes.extend(attr.attributes) else: attributes.append(attr) return attributes @threaded_cached_property def elements(self): """List of tuples containing the element name and the element""" result = [] for name, element in self.elements_nested: if isinstance(element, Element): result.append((element.attr_name, element)) else: result.extend(element.elements) return result @threaded_cached_property def elements_nested(self): """List of tuples containing the element name and the element""" result = [] generator = NamePrefixGenerator() # Handle wsdl:arrayType objects if self._array_type: name = generator.get_name() if isinstance(self._element, Group): result = [ ( name, Sequence( [ Any( max_occurs="unbounded", restrict=self._array_type.array_type, ) ] ), ) ] else: result = [(name, self._element)] else: # _element is one of All, Choice, Group, Sequence if self._element: result.append((generator.get_name(), self._element)) return result @property def _array_type(self): attrs = {attr.qname.text: attr for attr in self._attributes if attr.qname} array_type = attrs.get("{http://schemas.xmlsoap.org/soap/encoding/}arrayType") return array_type def parse_xmlelement( self, xmlelement, schema=None, allow_none=True, context=None, schema_type=None ): """Consume matching xmlelements and call parse() on each :param xmlelement: XML element objects :type xmlelement: lxml.etree._Element :param schema: The parent XML schema :type schema: zeep.xsd.Schema :param allow_none: Allow none :type allow_none: bool :param context: Optional parsing context (for inline schemas) :type context: zeep.xsd.context.XmlParserContext :param schema_type: The original type (not overriden via xsi:type) :type schema_type: zeep.xsd.types.base.Type :rtype: dict or None """ # If this is an empty complexType (<xsd:complexType name="x"/>) if not self.attributes and not self.elements: return None attributes = xmlelement.attrib init_kwargs = OrderedDict() # If this complexType extends a simpleType then we have no nested # elements. Parse it directly via the type object. This is the case # for xsd:simpleContent if isinstance(self._element, Element) and isinstance( self._element.type, AnySimpleType ): name, element = self.elements_nested[0] init_kwargs[name] = element.type.parse_xmlelement( xmlelement, schema, name, context=context ) else: elements = deque(xmlelement.iterchildren()) if allow_none and len(elements) == 0 and len(attributes) == 0: return # Parse elements. These are always indicator elements (all, choice, # group, sequence) assert len(self.elements_nested) < 2 for name, element in self.elements_nested: try: result = element.parse_xmlelements( elements, schema, name, context=context ) if result: init_kwargs.update(result) except UnexpectedElementError as exc: raise XMLParseError(exc.message) # Check if all children are consumed (parsed) if elements: if schema.settings.strict: raise XMLParseError("Unexpected element %r" % elements[0].tag) else: init_kwargs["_raw_elements"] = elements # Parse attributes if attributes: attributes = copy.copy(attributes) for name, attribute in self.attributes: if attribute.name: if attribute.qname.text in attributes: value = attributes.pop(attribute.qname.text) init_kwargs[name] = attribute.parse(value) else: init_kwargs[name] = attribute.parse(attributes) value = self._value_class(**init_kwargs) schema_type = schema_type or self if schema_type and getattr(schema_type, "_array_type", None): value = schema_type._array_class.from_value_object(value) return value def render(self, parent, value, xsd_type=None, render_path=None): """Serialize the given value lxml.Element subelements on the parent element. :type parent: lxml.etree._Element :type value: Union[list, dict, zeep.xsd.valueobjects.CompoundValue] :type xsd_type: zeep.xsd.types.base.Type :param render_path: list """ if not render_path: render_path = [self.name] if not self.elements_nested and not self.attributes: return # TODO: Implement test case for this if value is None: value = {} if isinstance(value, ArrayValue): value = value.as_value_object() # Render attributes for name, attribute in self.attributes: attr_value = value[name] if name in value else NotSet child_path = render_path + [name] attribute.render(parent, attr_value, child_path) if ( len(self.elements_nested) == 1 and isinstance(value, self.accepted_types) and not isinstance(value, (list, dict, CompoundValue)) ): element = self.elements_nested[0][1] element.type.render(parent, value, None, child_path) return # Render sub elements for name, element in self.elements_nested: if isinstance(element, Element) or element.accepts_multiple: element_value = value[name] if name in value else NotSet child_path = render_path + [name] else: element_value = value child_path = list(render_path) # We want to explicitly skip this sub-element if element_value is SkipValue: continue if isinstance(element, Element): element.type.render(parent, element_value, None, child_path) else: element.render(parent, element_value, child_path) if xsd_type: if xsd_type._xsd_name: parent.set(xsi_ns("type"), xsd_type._xsd_name) if xsd_type.qname: parent.set(xsi_ns("type"), xsd_type.qname) def parse_kwargs(self, kwargs, name, available_kwargs): """Parse the kwargs for this type and return the accepted data as a dict. :param kwargs: The kwargs :type kwargs: dict :param name: The name as which this type is registered in the parent :type name: str :param available_kwargs: The kwargs keys which are still available, modified in place :type available_kwargs: set :rtype: dict """ value = None name = name or self.name if name in available_kwargs: value = kwargs[name] available_kwargs.remove(name) if value is not Nil: value = self._create_object(value, name) return {name: value} return {} def _create_object(self, value, name): """Return the value as a CompoundValue object :type value: str :type value: list, dict, CompoundValue """ if value is None: return None if isinstance(value, list) and not self._array_type: return [self._create_object(val, name) for val in value] if isinstance(value, CompoundValue) or value is SkipValue: return value if isinstance(value, dict): return self(**value) # Try to automatically create an object. This might fail if there # are multiple required arguments. return self(value) def resolve(self): """Resolve all sub elements and types""" if self._resolved: return self._resolved self._resolved = self resolved = [] for attribute in self._attributes: value = attribute.resolve() assert value is not None if isinstance(value, list): resolved.extend(value) else: resolved.append(value) self._attributes = resolved if self._extension: self._extension = self._extension.resolve() self._resolved = self.extend(self._extension) elif self._restriction: self._restriction = self._restriction.resolve() self._resolved = self.restrict(self._restriction) if self._element: self._element = self._element.resolve() return self._resolved def extend(self, base): """Create a new ComplexType instance which is the current type extending the given base type. Used for handling xsd:extension tags TODO: Needs a rewrite where the child containers are responsible for the extend functionality. :type base: zeep.xsd.types.base.Type :rtype base: zeep.xsd.types.base.Type """ if isinstance(base, ComplexType): base_attributes = base._attributes_unwrapped base_element = base._element else: base_attributes = [] base_element = None attributes = base_attributes + self._attributes_unwrapped # Make sure we don't have duplicate (child is leading) if base_attributes and self._attributes_unwrapped: new_attributes = OrderedDict() for attr in attributes: if isinstance(attr, AnyAttribute): new_attributes["##any"] = attr else: new_attributes[attr.qname.text] = attr attributes = new_attributes.values() # If the base and the current type both have an element defined then # these need to be merged. The base_element might be empty (or just # container a placeholder element). element = [] if self._element and base_element: self._element = self._element.resolve() base_element = base_element.resolve() element = self._element.clone(self._element.name) if isinstance(base_element, OrderIndicator): if isinstance(base_element, Choice): element.insert(0, base_element) elif isinstance(self._element, Choice): element = base_element.clone(self._element.name) element.append(self._element) elif isinstance(element, OrderIndicator): for item in reversed(base_element): element.insert(0, item) elif isinstance(element, Group): for item in reversed(base_element): element.child.insert(0, item) elif isinstance(self._element, Group): raise NotImplementedError("TODO") else: pass # Element (ignore for now) elif self._element or base_element: element = self._element or base_element else: element = Element("_value_1", base) new = self.__class__( element=element, attributes=attributes, qname=self.qname, is_global=self.is_global, ) new._extension_types = base.accepted_types return new def restrict(self, base): """Create a new complextype instance which is the current type restricted by the base type. Used for handling xsd:restriction :type base: zeep.xsd.types.base.Type :rtype base: zeep.xsd.types.base.Type """ attributes = list(chain(base._attributes_unwrapped, self._attributes_unwrapped)) # Make sure we don't have duplicate (self is leading) if base._attributes_unwrapped and self._attributes_unwrapped: new_attributes = OrderedDict() for attr in attributes: if isinstance(attr, AnyAttribute): new_attributes["##any"] = attr else: new_attributes[attr.qname.text] = attr attributes = list(new_attributes.values()) if base._element: base._element.resolve() new = self.__class__( element=self._element or base._element, attributes=attributes, qname=self.qname, is_global=self.is_global, ) return new.resolve() def signature(self, schema=None, standalone=True): parts = [] for name, element in self.elements_nested: part = element.signature(schema, standalone=False) parts.append(part) for name, attribute in self.attributes: part = "%s: %s" % (name, attribute.signature(schema, standalone=False)) parts.append(part) value = ", ".join(parts) if standalone: return "%s(%s)" % (self.get_prefixed_name(schema), value) else: return value
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/xsd/types/complex.py
complex.py
import logging from zeep.utils import qname_attr from zeep.xsd.const import xsd_ns, xsi_ns from zeep.xsd.types.base import Type from zeep.xsd.valueobjects import AnyObject logger = logging.getLogger(__name__) __all__ = ["AnyType"] class AnyType(Type): _default_qname = xsd_ns("anyType") _attributes_unwrapped = [] _element = None def __call__(self, value=None): return value or "" def render(self, parent, value, xsd_type=None, render_path=None): if isinstance(value, AnyObject): if value.xsd_type is None: parent.set(xsi_ns("nil"), "true") else: value.xsd_type.render(parent, value.value, None, render_path) parent.set(xsi_ns("type"), value.xsd_type.qname) elif hasattr(value, "_xsd_elm"): value._xsd_elm.render(parent, value, render_path) parent.set(xsi_ns("type"), value._xsd_elm.qname) else: parent.text = self.xmlvalue(value) def parse_xmlelement( self, xmlelement, schema=None, allow_none=True, context=None, schema_type=None ): """Consume matching xmlelements and call parse() on each :param xmlelement: XML element objects :type xmlelement: lxml.etree._Element :param schema: The parent XML schema :type schema: zeep.xsd.Schema :param allow_none: Allow none :type allow_none: bool :param context: Optional parsing context (for inline schemas) :type context: zeep.xsd.context.XmlParserContext :param schema_type: The original type (not overriden via xsi:type) :type schema_type: zeep.xsd.types.base.Type :rtype: dict or None """ xsi_type = qname_attr(xmlelement, xsi_ns("type")) xsi_nil = xmlelement.get(xsi_ns("nil")) children = list(xmlelement) # Handle xsi:nil attribute if xsi_nil == "true": return None # Check if a xsi:type is defined and try to parse the xml according # to that type. if xsi_type and schema: xsd_type = schema.get_type(xsi_type, fail_silently=True) # If we were unable to resolve a type for the xsi:type (due to # buggy soap servers) then we just return the text or lxml element. if not xsd_type: logger.debug( "Unable to resolve type for %r, returning raw data", xsi_type.text ) if xmlelement.text: return xmlelement.text return children # If the xsd_type is xsd:anyType then we will recurs so ignore # that. if isinstance(xsd_type, self.__class__): return xmlelement.text or None return xsd_type.parse_xmlelement(xmlelement, schema, context=context) # If no xsi:type is set and the element has children then there is # not much we can do. Just return the children elif children: return children elif xmlelement.text is not None: return self.pythonvalue(xmlelement.text) return None def resolve(self): return self def xmlvalue(self, value): """Guess the xsd:type for the value and use corresponding serializer""" from zeep.xsd.types import builtins available_types = [ builtins.String, builtins.Boolean, builtins.Decimal, builtins.Float, builtins.DateTime, builtins.Date, builtins.Time, ] for xsd_type in available_types: if isinstance(value, xsd_type.accepted_types): return xsd_type().xmlvalue(value) return str(value) def pythonvalue(self, value, schema=None): return value def signature(self, schema=None, standalone=True): return "xsd:anyType"
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/xsd/types/any.py
any.py
import base64 import datetime import math import re from decimal import Decimal as _Decimal import isodate import pytz import six from zeep.xsd.const import xsd_ns from zeep.xsd.types.any import AnyType from zeep.xsd.types.simple import AnySimpleType class ParseError(ValueError): pass class BuiltinType(object): def __init__(self, qname=None, is_global=False): super(BuiltinType, self).__init__(qname, is_global=True) def check_no_collection(func): def _wrapper(self, value): if isinstance(value, (list, dict, set)): raise ValueError( "The %s type doesn't accept collections as value" % (self.__class__.__name__) ) return func(self, value) return _wrapper ## # Primitive types class String(BuiltinType, AnySimpleType): _default_qname = xsd_ns("string") accepted_types = six.string_types @check_no_collection def xmlvalue(self, value): if isinstance(value, bytes): return value.decode("utf-8") return six.text_type(value if value is not None else "") def pythonvalue(self, value): return value class Boolean(BuiltinType, AnySimpleType): _default_qname = xsd_ns("boolean") accepted_types = (bool,) @check_no_collection def xmlvalue(self, value): return "true" if value and value not in ("false", "0") else "false" def pythonvalue(self, value): """Return True if the 'true' or '1'. 'false' and '0' are legal false values, but we consider everything not true as false. """ return value in ("true", "1") class Decimal(BuiltinType, AnySimpleType): _default_qname = xsd_ns("decimal") accepted_types = (_Decimal, float) + six.string_types @check_no_collection def xmlvalue(self, value): return str(value) def pythonvalue(self, value): return _Decimal(value) class Float(BuiltinType, AnySimpleType): _default_qname = xsd_ns("float") accepted_types = (float, _Decimal) + six.string_types def xmlvalue(self, value): return str(value).upper() def pythonvalue(self, value): return float(value) class Double(BuiltinType, AnySimpleType): _default_qname = xsd_ns("double") accepted_types = (_Decimal, float) + six.string_types @check_no_collection def xmlvalue(self, value): return str(value) def pythonvalue(self, value): return float(value) class Duration(BuiltinType, AnySimpleType): _default_qname = xsd_ns("duration") accepted_types = (isodate.duration.Duration,) + six.string_types @check_no_collection def xmlvalue(self, value): return isodate.duration_isoformat(value) def pythonvalue(self, value): if value.startswith("PT-"): value = value.replace("PT-", "PT") result = isodate.parse_duration(value) return datetime.timedelta(0 - result.total_seconds()) else: return isodate.parse_duration(value) class DateTime(BuiltinType, AnySimpleType): _default_qname = xsd_ns("dateTime") accepted_types = (datetime.datetime,) + six.string_types @check_no_collection def xmlvalue(self, value): if isinstance(value, six.string_types): return value # Bit of a hack, since datetime is a subclass of date we can't just # test it with an isinstance(). And actually, we should not really # care about the type, as long as it has the required attributes if not all(hasattr(value, attr) for attr in ("hour", "minute", "second")): value = datetime.datetime.combine( value, datetime.time( getattr(value, "hour", 0), getattr(value, "minute", 0), getattr(value, "second", 0), ), ) if getattr(value, "microsecond", 0): return isodate.isostrf.strftime(value, "%Y-%m-%dT%H:%M:%S.%f%Z") return isodate.isostrf.strftime(value, "%Y-%m-%dT%H:%M:%S%Z") def pythonvalue(self, value): # Determine based on the length of the value if it only contains a date # lazy hack ;-) if len(value) == 10: value += "T00:00:00" return isodate.parse_datetime(value) class Time(BuiltinType, AnySimpleType): _default_qname = xsd_ns("time") accepted_types = (datetime.time,) + six.string_types @check_no_collection def xmlvalue(self, value): if isinstance(value, six.string_types): return value if value.microsecond: return isodate.isostrf.strftime(value, "%H:%M:%S.%f%Z") return isodate.isostrf.strftime(value, "%H:%M:%S%Z") def pythonvalue(self, value): return isodate.parse_time(value) class Date(BuiltinType, AnySimpleType): _default_qname = xsd_ns("date") accepted_types = (datetime.date,) + six.string_types @check_no_collection def xmlvalue(self, value): if isinstance(value, six.string_types): return value return isodate.isostrf.strftime(value, "%Y-%m-%d") def pythonvalue(self, value): return isodate.parse_date(value) class gYearMonth(BuiltinType, AnySimpleType): """gYearMonth represents a specific gregorian month in a specific gregorian year. Lexical representation: CCYY-MM """ accepted_types = (datetime.date,) + six.string_types _default_qname = xsd_ns("gYearMonth") _pattern = re.compile( r"^(?P<year>-?\d{4,})-(?P<month>\d\d)(?P<timezone>Z|[-+]\d\d:?\d\d)?$" ) @check_no_collection def xmlvalue(self, value): year, month, tzinfo = value return "%04d-%02d%s" % (year, month, _unparse_timezone(tzinfo)) def pythonvalue(self, value): match = self._pattern.match(value) if not match: raise ParseError() group = match.groupdict() return ( int(group["year"]), int(group["month"]), _parse_timezone(group["timezone"]), ) class gYear(BuiltinType, AnySimpleType): """gYear represents a gregorian calendar year. Lexical representation: CCYY """ accepted_types = (datetime.date,) + six.string_types _default_qname = xsd_ns("gYear") _pattern = re.compile(r"^(?P<year>-?\d{4,})(?P<timezone>Z|[-+]\d\d:?\d\d)?$") @check_no_collection def xmlvalue(self, value): year, tzinfo = value return "%04d%s" % (year, _unparse_timezone(tzinfo)) def pythonvalue(self, value): match = self._pattern.match(value) if not match: raise ParseError() group = match.groupdict() return (int(group["year"]), _parse_timezone(group["timezone"])) class gMonthDay(BuiltinType, AnySimpleType): """gMonthDay is a gregorian date that recurs, specifically a day of the year such as the third of May. Lexical representation: --MM-DD """ accepted_types = (datetime.date,) + six.string_types _default_qname = xsd_ns("gMonthDay") _pattern = re.compile( r"^--(?P<month>\d\d)-(?P<day>\d\d)(?P<timezone>Z|[-+]\d\d:?\d\d)?$" ) @check_no_collection def xmlvalue(self, value): month, day, tzinfo = value return "--%02d-%02d%s" % (month, day, _unparse_timezone(tzinfo)) def pythonvalue(self, value): match = self._pattern.match(value) if not match: raise ParseError() group = match.groupdict() return ( int(group["month"]), int(group["day"]), _parse_timezone(group["timezone"]), ) class gDay(BuiltinType, AnySimpleType): """gDay is a gregorian day that recurs, specifically a day of the month such as the 5th of the month Lexical representation: ---DD """ accepted_types = (datetime.date,) + six.string_types _default_qname = xsd_ns("gDay") _pattern = re.compile(r"^---(?P<day>\d\d)(?P<timezone>Z|[-+]\d\d:?\d\d)?$") @check_no_collection def xmlvalue(self, value): day, tzinfo = value return "---%02d%s" % (day, _unparse_timezone(tzinfo)) def pythonvalue(self, value): match = self._pattern.match(value) if not match: raise ParseError() group = match.groupdict() return (int(group["day"]), _parse_timezone(group["timezone"])) class gMonth(BuiltinType, AnySimpleType): """gMonth is a gregorian month that recurs every year. Lexical representation: --MM """ accepted_types = (datetime.date,) + six.string_types _default_qname = xsd_ns("gMonth") _pattern = re.compile(r"^--(?P<month>\d\d)(?P<timezone>Z|[-+]\d\d:?\d\d)?$") @check_no_collection def xmlvalue(self, value): month, tzinfo = value return "--%d%s" % (month, _unparse_timezone(tzinfo)) def pythonvalue(self, value): match = self._pattern.match(value) if not match: raise ParseError() group = match.groupdict() return (int(group["month"]), _parse_timezone(group["timezone"])) class HexBinary(BuiltinType, AnySimpleType): accepted_types = six.string_types _default_qname = xsd_ns("hexBinary") @check_no_collection def xmlvalue(self, value): return value def pythonvalue(self, value): return value class Base64Binary(BuiltinType, AnySimpleType): accepted_types = six.string_types _default_qname = xsd_ns("base64Binary") @check_no_collection def xmlvalue(self, value): return base64.b64encode(value) def pythonvalue(self, value): return base64.b64decode(value) class AnyURI(BuiltinType, AnySimpleType): accepted_types = six.string_types _default_qname = xsd_ns("anyURI") @check_no_collection def xmlvalue(self, value): return value def pythonvalue(self, value): return value class QName(BuiltinType, AnySimpleType): accepted_types = six.string_types _default_qname = xsd_ns("QName") @check_no_collection def xmlvalue(self, value): return value def pythonvalue(self, value): return value class Notation(BuiltinType, AnySimpleType): accepted_types = six.string_types _default_qname = xsd_ns("NOTATION") ## # Derived datatypes class NormalizedString(String): _default_qname = xsd_ns("normalizedString") class Token(NormalizedString): _default_qname = xsd_ns("token") class Language(Token): _default_qname = xsd_ns("language") class NmToken(Token): _default_qname = xsd_ns("NMTOKEN") class NmTokens(NmToken): _default_qname = xsd_ns("NMTOKENS") class Name(Token): _default_qname = xsd_ns("Name") class NCName(Name): _default_qname = xsd_ns("NCName") class ID(NCName): _default_qname = xsd_ns("ID") class IDREF(NCName): _default_qname = xsd_ns("IDREF") class IDREFS(IDREF): _default_qname = xsd_ns("IDREFS") class Entity(NCName): _default_qname = xsd_ns("ENTITY") class Entities(Entity): _default_qname = xsd_ns("ENTITIES") class Integer(Decimal): _default_qname = xsd_ns("integer") accepted_types = (int, float) + six.string_types def xmlvalue(self, value): return str(value) def pythonvalue(self, value): return int(value) class NonPositiveInteger(Integer): _default_qname = xsd_ns("nonPositiveInteger") class NegativeInteger(Integer): _default_qname = xsd_ns("negativeInteger") class Long(Integer): _default_qname = xsd_ns("long") def pythonvalue(self, value): return long(value) if six.PY2 else int(value) # noqa class Int(Long): _default_qname = xsd_ns("int") class Short(Int): _default_qname = xsd_ns("short") class Byte(Short): """A signed 8-bit integer""" _default_qname = xsd_ns("byte") class NonNegativeInteger(Integer): _default_qname = xsd_ns("nonNegativeInteger") class UnsignedLong(NonNegativeInteger): _default_qname = xsd_ns("unsignedLong") class UnsignedInt(UnsignedLong): _default_qname = xsd_ns("unsignedInt") class UnsignedShort(UnsignedInt): _default_qname = xsd_ns("unsignedShort") class UnsignedByte(UnsignedShort): _default_qname = xsd_ns("unsignedByte") class PositiveInteger(NonNegativeInteger): _default_qname = xsd_ns("positiveInteger") ## # Other def _parse_timezone(val): """Return a pytz.tzinfo object""" if not val: return if val == "Z" or val == "+00:00": return pytz.utc negative = val.startswith("-") minutes = int(val[-2:]) minutes += int(val[1:3]) * 60 if negative: minutes = 0 - minutes return pytz.FixedOffset(minutes) def _unparse_timezone(tzinfo): if not tzinfo: return "" if tzinfo == pytz.utc: return "Z" hours = math.floor(tzinfo._minutes / 60) minutes = tzinfo._minutes % 60 if hours > 0: return "+%02d:%02d" % (hours, minutes) return "-%02d:%02d" % (abs(hours), minutes) _types = [ # Primitive String, Boolean, Decimal, Float, Double, Duration, DateTime, Time, Date, gYearMonth, gYear, gMonthDay, gDay, gMonth, HexBinary, Base64Binary, AnyURI, QName, Notation, # Derived NormalizedString, Token, Language, NmToken, NmTokens, Name, NCName, ID, IDREF, IDREFS, Entity, Entities, Integer, NonPositiveInteger, # noqa NegativeInteger, Long, Int, Short, Byte, NonNegativeInteger, # noqa UnsignedByte, UnsignedInt, UnsignedLong, UnsignedShort, PositiveInteger, # Other AnyType, AnySimpleType, ] default_types = {cls._default_qname: cls(is_global=True) for cls in _types}
zeep-bold
/zeep-bold-3.6.0.tar.gz/zeep-bold-3.6.0/src/zeep/xsd/types/builtins.py
builtins.py
Authors ======= * Michael van Tellingen Contributors ============ * Kateryna Burda * Alexey Stepanov * Marco Vellinga * jaceksnet * Andrew Serong * vashek * Seppo Yli-Olli * Sam Denton * Dani Möller * Julien Delasoie * Christian González * bjarnagin * mcordes * Joeri Bekker * Bartek Wójcicki * jhorman * fiebiga * David Baumgold * Antonio Cuni * Alexandre de Mari * Nicolas Evrard * Eric Wong * Jason Vertrees * Falldog * Matt Grimm (mgrimm) * Marek Wywiał * btmanm * Caleb Salt * Ondřej Lanč * Jan Murre * Stefano Parmesan * Julien Marechal * Dave Wapstra * Mike Fiedler * Derek Harland * Bruno Duyé * Christoph Heuel * Ben Tucker * Eric Waller * Falk Schuetzenmeister * Jon Jenkins * OrangGeeGee * Raymond Piller * Zoltan Benedek * Øyvind Heddeland Instefjord
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/CONTRIBUTORS.rst
CONTRIBUTORS.rst
======================== Zeep: Python SOAP client ======================== A fast and modern Python SOAP client Highlights: * Compatible with Python 2.7, 3.5, 3.6, 3.7 and PyPy * Build on top of lxml and requests * Support for Soap 1.1, Soap 1.2 and HTTP bindings * Support for WS-Addressing headers * Support for WSSE (UserNameToken / x.509 signing) * Support for tornado async transport via gen.coroutine (Python 2.7+) * Support for asyncio via aiohttp (Python 3.5+) * Experimental support for XOP messages Please see for more information the documentation at http://docs.python-zeep.org/ .. start-no-pypi Status ------ .. image:: https://readthedocs.org/projects/python-zeep/badge/?version=latest :target: https://readthedocs.org/projects/python-zeep/ .. image:: https://dev.azure.com/mvantellingen/zeep/_apis/build/status/python-zeep?branchName=master :target: https://dev.azure.com/mvantellingen/zeep/_build?definitionId=1 .. image:: http://codecov.io/github/mvantellingen/python-zeep/coverage.svg?branch=master :target: http://codecov.io/github/mvantellingen/python-zeep?branch=master .. image:: https://img.shields.io/pypi/v/zeep.svg :target: https://pypi.python.org/pypi/zeep/ .. end-no-pypi Installation ------------ .. code-block:: bash pip install zeep Usage ----- .. code-block:: python from zeep import Client client = Client('tests/wsdl_files/example.rst') client.service.ping() To quickly inspect a WSDL file use:: python -m zeep <url-to-wsdl> Please see the documentation at http://docs.python-zeep.org for more information. Support ======= If you want to report a bug then please first read http://docs.python-zeep.org/en/master/reporting_bugs.html Please only report bugs and not support requests to the GitHub issue tracker.
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/README.rst
README.rst
from __future__ import absolute_import, print_function import argparse import logging import logging.config import time import requests from six.moves.urllib.parse import urlparse from zeep.cache import SqliteCache from zeep.client import Client from zeep.settings import Settings from zeep.transports import Transport logger = logging.getLogger("zeep") def parse_arguments(args=None): parser = argparse.ArgumentParser(description="Zeep: The SOAP client") parser.add_argument( "wsdl_file", type=str, help="Path or URL to the WSDL file", default=None ) parser.add_argument("--cache", action="store_true", help="Enable cache") parser.add_argument( "--no-verify", action="store_true", help="Disable SSL verification" ) parser.add_argument("--verbose", action="store_true", help="Enable verbose output") parser.add_argument( "--profile", help="Enable profiling and save output to given file" ) parser.add_argument( "--no-strict", action="store_true", default=False, help="Disable strict mode" ) return parser.parse_args(args) def main(args): if args.verbose: logging.config.dictConfig( { "version": 1, "formatters": {"verbose": {"format": "%(name)20s: %(message)s"}}, "handlers": { "console": { "level": "DEBUG", "class": "logging.StreamHandler", "formatter": "verbose", } }, "loggers": { "zeep": { "level": "DEBUG", "propagate": True, "handlers": ["console"], } }, } ) if args.profile: import cProfile profile = cProfile.Profile() profile.enable() cache = SqliteCache() if args.cache else None session = requests.Session() if args.no_verify: session.verify = False result = urlparse(args.wsdl_file) if result.username or result.password: session.auth = (result.username, result.password) transport = Transport(cache=cache, session=session) st = time.time() settings = Settings(strict=not args.no_strict) client = Client(args.wsdl_file, transport=transport, settings=settings) logger.debug("Loading WSDL took %sms", (time.time() - st) * 1000) if args.profile: profile.disable() profile.dump_stats(args.profile) client.wsdl.dump() if __name__ == "__main__": args = parse_arguments() main(args)
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/src/zeep/__main__.py
__main__.py
import threading from contextlib import contextmanager import attr @attr.s(slots=True) class Settings(object): """ :param strict: boolean to indicate if the lxml should be parsed a 'strict'. If false then the recover mode is enabled which tries to parse invalid XML as best as it can. :type strict: boolean :param raw_response: boolean to skip the parsing of the XML response by zeep but instead returning the raw data :param forbid_dtd: disallow XML with a <!DOCTYPE> processing instruction :type forbid_dtd: bool :param forbid_entities: disallow XML with <!ENTITY> declarations inside the DTD :type forbid_entities: bool :param forbid_external: disallow any access to remote or local resources in external entities or DTD and raising an ExternalReferenceForbidden exception when a DTD or entity references an external resource. :type forbid_entities: bool :param xml_huge_tree: disable lxml/libxml2 security restrictions and support very deep trees and very long text content :param force_https: Force all connections to HTTPS if the WSDL is also loaded from an HTTPS endpoint. (default: true) :type force_https: bool :param extra_http_headers: Additional HTTP headers to be sent to the transport. This can be used in combination with the context manager approach to add http headers for specific calls. :type extra_headers: list :param xsd_ignore_sequence_order: boolean to indicate whether to enforce sequence order when parsing complex types. This is a workaround for servers that don't respect sequence order. :type xsd_ignore_sequence_order: boolean """ strict = attr.ib(default=True) raw_response = attr.ib(default=False) # transport force_https = attr.ib(default=True) extra_http_headers = attr.ib(default=None) # lxml processing xml_huge_tree = attr.ib(default=False) forbid_dtd = attr.ib(default=False) forbid_entities = attr.ib(default=True) forbid_external = attr.ib(default=True) # xsd workarounds xsd_ignore_sequence_order = attr.ib(default=False) _tls = attr.ib(default=attr.Factory(threading.local)) @contextmanager def __call__(self, **options): current = {} for key, value in options.items(): current[key] = getattr(self, key) setattr(self._tls, key, value) yield for key, value in current.items(): default = getattr(self, key) if value == default: delattr(self._tls, key) else: setattr(self._tls, key, value) def __getattribute__(self, key): if key != "_tls" and hasattr(self._tls, key): return getattr(self._tls, key) return super(Settings, self).__getattribute__(key)
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/src/zeep/settings.py
settings.py
import base64 import datetime import errno import logging import os import threading from contextlib import contextmanager import appdirs import pytz import six # The sqlite3 is not available on Google App Engine so we handle the # ImportError here and set the sqlite3 var to None. # See https://github.com/mvantellingen/python-zeep/issues/243 try: import sqlite3 except ImportError: sqlite3 = None logger = logging.getLogger(__name__) class Base(object): def add(self, url, content): raise NotImplemented() def get(self, url): raise NotImplemented() class InMemoryCache(Base): """Simple in-memory caching using dict lookup with support for timeouts""" _cache = {} # global cache, thread-safe by default def __init__(self, timeout=3600): self._timeout = timeout def add(self, url, content): logger.debug("Caching contents of %s", url) if not isinstance(content, (str, bytes)): raise TypeError( "a bytes-like object is required, not {}".format(type(content).__name__) ) self._cache[url] = (datetime.datetime.utcnow(), content) def get(self, url): try: created, content = self._cache[url] except KeyError: pass else: if not _is_expired(created, self._timeout): logger.debug("Cache HIT for %s", url) return content logger.debug("Cache MISS for %s", url) return None class SqliteCache(Base): """Cache contents via an sqlite database on the filesystem""" _version = "1" def __init__(self, path=None, timeout=3600): if sqlite3 is None: raise RuntimeError("sqlite3 module is required for the SqliteCache") # No way we can support this when we want to achieve thread safety if path == ":memory:": raise ValueError( "The SqliteCache doesn't support :memory: since it is not " + "thread-safe. Please use zeep.cache.InMemoryCache()" ) self._lock = threading.RLock() self._timeout = timeout self._db_path = path if path else _get_default_cache_path() # Initialize db with self.db_connection() as conn: cursor = conn.cursor() cursor.execute( """ CREATE TABLE IF NOT EXISTS request (created timestamp, url text, content text) """ ) conn.commit() @contextmanager def db_connection(self): with self._lock: connection = sqlite3.connect( self._db_path, detect_types=sqlite3.PARSE_DECLTYPES ) yield connection connection.close() def add(self, url, content): logger.debug("Caching contents of %s", url) data = self._encode_data(content) with self.db_connection() as conn: cursor = conn.cursor() cursor.execute("DELETE FROM request WHERE url = ?", (url,)) cursor.execute( "INSERT INTO request (created, url, content) VALUES (?, ?, ?)", (datetime.datetime.utcnow(), url, data), ) conn.commit() def get(self, url): with self.db_connection() as conn: cursor = conn.cursor() cursor.execute("SELECT created, content FROM request WHERE url=?", (url,)) rows = cursor.fetchall() if rows: created, data = rows[0] if not _is_expired(created, self._timeout): logger.debug("Cache HIT for %s", url) return self._decode_data(data) logger.debug("Cache MISS for %s", url) def _encode_data(self, data): data = base64.b64encode(data) if six.PY2: return buffer(self._version_string + data) # noqa return self._version_string + data def _decode_data(self, data): if six.PY2: data = str(data) if data.startswith(self._version_string): return base64.b64decode(data[len(self._version_string) :]) @property def _version_string(self): prefix = u"$ZEEP:%s$" % self._version return bytes(prefix.encode("ascii")) def _is_expired(value, timeout): """Return boolean if the value is expired""" if timeout is None: return False now = datetime.datetime.utcnow().replace(tzinfo=pytz.utc) max_age = value.replace(tzinfo=pytz.utc) max_age += datetime.timedelta(seconds=timeout) return now > max_age def _get_default_cache_path(): path = appdirs.user_cache_dir("zeep", False) try: os.makedirs(path) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise return os.path.join(path, "cache.db")
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/src/zeep/cache.py
cache.py
import logging from zeep.proxy import ServiceProxy from zeep.settings import Settings from zeep.transports import Transport from zeep.wsdl import Document logger = logging.getLogger(__name__) class Factory(object): def __init__(self, types, kind, namespace): self._method = getattr(types, "get_%s" % kind) if namespace in types.namespaces: self._ns = namespace else: self._ns = types.get_ns_prefix(namespace) def __getattr__(self, key): """Return the complexType or simpleType for the given localname. :rtype: zeep.xsd.ComplexType or zeep.xsd.AnySimpleType """ return self[key] def __getitem__(self, key): """Return the complexType or simpleType for the given localname. :rtype: zeep.xsd.ComplexType or zeep.xsd.AnySimpleType """ return self._method("{%s}%s" % (self._ns, key)) class Client(object): """The zeep Client. :param wsdl: :param wsse: :param transport: Custom transport class. :param service_name: The service name for the service binding. Defaults to the first service in the WSDL document. :param port_name: The port name for the default binding. Defaults to the first port defined in the service element in the WSDL document. :param plugins: a list of Plugin instances :param settings: a zeep.Settings() object """ def __init__( self, wsdl, wsse=None, transport=None, service_name=None, port_name=None, plugins=None, settings=None, ): if not wsdl: raise ValueError("No URL given for the wsdl") self.settings = settings or Settings() self.transport = transport if transport is not None else Transport() self.wsdl = Document(wsdl, self.transport, settings=self.settings) self.wsse = wsse self.plugins = plugins if plugins is not None else [] self._default_service = None self._default_service_name = service_name self._default_port_name = port_name self._default_soapheaders = None @property def namespaces(self): return self.wsdl.types.prefix_map @property def service(self): """The default ServiceProxy instance :rtype: ServiceProxy """ if self._default_service: return self._default_service self._default_service = self.bind( service_name=self._default_service_name, port_name=self._default_port_name ) if not self._default_service: raise ValueError( "There is no default service defined. This is usually due to " "missing wsdl:service definitions in the WSDL" ) return self._default_service def bind(self, service_name=None, port_name=None): """Create a new ServiceProxy for the given service_name and port_name. The default ServiceProxy instance (`self.service`) always referes to the first service/port in the wsdl Document. Use this when a specific port is required. """ if not self.wsdl.services: return service = self._get_service(service_name) port = self._get_port(service, port_name) return ServiceProxy(self, port.binding, **port.binding_options) def create_service(self, binding_name, address): """Create a new ServiceProxy for the given binding name and address. :param binding_name: The QName of the binding :param address: The address of the endpoint """ try: binding = self.wsdl.bindings[binding_name] except KeyError: raise ValueError( "No binding found with the given QName. Available bindings " "are: %s" % (", ".join(self.wsdl.bindings.keys())) ) return ServiceProxy(self, binding, address=address) def create_message(self, service, operation_name, *args, **kwargs): """Create the payload for the given operation. :rtype: lxml.etree._Element """ envelope, http_headers = service._binding._create( operation_name, args, kwargs, client=self ) return envelope def type_factory(self, namespace): """Return a type factory for the given namespace. Example:: factory = client.type_factory('ns0') user = factory.User(name='John') :rtype: Factory """ return Factory(self.wsdl.types, "type", namespace) def get_type(self, name): """Return the type for the given qualified name. :rtype: zeep.xsd.ComplexType or zeep.xsd.AnySimpleType """ return self.wsdl.types.get_type(name) def get_element(self, name): """Return the element for the given qualified name. :rtype: zeep.xsd.Element """ return self.wsdl.types.get_element(name) def set_ns_prefix(self, prefix, namespace): """Set a shortcut for the given namespace. """ self.wsdl.types.set_ns_prefix(prefix, namespace) def set_default_soapheaders(self, headers): """Set the default soap headers which will be automatically used on all calls. Note that if you pass custom soapheaders using a list then you will also need to use that during the operations. Since mixing these use cases isn't supported (yet). """ self._default_soapheaders = headers def _get_port(self, service, name): if name: port = service.ports.get(name) if not port: raise ValueError("Port not found") else: port = list(service.ports.values())[0] return port def _get_service(self, name): if name: service = self.wsdl.services.get(name) if not service: raise ValueError("Service not found") else: service = next(iter(self.wsdl.services.values()), None) return service class CachingClient(Client): """Shortcut to create a caching client, for the lazy people. This enables the SqliteCache by default in the transport as was the default in earlier versions of zeep. """ def __init__(self, *args, **kwargs): # Don't use setdefault since we want to lazily init the Transport cls from zeep.cache import SqliteCache kwargs["transport"] = kwargs.get("transport") or Transport(cache=SqliteCache()) super(CachingClient, self).__init__(*args, **kwargs)
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/src/zeep/client.py
client.py
import copy import itertools import logging logger = logging.getLogger(__name__) class OperationProxy(object): def __init__(self, service_proxy, operation_name): self._proxy = service_proxy self._op_name = operation_name @property def __doc__(self): return str(self._proxy._binding._operations[self._op_name]) def __call__(self, *args, **kwargs): """Call the operation with the given args and kwargs. :rtype: zeep.xsd.CompoundValue """ # Merge the default _soapheaders with the passed _soapheaders if self._proxy._client._default_soapheaders: op_soapheaders = kwargs.get("_soapheaders") if op_soapheaders: soapheaders = copy.deepcopy(self._proxy._client._default_soapheaders) if type(op_soapheaders) != type(soapheaders): raise ValueError("Incompatible soapheaders definition") if isinstance(soapheaders, list): soapheaders.extend(op_soapheaders) else: soapheaders.update(op_soapheaders) else: soapheaders = self._proxy._client._default_soapheaders kwargs["_soapheaders"] = soapheaders return self._proxy._binding.send( self._proxy._client, self._proxy._binding_options, self._op_name, args, kwargs, ) class ServiceProxy(object): def __init__(self, client, binding, **binding_options): self._client = client self._binding_options = binding_options self._binding = binding self._operations = { name: OperationProxy(self, name) for name in self._binding.all() } def __getattr__(self, key): """Return the OperationProxy for the given key. :rtype: OperationProxy() """ return self[key] def __getitem__(self, key): """Return the OperationProxy for the given key. :rtype: OperationProxy() """ try: return self._operations[key] except KeyError: raise AttributeError("Service has no operation %r" % key) def __iter__(self): """ Return iterator over the services and their callables. """ return iter(self._operations.items()) def __dir__(self): """ Return the names of the operations. """ return list(itertools.chain(dir(super(ServiceProxy, self)), self._operations))
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/src/zeep/proxy.py
proxy.py
import os.path from defusedxml.lxml import fromstring from lxml import etree from six.moves.urllib.parse import urljoin, urlparse, urlunparse from zeep.exceptions import XMLSyntaxError from zeep.settings import Settings class ImportResolver(etree.Resolver): """Custom lxml resolve to use the transport object""" def __init__(self, transport): self.transport = transport def resolve(self, url, pubid, context): if urlparse(url).scheme in ("http", "https"): content = self.transport.load(url) return self.resolve_string(content, context) def parse_xml(content, transport, base_url=None, settings=None): """Parse an XML string and return the root Element. :param content: The XML string :type content: str :param transport: The transport instance to load imported documents :type transport: zeep.transports.Transport :param base_url: The base url of the document, used to make relative lookups absolute. :type base_url: str :param settings: A zeep.settings.Settings object containing parse settings. :type settings: zeep.settings.Settings :returns: The document root :rtype: lxml.etree._Element """ settings = settings or Settings() recover = not settings.strict parser = etree.XMLParser( remove_comments=True, resolve_entities=False, recover=recover, huge_tree=settings.xml_huge_tree, ) parser.resolvers.add(ImportResolver(transport)) try: return fromstring( content, parser=parser, base_url=base_url, forbid_dtd=settings.forbid_dtd, forbid_entities=settings.forbid_entities, ) except etree.XMLSyntaxError as exc: raise XMLSyntaxError( "Invalid XML content received (%s)" % exc.msg, content=content ) def load_external(url, transport, base_url=None, settings=None): """Load an external XML document. :param url: :param transport: :param base_url: :param settings: A zeep.settings.Settings object containing parse settings. :type settings: zeep.settings.Settings """ settings = settings or Settings() if hasattr(url, "read"): content = url.read() else: if base_url: url = absolute_location(url, base_url) content = transport.load(url) return parse_xml(content, transport, base_url, settings=settings) def normalize_location(settings, url, base_url): """Return a 'normalized' url for the given url. This will make the url absolute and force it to https when that setting is enabled. """ # Python 2.7 doesn't accept None to urlparse() calls, but Python 3 does. # So as a guard convert None to '' here so that we can't introduce errors in # Python 2.7 like #930. Can be removed when we drop Python 2 support. if url is None: url = "" if base_url: url = absolute_location(url, base_url) if base_url and settings.force_https: base_url_parts = urlparse(base_url) url_parts = urlparse(url) if ( base_url_parts.netloc == url_parts.netloc and base_url_parts.scheme != url_parts.scheme ): url = urlunparse(("https",) + url_parts[1:]) return url def absolute_location(location, base): """Make an url absolute (if it is optional) via the passed base url. :param location: The (relative) url :type location: str :param base: The base location :type base: str :returns: An absolute URL :rtype: str """ if location == base: return location if urlparse(location).scheme in ("http", "https", "file"): return location if base and urlparse(base).scheme in ("http", "https", "file"): return urljoin(base, location) else: if os.path.isabs(location): return location if base: return os.path.realpath(os.path.join(os.path.dirname(base), location)) return location def is_relative_path(value): """Check if the given value is a relative path :param value: The value :type value: str :returns: Boolean indicating if the url is relative. If it is absolute then False is returned. :rtype: boolean """ if urlparse(value).scheme in ("http", "https", "file"): return False return not os.path.isabs(value)
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/src/zeep/loader.py
loader.py
from collections import deque class Plugin(object): """Base plugin""" def ingress(self, envelope, http_headers, operation): """Override to update the envelope or http headers when receiving a message. :param envelope: The envelope as XML node :param http_headers: Dict with the HTTP headers """ return envelope, http_headers def egress(self, envelope, http_headers, operation, binding_options): """Override to update the envelope or http headers when sending a message. :param envelope: The envelope as XML node :param http_headers: Dict with the HTTP headers :param operation: The associated Operation instance :param binding_options: Binding specific options for the operation """ return envelope, http_headers def apply_egress(client, envelope, http_headers, operation, binding_options): for plugin in client.plugins: result = plugin.egress(envelope, http_headers, operation, binding_options) if result is not None: envelope, http_headers = result return envelope, http_headers def apply_ingress(client, envelope, http_headers, operation): for plugin in client.plugins: result = plugin.ingress(envelope, http_headers, operation) if result is not None: envelope, http_headers = result return envelope, http_headers class HistoryPlugin(object): def __init__(self, maxlen=1): self._buffer = deque([], maxlen) @property def last_sent(self): last_tx = self._buffer[-1] if last_tx: return last_tx["sent"] @property def last_received(self): last_tx = self._buffer[-1] if last_tx: return last_tx["received"] def ingress(self, envelope, http_headers, operation): last_tx = self._buffer[-1] last_tx["received"] = {"envelope": envelope, "http_headers": http_headers} def egress(self, envelope, http_headers, operation, binding_options): self._buffer.append( { "received": None, "sent": {"envelope": envelope, "http_headers": http_headers}, } )
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/src/zeep/plugins.py
plugins.py
import cgi import inspect from lxml import etree from zeep.exceptions import XMLParseError from zeep.ns import XSD def qname_attr(node, attr_name, target_namespace=None): value = node.get(attr_name) if value is not None: return as_qname(value, node.nsmap, target_namespace) def as_qname(value, nsmap, target_namespace=None): """Convert the given value to a QName""" value = value.strip() # some xsd's contain leading/trailing spaces if ":" in value: prefix, local = value.split(":") # The xml: prefix is always bound to the XML namespace, see # https://www.w3.org/TR/xml-names/ if prefix == "xml": namespace = "http://www.w3.org/XML/1998/namespace" else: namespace = nsmap.get(prefix) if not namespace: raise XMLParseError("No namespace defined for %r (%r)" % (prefix, value)) # Workaround for https://github.com/mvantellingen/python-zeep/issues/349 if not local: return etree.QName(XSD, "anyType") return etree.QName(namespace, local) if target_namespace: return etree.QName(target_namespace, value) if nsmap.get(None): return etree.QName(nsmap[None], value) return etree.QName(value) def findall_multiple_ns(node, name, namespace_sets): result = [] for nsmap in namespace_sets: result.extend(node.findall(name, namespaces=nsmap)) return result def get_version(): from zeep import __version__ # cyclic import return __version__ def get_base_class(objects): """Return the best base class for multiple objects. Implementation is quick and dirty, might be done better.. ;-) """ bases = [inspect.getmro(obj.__class__)[::-1] for obj in objects] num_objects = len(objects) max_mro = max(len(mro) for mro in bases) base_class = None for i in range(max_mro): try: if len({bases[j][i] for j in range(num_objects)}) > 1: break except IndexError: break base_class = bases[0][i] return base_class def detect_soap_env(envelope): root_tag = etree.QName(envelope) return root_tag.namespace def get_media_type(value): """Parse a HTTP content-type header and return the media-type""" main_value, parameters = cgi.parse_header(value) return main_value.lower()
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/src/zeep/utils.py
utils.py
import logging import os from contextlib import contextmanager import requests from six.moves.urllib.parse import urlparse from zeep.utils import get_media_type, get_version from zeep.wsdl.utils import etree_to_string class Transport(object): """The transport object handles all communication to the SOAP server. :param cache: The cache object to be used to cache GET requests :param timeout: The timeout for loading wsdl and xsd documents. :param operation_timeout: The timeout for operations (POST/GET). By default this is None (no timeout). :param session: A :py:class:`request.Session()` object (optional) """ def __init__(self, cache=None, timeout=300, operation_timeout=None, session=None): self.cache = cache self.load_timeout = timeout self.operation_timeout = operation_timeout self.logger = logging.getLogger(__name__) self.session = session or requests.Session() self.session.headers["User-Agent"] = "Zeep/%s (www.python-zeep.org)" % ( get_version() ) def get(self, address, params, headers): """Proxy to requests.get() :param address: The URL for the request :param params: The query parameters :param headers: a dictionary with the HTTP headers. """ response = self.session.get( address, params=params, headers=headers, timeout=self.operation_timeout ) return response def post(self, address, message, headers): """Proxy to requests.posts() :param address: The URL for the request :param message: The content for the body :param headers: a dictionary with the HTTP headers. """ if self.logger.isEnabledFor(logging.DEBUG): log_message = message if isinstance(log_message, bytes): log_message = log_message.decode("utf-8") self.logger.debug("HTTP Post to %s:\n%s", address, log_message) response = self.session.post( address, data=message, headers=headers, timeout=self.operation_timeout ) if self.logger.isEnabledFor(logging.DEBUG): media_type = get_media_type( response.headers.get("Content-Type", "text/xml") ) if media_type == "multipart/related": log_message = response.content else: log_message = response.content if isinstance(log_message, bytes): log_message = log_message.decode(response.encoding or "utf-8") self.logger.debug( "HTTP Response from %s (status: %d):\n%s", address, response.status_code, log_message, ) return response def post_xml(self, address, envelope, headers): """Post the envelope xml element to the given address with the headers. This method is intended to be overriden if you want to customize the serialization of the xml element. By default the body is formatted and encoded as utf-8. See ``zeep.wsdl.utils.etree_to_string``. """ message = etree_to_string(envelope) return self.post(address, message, headers) def load(self, url): """Load the content from the given URL""" if not url: raise ValueError("No url given to load") scheme = urlparse(url).scheme if scheme in ("http", "https"): if self.cache: response = self.cache.get(url) if response: return bytes(response) content = self._load_remote_data(url) if self.cache: self.cache.add(url, content) return content elif scheme == "file": if url.startswith("file://"): url = url[7:] with open(os.path.expanduser(url), "rb") as fh: return fh.read() def _load_remote_data(self, url): self.logger.debug("Loading remote data from: %s", url) response = self.session.get(url, timeout=self.load_timeout) response.raise_for_status() return response.content @contextmanager def settings(self, timeout=None): """Context manager to temporarily overrule options. Example:: transport = zeep.Transport() with transport.settings(timeout=10): client.service.fast_call() :param timeout: Set the timeout for POST/GET operations (not used for loading external WSDL or XSD documents) """ old_timeout = self.operation_timeout self.operation_timeout = timeout yield self.operation_timeout = old_timeout
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/src/zeep/transports.py
transports.py
class Error(Exception): def __init__(self, message=""): super(Exception, self).__init__(message) self.message = message def __repr__(self): return "%s(%r)" % (self.__class__.__name__, self.message) class XMLSyntaxError(Error): def __init__(self, *args, **kwargs): self.content = kwargs.pop("content", None) super(XMLSyntaxError, self).__init__(*args, **kwargs) class XMLParseError(Error): def __init__(self, *args, **kwargs): self.filename = kwargs.pop("filename", None) self.sourceline = kwargs.pop("sourceline", None) super(XMLParseError, self).__init__(*args, **kwargs) def __str__(self): location = None if self.filename and self.sourceline: location = "%s:%s" % (self.filename, self.sourceline) if location: return "%s (%s)" % (self.message, location) return self.message class UnexpectedElementError(Error): pass class WsdlSyntaxError(Error): pass class TransportError(Error): def __init__(self, message="", status_code=0, content=None): super(TransportError, self).__init__(message) self.status_code = status_code self.content = content class LookupError(Error): def __init__(self, *args, **kwargs): self.qname = kwargs.pop("qname", None) self.item_name = kwargs.pop("item_name", None) self.location = kwargs.pop("location", None) super(LookupError, self).__init__(*args, **kwargs) class NamespaceError(Error): pass class Fault(Error): def __init__(self, message, code=None, actor=None, detail=None, subcodes=None): super(Fault, self).__init__(message) self.message = message self.code = code self.actor = actor self.detail = detail self.subcodes = subcodes class ZeepWarning(RuntimeWarning): pass class ValidationError(Error): def __init__(self, *args, **kwargs): self.path = kwargs.pop("path", []) super(ValidationError, self).__init__(*args, **kwargs) def __str__(self): if self.path: path = ".".join(str(x) for x in self.path) return "%s (%s)" % (self.message, path) return self.message class SignatureVerificationFailed(Error): pass class IncompleteMessage(Error): pass class IncompleteOperation(Error): pass
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/src/zeep/exceptions.py
exceptions.py
from lxml import etree from zeep.exceptions import IncompleteMessage, LookupError, NamespaceError from zeep.utils import qname_attr from zeep.wsdl import definitions NSMAP = { "wsdl": "http://schemas.xmlsoap.org/wsdl/", "wsaw": "http://www.w3.org/2006/05/addressing/wsdl", "wsam": "http://www.w3.org/2007/05/addressing/metadata", } def parse_abstract_message(wsdl, xmlelement): """Create an AbstractMessage object from a xml element. Definition:: <definitions .... > <message name="nmtoken"> * <part name="nmtoken" element="qname"? type="qname"?/> * </message> </definitions> :param wsdl: The parent definition instance :type wsdl: zeep.wsdl.wsdl.Definition :param xmlelement: The XML node :type xmlelement: lxml.etree._Element :rtype: zeep.wsdl.definitions.AbstractMessage """ tns = wsdl.target_namespace message_name = qname_attr(xmlelement, "name", tns) parts = [] for part in xmlelement.findall("wsdl:part", namespaces=NSMAP): part_name = part.get("name") part_element = qname_attr(part, "element") part_type = qname_attr(part, "type") try: if part_element is not None: part_element = wsdl.types.get_element(part_element) if part_type is not None: part_type = wsdl.types.get_type(part_type) except (NamespaceError, LookupError): raise IncompleteMessage( ( "The wsdl:message for %r contains an invalid part (%r): " "invalid xsd type or elements" ) % (message_name.text, part_name) ) part = definitions.MessagePart(part_element, part_type) parts.append((part_name, part)) # Create the object, add the parts and return it msg = definitions.AbstractMessage(message_name) for part_name, part in parts: msg.add_part(part_name, part) return msg def parse_abstract_operation(wsdl, xmlelement): """Create an AbstractOperation object from a xml element. This is called from the parse_port_type function since the abstract operations are part of the port type element. Definition:: <wsdl:operation name="nmtoken">* <wsdl:documentation .... /> ? <wsdl:input name="nmtoken"? message="qname">? <wsdl:documentation .... /> ? </wsdl:input> <wsdl:output name="nmtoken"? message="qname">? <wsdl:documentation .... /> ? </wsdl:output> <wsdl:fault name="nmtoken" message="qname"> * <wsdl:documentation .... /> ? </wsdl:fault> </wsdl:operation> :param wsdl: The parent definition instance :type wsdl: zeep.wsdl.wsdl.Definition :param xmlelement: The XML node :type xmlelement: lxml.etree._Element :rtype: zeep.wsdl.definitions.AbstractOperation """ name = xmlelement.get("name") kwargs = {"fault_messages": {}} for msg_node in xmlelement: tag_name = etree.QName(msg_node.tag).localname if tag_name not in ("input", "output", "fault"): continue param_msg = qname_attr(msg_node, "message", wsdl.target_namespace) param_name = msg_node.get("name") try: param_value = wsdl.get("messages", param_msg.text) except IndexError: return if tag_name == "input": kwargs["input_message"] = param_value elif tag_name == "output": kwargs["output_message"] = param_value else: kwargs["fault_messages"][param_name] = param_value wsa_action = msg_node.get(etree.QName(NSMAP["wsam"], "Action")) if not wsa_action: wsa_action = msg_node.get(etree.QName(NSMAP["wsaw"], "Action")) param_value.wsa_action = wsa_action kwargs["name"] = name kwargs["parameter_order"] = xmlelement.get("parameterOrder") return definitions.AbstractOperation(**kwargs) def parse_port_type(wsdl, xmlelement): """Create a PortType object from a xml element. Definition:: <wsdl:definitions .... > <wsdl:portType name="nmtoken"> <wsdl:operation name="nmtoken" .... /> * </wsdl:portType> </wsdl:definitions> :param wsdl: The parent definition instance :type wsdl: zeep.wsdl.wsdl.Definition :param xmlelement: The XML node :type xmlelement: lxml.etree._Element :rtype: zeep.wsdl.definitions.PortType """ name = qname_attr(xmlelement, "name", wsdl.target_namespace) operations = {} for elm in xmlelement.findall("wsdl:operation", namespaces=NSMAP): operation = parse_abstract_operation(wsdl, elm) if operation: operations[operation.name] = operation return definitions.PortType(name, operations) def parse_port(wsdl, xmlelement): """Create a Port object from a xml element. This is called via the parse_service function since ports are part of the service xml elements. Definition:: <wsdl:port name="nmtoken" binding="qname"> * <wsdl:documentation .... /> ? <-- extensibility element --> </wsdl:port> :param wsdl: The parent definition instance :type wsdl: zeep.wsdl.wsdl.Definition :param xmlelement: The XML node :type xmlelement: lxml.etree._Element :rtype: zeep.wsdl.definitions.Port """ name = xmlelement.get("name") binding_name = qname_attr(xmlelement, "binding", wsdl.target_namespace) return definitions.Port(name, binding_name=binding_name, xmlelement=xmlelement) def parse_service(wsdl, xmlelement): """ Definition:: <wsdl:service name="nmtoken"> * <wsdl:documentation .... />? <wsdl:port name="nmtoken" binding="qname"> * <wsdl:documentation .... /> ? <-- extensibility element --> </wsdl:port> <-- extensibility element --> </wsdl:service> Example:: <service name="StockQuoteService"> <documentation>My first service</documentation> <port name="StockQuotePort" binding="tns:StockQuoteBinding"> <soap:address location="http://example.com/stockquote"/> </port> </service> :param wsdl: The parent definition instance :type wsdl: zeep.wsdl.wsdl.Definition :param xmlelement: The XML node :type xmlelement: lxml.etree._Element :rtype: zeep.wsdl.definitions.Service """ name = xmlelement.get("name") ports = [] for port_node in xmlelement.findall("wsdl:port", namespaces=NSMAP): port = parse_port(wsdl, port_node) if port: ports.append(port) obj = definitions.Service(name) for port in ports: obj.add_port(port) return obj
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/src/zeep/wsdl/parse.py
parse.py
from __future__ import print_function import logging import operator import os import warnings from collections import OrderedDict import six from lxml import etree from zeep.exceptions import IncompleteMessage from zeep.loader import absolute_location, is_relative_path, load_external from zeep.settings import Settings from zeep.utils import findall_multiple_ns from zeep.wsdl import parse from zeep.xsd import Schema NSMAP = {"wsdl": "http://schemas.xmlsoap.org/wsdl/"} logger = logging.getLogger(__name__) class Document(object): """A WSDL Document exists out of one or more definitions. There is always one 'root' definition which should be passed as the location to the Document. This definition can import other definitions. These imports are non-transitive, only the definitions defined in the imported document are available in the parent definition. This Document is mostly just a simple interface to the root definition. After all definitions are loaded the definitions are resolved. This resolves references which were not yet available during the initial parsing phase. :param location: Location of this WSDL :type location: string :param transport: The transport object to be used :type transport: zeep.transports.Transport :param base: The base location of this document :type base: str :param strict: Indicates if strict mode is enabled :type strict: bool """ def __init__(self, location, transport, base=None, settings=None): """Initialize a WSDL document. The root definition properties are exposed as entry points. """ self.settings = settings or Settings() if isinstance(location, six.string_types): if is_relative_path(location): location = os.path.abspath(location) self.location = location else: self.location = base self.transport = transport # Dict with all definition objects within this WSDL self._definitions = {} self.types = Schema( node=None, transport=self.transport, location=self.location, settings=self.settings, ) document = self._get_xml_document(location) root_definitions = Definition(self, document, self.location) root_definitions.resolve_imports() # Make the wsdl definitions public self.messages = root_definitions.messages self.port_types = root_definitions.port_types self.bindings = root_definitions.bindings self.services = root_definitions.services def __repr__(self): return "<WSDL(location=%r)>" % self.location def dump(self): print("") print("Prefixes:") for prefix, namespace in self.types.prefix_map.items(): print(" " * 4, "%s: %s" % (prefix, namespace)) print("") print("Global elements:") for elm_obj in sorted(self.types.elements, key=lambda k: k.qname): value = elm_obj.signature(schema=self.types) print(" " * 4, value) print("") print("Global types:") for type_obj in sorted(self.types.types, key=lambda k: k.qname or ""): value = type_obj.signature(schema=self.types) print(" " * 4, value) print("") print("Bindings:") for binding_obj in sorted( self.bindings.values(), key=lambda k: six.text_type(k) ): print(" " * 4, six.text_type(binding_obj)) print("") for service in self.services.values(): print(six.text_type(service)) for port in service.ports.values(): print(" " * 4, six.text_type(port)) print(" " * 8, "Operations:") operations = sorted( port.binding._operations.values(), key=operator.attrgetter("name") ) for operation in operations: print("%s%s" % (" " * 12, six.text_type(operation))) print("") def _get_xml_document(self, location): """Load the XML content from the given location and return an lxml.Element object. :param location: The URL of the document to load :type location: string """ return load_external( location, self.transport, self.location, settings=self.settings ) def _add_definition(self, definition): key = (definition.target_namespace, definition.location) self._definitions[key] = definition class Definition(object): """The Definition represents one wsdl:definition within a Document. :param wsdl: The wsdl """ def __init__(self, wsdl, doc, location): """fo :param wsdl: The wsdl """ logger.debug("Creating definition for %s", location) self.wsdl = wsdl self.location = location self.types = wsdl.types self.port_types = {} self.messages = {} self.bindings = {} self.services = OrderedDict() self.imports = {} self._resolved_imports = False self.target_namespace = doc.get("targetNamespace") self.wsdl._add_definition(self) self.nsmap = doc.nsmap # Process the definitions self.parse_imports(doc) self.parse_types(doc) self.messages = self.parse_messages(doc) self.port_types = self.parse_ports(doc) self.bindings = self.parse_binding(doc) self.services = self.parse_service(doc) def __repr__(self): return "<Definition(location=%r)>" % self.location def get(self, name, key, _processed=None): container = getattr(self, name) if key in container: return container[key] # Turns out that no one knows if the wsdl import statement is # transitive or not. WSDL/SOAP specs are awesome... So lets just do it. # TODO: refactor me into something more sane _processed = _processed or set() if self.target_namespace not in _processed: _processed.add(self.target_namespace) for definition in self.imports.values(): try: return definition.get(name, key, _processed) except IndexError: # Try to see if there is an item which has no namespace # but where the localname matches. This is basically for # #356 but in the future we should also ignore mismatching # namespaces as last fallback fallback_key = etree.QName(key).localname try: return definition.get(name, fallback_key, _processed) except IndexError: pass raise IndexError("No definition %r in %r found" % (key, name)) def resolve_imports(self): """Resolve all root elements (types, messages, etc).""" # Simple guard to protect against cyclic imports if self._resolved_imports: return self._resolved_imports = True for definition in self.imports.values(): definition.resolve_imports() for message in self.messages.values(): message.resolve(self) for port_type in self.port_types.values(): port_type.resolve(self) for binding in self.bindings.values(): binding.resolve(self) for service in self.services.values(): service.resolve(self) def parse_imports(self, doc): """Import other WSDL definitions in this document. Note that imports are non-transitive, so only import definitions which are defined in the imported document and ignore definitions imported in that document. This should handle recursive imports though: A -> B -> A A -> B -> C -> A :param doc: The source document :type doc: lxml.etree._Element """ for import_node in doc.findall("wsdl:import", namespaces=NSMAP): namespace = import_node.get("namespace") location = import_node.get("location") if not location: logger.debug( "Skipping import for namespace %s (empty location)", namespace ) continue location = absolute_location(location, self.location) key = (namespace, location) if key in self.wsdl._definitions: self.imports[key] = self.wsdl._definitions[key] else: document = self.wsdl._get_xml_document(location) if etree.QName(document.tag).localname == "schema": self.types.add_documents([document], location) else: wsdl = Definition(self.wsdl, document, location) self.imports[key] = wsdl def parse_types(self, doc): """Return an xsd.Schema() instance for the given wsdl:types element. If the wsdl:types contain multiple schema definitions then a new wrapping xsd.Schema is defined with xsd:import statements linking them together. If the wsdl:types doesn't container an xml schema then an empty schema is returned instead. Definition:: <definitions .... > <types> <xsd:schema .... />* </types> </definitions> :param doc: The source document :type doc: lxml.etree._Element """ namespace_sets = [ { "xsd": "http://www.w3.org/2001/XMLSchema", "wsdl": "http://schemas.xmlsoap.org/wsdl/", }, { "xsd": "http://www.w3.org/1999/XMLSchema", "wsdl": "http://schemas.xmlsoap.org/wsdl/", }, ] # Find xsd:schema elements (wsdl:types/xsd:schema) schema_nodes = findall_multiple_ns(doc, "wsdl:types/xsd:schema", namespace_sets) self.types.add_documents(schema_nodes, self.location) def parse_messages(self, doc): """ Definition:: <definitions .... > <message name="nmtoken"> * <part name="nmtoken" element="qname"? type="qname"?/> * </message> </definitions> :param doc: The source document :type doc: lxml.etree._Element """ result = {} for msg_node in doc.findall("wsdl:message", namespaces=NSMAP): try: msg = parse.parse_abstract_message(self, msg_node) except IncompleteMessage as exc: warnings.warn(str(exc)) else: result[msg.name.text] = msg logger.debug("Adding message: %s", msg.name.text) return result def parse_ports(self, doc): """Return dict with `PortType` instances as values Definition:: <wsdl:definitions .... > <wsdl:portType name="nmtoken"> <wsdl:operation name="nmtoken" .... /> * </wsdl:portType> </wsdl:definitions> :param doc: The source document :type doc: lxml.etree._Element """ result = {} for port_node in doc.findall("wsdl:portType", namespaces=NSMAP): port_type = parse.parse_port_type(self, port_node) result[port_type.name.text] = port_type logger.debug("Adding port: %s", port_type.name.text) return result def parse_binding(self, doc): """Parse the binding elements and return a dict of bindings. Currently supported bindings are Soap 1.1, Soap 1.2., HTTP Get and HTTP Post. The detection of the type of bindings is done by the bindings themselves using the introspection of the xml nodes. Definition:: <wsdl:definitions .... > <wsdl:binding name="nmtoken" type="qname"> * <-- extensibility element (1) --> * <wsdl:operation name="nmtoken"> * <-- extensibility element (2) --> * <wsdl:input name="nmtoken"? > ? <-- extensibility element (3) --> </wsdl:input> <wsdl:output name="nmtoken"? > ? <-- extensibility element (4) --> * </wsdl:output> <wsdl:fault name="nmtoken"> * <-- extensibility element (5) --> * </wsdl:fault> </wsdl:operation> </wsdl:binding> </wsdl:definitions> :param doc: The source document :type doc: lxml.etree._Element :returns: Dictionary with binding name as key and Binding instance as value :rtype: dict """ result = {} if not getattr(self.wsdl.transport, "binding_classes", None): from zeep.wsdl import bindings binding_classes = [ bindings.Soap11Binding, bindings.Soap12Binding, bindings.HttpGetBinding, bindings.HttpPostBinding, ] else: binding_classes = self.wsdl.transport.binding_classes for binding_node in doc.findall("wsdl:binding", namespaces=NSMAP): # Detect the binding type binding = None for binding_class in binding_classes: if binding_class.match(binding_node): try: binding = binding_class.parse(self, binding_node) except NotImplementedError as exc: logger.debug("Ignoring binding: %s", exc) continue logger.debug("Adding binding: %s", binding.name.text) result[binding.name.text] = binding break return result def parse_service(self, doc): """ Definition:: <wsdl:definitions .... > <wsdl:service .... > * <wsdl:port name="nmtoken" binding="qname"> * <-- extensibility element (1) --> </wsdl:port> </wsdl:service> </wsdl:definitions> :param doc: The source document :type doc: lxml.etree._Element """ result = OrderedDict() for service_node in doc.findall("wsdl:service", namespaces=NSMAP): service = parse.parse_service(self, service_node) result[service.name] = service logger.debug("Adding service: %s", service.name) return result
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/src/zeep/wsdl/wsdl.py
wsdl.py
import warnings from collections import OrderedDict, namedtuple from six import python_2_unicode_compatible from zeep.exceptions import IncompleteOperation MessagePart = namedtuple("MessagePart", ["element", "type"]) class AbstractMessage(object): """Messages consist of one or more logical parts. Each part is associated with a type from some type system using a message-typing attribute. The set of message-typing attributes is extensible. WSDL defines several such message-typing attributes for use with XSD: - element: Refers to an XSD element using a QName. - type: Refers to an XSD simpleType or complexType using a QName. """ def __init__(self, name): self.name = name self.parts = OrderedDict() def __repr__(self): return "<%s(name=%r)>" % (self.__class__.__name__, self.name.text) def resolve(self, definitions): pass def add_part(self, name, element): self.parts[name] = element class AbstractOperation(object): """Abstract operations are defined in the wsdl's portType elements.""" def __init__( self, name, input_message=None, output_message=None, fault_messages=None, parameter_order=None, ): """Initialize the abstract operation. :param name: The name of the operation :type name: str :param input_message: Message to generate the request XML :type input_message: AbstractMessage :param output_message: Message to process the response XML :type output_message: AbstractMessage :param fault_messages: Dict of messages to handle faults :type fault_messages: dict of str: AbstractMessage """ self.name = name self.input_message = input_message self.output_message = output_message self.fault_messages = fault_messages self.parameter_order = parameter_order class PortType(object): def __init__(self, name, operations): self.name = name self.operations = operations def __repr__(self): return "<%s(name=%r)>" % (self.__class__.__name__, self.name.text) def resolve(self, definitions): pass @python_2_unicode_compatible class Binding(object): """Base class for the various bindings (SoapBinding / HttpBinding) .. raw:: ascii Binding | +-> Operation | +-> ConcreteMessage | +-> AbstractMessage """ def __init__(self, wsdl, name, port_name): """Binding :param wsdl: :type wsdl: :param name: :type name: string :param port_name: :type port_name: string """ self.name = name self.port_name = port_name self.port_type = None self.wsdl = wsdl self._operations = {} def resolve(self, definitions): self.port_type = definitions.get("port_types", self.port_name.text) for name, operation in list(self._operations.items()): try: operation.resolve(definitions) except IncompleteOperation as exc: warnings.warn(str(exc)) del self._operations[name] def _operation_add(self, operation): # XXX: operation name is not unique self._operations[operation.name] = operation def __str__(self): return "%s: %s" % (self.__class__.__name__, self.name.text) def __repr__(self): return "<%s(name=%r, port_type=%r)>" % ( self.__class__.__name__, self.name.text, self.port_type, ) def all(self): return self._operations def get(self, key): try: return self._operations[key] except KeyError: raise ValueError("No such operation %r on %s" % (key, self.name)) @classmethod def match(cls, node): raise NotImplementedError() @classmethod def parse(cls, definitions, xmlelement): raise NotImplementedError() @python_2_unicode_compatible class Operation(object): """Concrete operation Contains references to the concrete messages """ def __init__(self, name, binding): self.name = name self.binding = binding self.abstract = None self.style = None self.input = None self.output = None self.faults = {} def resolve(self, definitions): try: self.abstract = self.binding.port_type.operations[self.name] except KeyError: raise IncompleteOperation( "The wsdl:operation %r was not found in the wsdl:portType %r" % (self.name, self.binding.port_type.name.text) ) def __repr__(self): return "<%s(name=%r, style=%r)>" % ( self.__class__.__name__, self.name, self.style, ) def __str__(self): if not self.input: return u"%s(missing input message)" % (self.name) retval = u"%s(%s)" % (self.name, self.input.signature()) if self.output: retval += u" -> %s" % (self.output.signature(as_output=True)) return retval def create(self, *args, **kwargs): return self.input.serialize(*args, **kwargs) def process_reply(self, envelope): raise NotImplementedError() @classmethod def parse(cls, wsdl, xmlelement, binding): """ Definition:: <wsdl:operation name="nmtoken"> * <-- extensibility element (2) --> * <wsdl:input name="nmtoken"? > ? <-- extensibility element (3) --> </wsdl:input> <wsdl:output name="nmtoken"? > ? <-- extensibility element (4) --> * </wsdl:output> <wsdl:fault name="nmtoken"> * <-- extensibility element (5) --> * </wsdl:fault> </wsdl:operation> """ raise NotImplementedError() @python_2_unicode_compatible class Port(object): """Specifies an address for a binding, thus defining a single communication endpoint. """ def __init__(self, name, binding_name, xmlelement): self.name = name self._resolve_context = {"binding_name": binding_name, "xmlelement": xmlelement} # Set during resolve() self.binding = None self.binding_options = {} def __repr__(self): return "<%s(name=%r, binding=%r, %r)>" % ( self.__class__.__name__, self.name, self.binding, self.binding_options, ) def __str__(self): return u"Port: %s (%s)" % (self.name, self.binding) def resolve(self, definitions): if self._resolve_context is None: return try: self.binding = definitions.get( "bindings", self._resolve_context["binding_name"].text ) except IndexError: return False if definitions.location and self.binding.wsdl.settings.force_https: force_https = definitions.location.startswith("https") else: force_https = False self.binding_options = self.binding.process_service_port( self._resolve_context["xmlelement"], force_https ) self._resolve_context = None return True @python_2_unicode_compatible class Service(object): """Used to aggregate a set of related ports. """ def __init__(self, name): self.ports = OrderedDict() self.name = name self._is_resolved = False def __str__(self): return u"Service: %s" % self.name def __repr__(self): return "<%s(name=%r, ports=%r)>" % ( self.__class__.__name__, self.name, self.ports, ) def resolve(self, definitions): if self._is_resolved: return unresolved = [] for name, port in self.ports.items(): is_resolved = port.resolve(definitions) if not is_resolved: unresolved.append(name) # Remove unresolved bindings (http etc) for name in unresolved: del self.ports[name] self._is_resolved = True def add_port(self, port): self.ports[port.name] = port
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/src/zeep/wsdl/definitions.py
definitions.py
import base64 from cached_property import cached_property from requests.structures import CaseInsensitiveDict class MessagePack(object): def __init__(self, parts): self._parts = parts def __repr__(self): return "<MessagePack(attachments=[%s])>" % ( ", ".join(repr(a) for a in self.attachments) ) @property def root(self): return self._root def _set_root(self, root): self._root = root @cached_property def attachments(self): """Return a list of attachments. :rtype: list of Attachment """ return [Attachment(part) for part in self._parts] def get_by_content_id(self, content_id): """get_by_content_id :param content_id: The content-id to return :type content_id: str :rtype: Attachment """ for attachment in self.attachments: if attachment.content_id == content_id: return attachment class Attachment(object): def __init__(self, part): encoding = part.encoding or "utf-8" self.headers = CaseInsensitiveDict( {k.decode(encoding): v.decode(encoding) for k, v in part.headers.items()} ) self.content_type = self.headers.get("Content-Type", None) self.content_id = self.headers.get("Content-ID", None) self.content_location = self.headers.get("Content-Location", None) self._part = part def __repr__(self): return "<Attachment(%r, %r)>" % (self.content_id, self.content_type) @cached_property def content(self): """Return the content of the attachment :rtype: bytes or str """ encoding = self.headers.get("Content-Transfer-Encoding", None) content = self._part.content if encoding == "base64": return base64.b64decode(content) elif encoding == "binary": return content.strip(b"\r\n") else: return content
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/src/zeep/wsdl/attachments.py
attachments.py
import six from defusedxml.lxml import fromstring from lxml import etree from zeep import ns, xsd from zeep.helpers import serialize_object from zeep.wsdl.messages.base import ConcreteMessage, SerializedMessage from zeep.wsdl.utils import etree_to_string __all__ = ["MimeContent", "MimeXML", "MimeMultipart"] class MimeMessage(ConcreteMessage): _nsmap = {"mime": ns.MIME} def __init__(self, wsdl, name, operation, part_name): super(MimeMessage, self).__init__(wsdl, name, operation) self.part_name = part_name def resolve(self, definitions, abstract_message): """Resolve the body element The specs are (again) not really clear how to handle the message parts in relation the message element vs type. The following strategy is chosen, which seem to work: - If the message part has a name and it maches then set it as body - If the message part has a name but it doesn't match but there are no other message parts, then just use that one. - If the message part has no name then handle it like an rpc call, in other words, each part is an argument. """ self.abstract = abstract_message if self.part_name and self.abstract.parts: if self.part_name in self.abstract.parts: message = self.abstract.parts[self.part_name] elif len(self.abstract.parts) == 1: message = list(self.abstract.parts.values())[0] else: raise ValueError( "Multiple parts for message %r while no matching part found" % self.part_name ) if message.element: self.body = message.element else: elm = xsd.Element(self.part_name, message.type) self.body = xsd.Element( self.operation.name, xsd.ComplexType(xsd.Sequence([elm])) ) else: children = [] for name, message in self.abstract.parts.items(): if message.element: elm = message.element.clone(name) else: elm = xsd.Element(name, message.type) children.append(elm) self.body = xsd.Element( self.operation.name, xsd.ComplexType(xsd.Sequence(children)) ) class MimeContent(MimeMessage): """WSDL includes a way to bind abstract types to concrete messages in some MIME format. Bindings for the following MIME types are defined: - multipart/related - text/xml - application/x-www-form-urlencoded - Others (by specifying the MIME type string) The set of defined MIME types is both large and evolving, so it is not a goal for WSDL to exhaustively define XML grammar for each MIME type. :param wsdl: The main wsdl document :type wsdl: zeep.wsdl.wsdl.Document :param name: :param operation: The operation to which this message belongs :type operation: zeep.wsdl.bindings.soap.SoapOperation :param part_name: :type type: str """ def __init__(self, wsdl, name, operation, content_type, part_name): super(MimeContent, self).__init__(wsdl, name, operation, part_name) self.content_type = content_type def serialize(self, *args, **kwargs): value = self.body(*args, **kwargs) headers = {"Content-Type": self.content_type} data = "" if self.content_type == "application/x-www-form-urlencoded": items = serialize_object(value) data = six.moves.urllib.parse.urlencode(items) elif self.content_type == "text/xml": document = etree.Element("root") self.body.render(document, value) data = etree_to_string(list(document)[0]) return SerializedMessage( path=self.operation.location, headers=headers, content=data ) def deserialize(self, node): node = fromstring(node) part = list(self.abstract.parts.values())[0] return part.type.parse_xmlelement(node) @classmethod def parse(cls, definitions, xmlelement, operation): name = xmlelement.get("name") part_name = content_type = None content_node = xmlelement.find("mime:content", namespaces=cls._nsmap) if content_node is not None: content_type = content_node.get("type") part_name = content_node.get("part") obj = cls(definitions.wsdl, name, operation, content_type, part_name) return obj class MimeXML(MimeMessage): """To specify XML payloads that are not SOAP compliant (do not have a SOAP Envelope), but do have a particular schema, the mime:mimeXml element may be used to specify that concrete schema. The part attribute refers to a message part defining the concrete schema of the root XML element. The part attribute MAY be omitted if the message has only a single part. The part references a concrete schema using the element attribute for simple parts or type attribute for composite parts :param wsdl: The main wsdl document :type wsdl: zeep.wsdl.wsdl.Document :param name: :param operation: The operation to which this message belongs :type operation: zeep.wsdl.bindings.soap.SoapOperation :param part_name: :type type: str """ def serialize(self, *args, **kwargs): raise NotImplementedError() def deserialize(self, node): node = fromstring(node) part = next(iter(self.abstract.parts.values()), None) return part.element.parse(node, self.wsdl.types) @classmethod def parse(cls, definitions, xmlelement, operation): name = xmlelement.get("name") part_name = None content_node = xmlelement.find("mime:mimeXml", namespaces=cls._nsmap) if content_node is not None: part_name = content_node.get("part") obj = cls(definitions.wsdl, name, operation, part_name) return obj class MimeMultipart(MimeMessage): """The multipart/related MIME type aggregates an arbitrary set of MIME formatted parts into one message using the MIME type "multipart/related". The mime:multipartRelated element describes the concrete format of such a message:: <mime:multipartRelated> <mime:part> * <-- mime element --> </mime:part> </mime:multipartRelated> The mime:part element describes each part of a multipart/related message. MIME elements appear within mime:part to specify the concrete MIME type for the part. If more than one MIME element appears inside a mime:part, they are alternatives. :param wsdl: The main wsdl document :type wsdl: zeep.wsdl.wsdl.Document :param name: :param operation: The operation to which this message belongs :type operation: zeep.wsdl.bindings.soap.SoapOperation :param part_name: :type type: str """ pass
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/src/zeep/wsdl/messages/mime.py
mime.py
import copy from collections import OrderedDict from lxml import etree from lxml.builder import ElementMaker from zeep import exceptions, xsd from zeep.utils import as_qname from zeep.wsdl.messages.base import ConcreteMessage, SerializedMessage from zeep.wsdl.messages.multiref import process_multiref from zeep.xsd.context import XmlParserContext __all__ = ["DocumentMessage", "RpcMessage"] class SoapMessage(ConcreteMessage): """Base class for the SOAP Document and RPC messages :param wsdl: The main wsdl document :type wsdl: zeep.wsdl.Document :param name: :param operation: The operation to which this message belongs :type operation: zeep.wsdl.bindings.soap.SoapOperation :param type: 'input' or 'output' :type type: str :param nsmap: The namespace mapping :type nsmap: dict """ def __init__(self, wsdl, name, operation, type, nsmap): super(SoapMessage, self).__init__(wsdl, name, operation) self.nsmap = nsmap self.abstract = None # Set during resolve() self.type = type self._is_body_wrapped = False self.body = None self.header = None self.envelope = None def serialize(self, *args, **kwargs): """Create a SerializedMessage for this message""" nsmap = {"soap-env": self.nsmap["soap-env"]} nsmap.update(self.wsdl.types._prefix_map_custom) soap = ElementMaker(namespace=self.nsmap["soap-env"], nsmap=nsmap) # Create the soap:envelope envelope = soap.Envelope() # Create the soap:header element headers_value = kwargs.pop("_soapheaders", None) header = self._serialize_header(headers_value, nsmap) if header is not None: envelope.append(header) # Create the soap:body element. The _is_body_wrapped attribute signals # that the self.body element is of type soap:body, so we don't have to # create it in that case. Otherwise we create a Element soap:body and # render the content into this. if self.body: body_value = self.body(*args, **kwargs) if self._is_body_wrapped: self.body.render(envelope, body_value) else: body = soap.Body() envelope.append(body) self.body.render(body, body_value) else: body = soap.Body() envelope.append(body) # XXX: This is only used in Soap 1.1 so should be moved to the the # Soap11Binding._set_http_headers(). But let's keep it like this for # now. headers = {"SOAPAction": '"%s"' % self.operation.soapaction} return SerializedMessage(path=None, headers=headers, content=envelope) def deserialize(self, envelope): """Deserialize the SOAP:Envelope and return a CompoundValue with the result. """ if not self.envelope: return None body = envelope.find("soap-env:Body", namespaces=self.nsmap) body_result = self._deserialize_body(body) header = envelope.find("soap-env:Header", namespaces=self.nsmap) headers_result = self._deserialize_headers(header) kwargs = body_result kwargs.update(headers_result) result = self.envelope(**kwargs) # If the message if self.header.type._element: return result result = result.body if result is None or len(result) == 0: return None elif len(result) > 1: return result # Check if we can remove the wrapping object to make the return value # easier to use. result = next(iter(result.__values__.values())) if isinstance(result, xsd.CompoundValue): children = result._xsd_type.elements attributes = result._xsd_type.attributes if len(children) == 1 and len(attributes) == 0: item_name, item_element = children[0] retval = getattr(result, item_name) return retval return result def signature(self, as_output=False): if not self.envelope: return None if as_output: if isinstance(self.envelope.type, xsd.ComplexType): try: if len(self.envelope.type.elements) == 1: return self.envelope.type.elements[0][1].type.signature( schema=self.wsdl.types, standalone=False ) except AttributeError: return None return self.envelope.type.signature( schema=self.wsdl.types, standalone=False ) if self.body: parts = [self.body.type.signature(schema=self.wsdl.types, standalone=False)] else: parts = [] if self.header.type._element: parts.append( "_soapheaders={%s}" % self.header.type.signature(schema=self.wsdl.types, standalone=False) ) return ", ".join(part for part in parts if part) @classmethod def parse(cls, definitions, xmlelement, operation, type, nsmap): """Parse a wsdl:binding/wsdl:operation/wsdl:operation for the SOAP implementation. Each wsdl:operation can contain three child nodes: - input - output - fault Definition for input/output:: <input> <soap:body parts="nmtokens"? use="literal|encoded" encodingStyle="uri-list"? namespace="uri"?> <soap:header message="qname" part="nmtoken" use="literal|encoded" encodingStyle="uri-list"? namespace="uri"?>* <soap:headerfault message="qname" part="nmtoken" use="literal|encoded" encodingStyle="uri-list"? namespace="uri"?/>* </soap:header> </input> And the definition for fault:: <soap:fault name="nmtoken" use="literal|encoded" encodingStyle="uri-list"? namespace="uri"?> """ name = xmlelement.get("name") obj = cls(definitions.wsdl, name, operation, nsmap=nsmap, type=type) body_data = None header_data = None # After some profiling it turns out that .find() and .findall() in this # case are twice as fast as the xpath method body = xmlelement.find("soap:body", namespaces=operation.binding.nsmap) if body is not None: body_data = cls._parse_body(body) # Parse soap:header (multiple) elements = xmlelement.findall("soap:header", namespaces=operation.binding.nsmap) header_data = cls._parse_header( elements, definitions.target_namespace, operation ) obj._resolve_info = {"body": body_data, "header": header_data} return obj @classmethod def _parse_body(cls, xmlelement): """Parse soap:body and return a dict with data to resolve it. <soap:body parts="nmtokens"? use="literal|encoded"? encodingStyle="uri-list"? namespace="uri"?> """ return { "part": xmlelement.get("part"), "use": xmlelement.get("use", "literal"), "encodingStyle": xmlelement.get("encodingStyle"), "namespace": xmlelement.get("namespace"), } @classmethod def _parse_header(cls, xmlelements, tns, operation): """Parse the soap:header and optionally included soap:headerfault elements <soap:header message="qname" part="nmtoken" use="literal|encoded" encodingStyle="uri-list"? namespace="uri"? />* The header can optionally contain one ore more soap:headerfault elements which can contain the same attributes as the soap:header:: <soap:headerfault message="qname" part="nmtoken" use="literal|encoded" encodingStyle="uri-list"? namespace="uri"?/>* """ result = [] for xmlelement in xmlelements: data = cls._parse_header_element(xmlelement, tns) # Add optional soap:headerfault elements data["faults"] = [] fault_elements = xmlelement.findall( "soap:headerfault", namespaces=operation.binding.nsmap ) for fault_element in fault_elements: fault_data = cls._parse_header_element(fault_element, tns) data["faults"].append(fault_data) result.append(data) return result @classmethod def _parse_header_element(cls, xmlelement, tns): attributes = xmlelement.attrib message_qname = as_qname(attributes["message"], xmlelement.nsmap, tns) try: return { "message": message_qname, "part": attributes["part"], "use": attributes["use"], "encodingStyle": attributes.get("encodingStyle"), "namespace": attributes.get("namespace"), } except KeyError: raise exceptions.WsdlSyntaxError("Invalid soap:header(fault)") def resolve(self, definitions, abstract_message): """Resolve the data in the self._resolve_info dict (set via parse()) This creates three xsd.Element objects: - self.header - self.body - self.envelope (combination of headers and body) XXX headerfaults are not implemented yet. """ info = self._resolve_info del self._resolve_info # If this message has no parts then we have nothing to do. This might # happen for output messages which don't return anything. if ( abstract_message is None or not abstract_message.parts ) and self.type != "input": return self.abstract = abstract_message parts = OrderedDict(self.abstract.parts) self.header = self._resolve_header(info["header"], definitions, parts) self.body = self._resolve_body(info["body"], definitions, parts) self.envelope = self._create_envelope_element() def _create_envelope_element(self): """Create combined `envelope` complexType which contains both the elements from the body and the headers. """ all_elements = xsd.Sequence([]) if self.header.type._element: all_elements.append( xsd.Element("{%s}header" % self.nsmap["soap-env"], self.header.type) ) all_elements.append( xsd.Element( "{%s}body" % self.nsmap["soap-env"], self.body.type if self.body else None, ) ) return xsd.Element( "{%s}envelope" % self.nsmap["soap-env"], xsd.ComplexType(all_elements) ) def _serialize_header(self, headers_value, nsmap): if not headers_value: return headers_value = copy.deepcopy(headers_value) soap = ElementMaker(namespace=self.nsmap["soap-env"], nsmap=nsmap) header = soap.Header() if isinstance(headers_value, list): for header_value in headers_value: if hasattr(header_value, "_xsd_elm"): header_value._xsd_elm.render(header, header_value) elif hasattr(header_value, "_xsd_type"): header_value._xsd_type.render(header, header_value) elif isinstance(header_value, etree._Element): header.append(header_value) else: raise ValueError("Invalid value given to _soapheaders") elif isinstance(headers_value, dict): if not self.header: raise ValueError( "_soapheaders only accepts a dictionary if the wsdl " "defines the headers." ) # Only render headers for which we have a value headers_value = self.header(**headers_value) for name, elm in self.header.type.elements: if name in headers_value and headers_value[name] is not None: elm.render(header, headers_value[name], ["header", name]) else: raise ValueError("Invalid value given to _soapheaders") return header def _deserialize_headers(self, xmlelement): """Deserialize the values in the SOAP:Header element""" if not self.header or xmlelement is None: return {} context = XmlParserContext(settings=self.wsdl.settings) result = self.header.parse(xmlelement, self.wsdl.types, context=context) if result is not None: return {"header": result} return {} def _resolve_header(self, info, definitions, parts): name = etree.QName(self.nsmap["soap-env"], "Header") container = xsd.All(consume_other=True) if not info: return xsd.Element(name, xsd.ComplexType(container)) for item in info: message_name = item["message"].text part_name = item["part"] message = definitions.get("messages", message_name) if message == self.abstract and part_name in parts: del parts[part_name] part = message.parts[part_name] if part.element: element = part.element.clone() element.attr_name = part_name else: element = xsd.Element(part_name, part.type) container.append(element) return xsd.Element(name, xsd.ComplexType(container)) class DocumentMessage(SoapMessage): """In the document message there are no additional wrappers, and the message parts appear directly under the SOAP Body element. .. inheritance-diagram:: zeep.wsdl.messages.soap.DocumentMessage :parts: 1 :param wsdl: The main wsdl document :type wsdl: zeep.wsdl.Document :param name: :param operation: The operation to which this message belongs :type operation: zeep.wsdl.bindings.soap.SoapOperation :param type: 'input' or 'output' :type type: str :param nsmap: The namespace mapping :type nsmap: dict """ def __init__(self, *args, **kwargs): super(DocumentMessage, self).__init__(*args, **kwargs) def _deserialize_body(self, xmlelement): if not self._is_body_wrapped: # TODO: For now we assume that the body only has one child since # only one part is specified in the wsdl. This should be handled # way better xmlelement = list(xmlelement)[0] context = XmlParserContext(settings=self.wsdl.settings) result = self.body.parse(xmlelement, self.wsdl.types, context=context) return {"body": result} def _resolve_body(self, info, definitions, parts): name = etree.QName(self.nsmap["soap-env"], "Body") if not info or not parts: return None # If the part name is omitted then all parts are available under # the soap:body tag. Otherwise only the part with the given name. if info["part"]: part_name = info["part"] sub_elements = [parts[part_name].element] else: sub_elements = [] for part_name, part in parts.items(): element = part.element.clone() element.attr_name = part_name or element.name sub_elements.append(element) if len(sub_elements) > 1: self._is_body_wrapped = True return xsd.Element(name, xsd.ComplexType(xsd.All(sub_elements))) else: self._is_body_wrapped = False return sub_elements[0] class RpcMessage(SoapMessage): """In RPC messages each part is a parameter or a return value and appears inside a wrapper element within the body. The wrapper element is named identically to the operation name and its namespace is the value of the namespace attribute. Each message part (parameter) appears under the wrapper, represented by an accessor named identically to the corresponding parameter of the call. Parts are arranged in the same order as the parameters of the call. .. inheritance-diagram:: zeep.wsdl.messages.soap.DocumentMessage :parts: 1 :param wsdl: The main wsdl document :type wsdl: zeep.wsdl.Document :param name: :param operation: The operation to which this message belongs :type operation: zeep.wsdl.bindings.soap.SoapOperation :param type: 'input' or 'output' :type type: str :param nsmap: The namespace mapping :type nsmap: dict """ def _resolve_body(self, info, definitions, parts): """Return an XSD element for the SOAP:Body. Each part is a parameter or a return value and appears inside a wrapper element within the body named identically to the operation name and its namespace is the value of the namespace attribute. """ if not info: return None namespace = info["namespace"] if self.type == "input": tag_name = etree.QName(namespace, self.operation.name) else: tag_name = etree.QName(namespace, self.abstract.name.localname) # Create the xsd element to create/parse the response. Each part # is a sub element of the root node (which uses the operation name) elements = [] for name, msg in parts.items(): if msg.element: elements.append(msg.element) else: elements.append(xsd.Element(name, msg.type)) return xsd.Element(tag_name, xsd.ComplexType(xsd.Sequence(elements))) def _deserialize_body(self, body_element): """The name of the wrapper element is not defined. The WS-I defines that it should be the operation name with the 'Response' string as suffix. But lets just do it really stupid for now and use the first element. """ process_multiref(body_element) response_element = list(body_element)[0] if self.body: context = XmlParserContext(self.wsdl.settings) result = self.body.parse(response_element, self.wsdl.types, context=context) return {"body": result} return {"body": None}
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/src/zeep/wsdl/messages/soap.py
soap.py
from zeep import xsd from zeep.wsdl.messages.base import ConcreteMessage, SerializedMessage __all__ = ["UrlEncoded", "UrlReplacement"] class HttpMessage(ConcreteMessage): """Base class for HTTP Binding messages""" def resolve(self, definitions, abstract_message): self.abstract = abstract_message children = [] for name, message in self.abstract.parts.items(): if message.element: elm = message.element.clone(name) else: elm = xsd.Element(name, message.type) children.append(elm) self.body = xsd.Element( self.operation.name, xsd.ComplexType(xsd.Sequence(children)) ) class UrlEncoded(HttpMessage): """The urlEncoded element indicates that all the message parts are encoded into the HTTP request URI using the standard URI-encoding rules (name1=value&name2=value...). The names of the parameters correspond to the names of the message parts. Each value contributed by the part is encoded using a name=value pair. This may be used with GET to specify URL encoding, or with POST to specify a FORM-POST. For GET, the "?" character is automatically appended as necessary. """ def serialize(self, *args, **kwargs): params = {key: None for key in self.abstract.parts.keys()} params.update(zip(self.abstract.parts.keys(), args)) params.update(kwargs) headers = {"Content-Type": "text/xml; charset=utf-8"} return SerializedMessage( path=self.operation.location, headers=headers, content=params ) @classmethod def parse(cls, definitions, xmlelement, operation): name = xmlelement.get("name") obj = cls(definitions.wsdl, name, operation) return obj class UrlReplacement(HttpMessage): """The http:urlReplacement element indicates that all the message parts are encoded into the HTTP request URI using a replacement algorithm. - The relative URI value of http:operation is searched for a set of search patterns. - The search occurs before the value of the http:operation is combined with the value of the location attribute from http:address. - There is one search pattern for each message part. The search pattern string is the name of the message part surrounded with parenthesis "(" and ")". - For each match, the value of the corresponding message part is substituted for the match at the location of the match. - Matches are performed before any values are replaced (replaced values do not trigger additional matches). Message parts MUST NOT have repeating values. <http:urlReplacement/> """ def serialize(self, *args, **kwargs): params = {key: None for key in self.abstract.parts.keys()} params.update(zip(self.abstract.parts.keys(), args)) params.update(kwargs) headers = {"Content-Type": "text/xml; charset=utf-8"} path = self.operation.location for key, value in params.items(): path = path.replace("(%s)" % key, value if value is not None else "") return SerializedMessage(path=path, headers=headers, content="") @classmethod def parse(cls, definitions, xmlelement, operation): name = xmlelement.get("name") obj = cls(definitions.wsdl, name, operation) return obj
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/src/zeep/wsdl/messages/http.py
http.py
import re from lxml import etree def process_multiref(node): """Iterate through the tree and replace the referened elements. This method replaces the nodes with an href attribute and replaces it with the elements it's referencing to (which have an id attribute).abs """ multiref_objects = {elm.attrib["id"]: elm for elm in node.xpath("*[@id]")} if not multiref_objects: return used_nodes = [] def process(node): """Recursive""" # TODO (In Soap 1.2 this is 'ref') href = node.attrib.get("href") if href and href.startswith("#"): obj = multiref_objects.get(href[1:]) if obj is not None: used_nodes.append(obj) node = _dereference_element(obj, node) for child in node: process(child) process(node) # Remove the old dereferenced nodes from the tree for node in used_nodes: parent = node.getparent() if parent is not None: parent.remove(node) def _dereference_element(source, target): """Move the referenced node (source) in the main response tree (target) :type source: lxml.etree._Element :type target: lxml.etree._Element :rtype target: lxml.etree._Element """ specific_nsmap = {k: v for k, v in source.nsmap.items() if k not in target.nsmap} new = _clone_element(source, target.tag, specific_nsmap) # Replace the node with the new dereferenced node parent = target.getparent() parent.insert(parent.index(target), new) parent.remove(target) # Update all descendants for obj in new.iter(): _prefix_node(obj) return new def _clone_element(node, tag_name=None, nsmap=None): """Clone the given node and return it. This is a recursive call since we want to clone the children the same way. :type source: lxml.etree._Element :type tag_name: str :type nsmap: dict :rtype source: lxml.etree._Element """ tag_name = tag_name or node.tag nsmap = node.nsmap if nsmap is None else nsmap new = etree.Element(tag_name, nsmap=nsmap) for child in node: new_child = _clone_element(child) new.append(new_child) new.text = node.text for key, value in _get_attributes(node): new.set(key, value) return new def _prefix_node(node): """Translate the internal attribute values back to prefixed tokens. This reverses the translation done in _get_attributes For example:: { 'foo:type': '{http://example.com}string' } will be converted to: { 'foo:type': 'example:string' } :type node: lxml.etree._Element """ reverse_nsmap = {v: k for k, v in node.nsmap.items()} prefix_re = re.compile("^{([^}]+)}(.*)") for key, value in node.attrib.items(): if value.startswith("{"): match = prefix_re.match(value) namespace, localname = match.groups() if namespace in reverse_nsmap: value = "%s:%s" % (reverse_nsmap.get(namespace), localname) node.set(key, value) def _get_attributes(node): """Return the node attributes where prefixed values are dereferenced. For example the following xml:: <foobar xmlns:xsi="foo" xmlns:ns0="bar" xsi:type="ns0:string"> will return the dict:: { 'foo:type': '{http://example.com}string' } :type node: lxml.etree._Element """ nsmap = node.nsmap result = {} for key, value in node.attrib.items(): if value.count(":") == 1: prefix, localname = value.split(":") if prefix in nsmap: namespace = nsmap[prefix] value = "{%s}%s" % (namespace, localname) result[key] = value return list(result.items())
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/src/zeep/wsdl/messages/multiref.py
multiref.py
import logging from lxml import etree from requests_toolbelt.multipart.decoder import MultipartDecoder from zeep import ns, plugins, wsa from zeep.exceptions import Fault, TransportError, XMLSyntaxError from zeep.loader import parse_xml from zeep.utils import as_qname, get_media_type, qname_attr from zeep.wsdl.attachments import MessagePack from zeep.wsdl.definitions import Binding, Operation from zeep.wsdl.messages import DocumentMessage, RpcMessage from zeep.wsdl.messages.xop import process_xop from zeep.wsdl.utils import etree_to_string, url_http_to_https logger = logging.getLogger(__name__) class SoapBinding(Binding): """Soap 1.1/1.2 binding""" def __init__(self, wsdl, name, port_name, transport, default_style): """The SoapBinding is the base class for the Soap11Binding and Soap12Binding. :param wsdl: :type wsdl: :param name: :type name: string :param port_name: :type port_name: string :param transport: :type transport: zeep.transports.Transport :param default_style: """ super(SoapBinding, self).__init__(wsdl, name, port_name) self.transport = transport self.default_style = default_style @classmethod def match(cls, node): """Check if this binding instance should be used to parse the given node. :param node: The node to match against :type node: lxml.etree._Element """ soap_node = node.find("soap:binding", namespaces=cls.nsmap) return soap_node is not None def create_message(self, operation, *args, **kwargs): envelope, http_headers = self._create(operation, args, kwargs) return envelope def _create(self, operation, args, kwargs, client=None, options=None): """Create the XML document to send to the server. Note that this generates the soap envelope without the wsse applied. """ operation_obj = self.get(operation) if not operation_obj: raise ValueError("Operation %r not found" % operation) # Create the SOAP envelope serialized = operation_obj.create(*args, **kwargs) self._set_http_headers(serialized, operation_obj) envelope = serialized.content http_headers = serialized.headers # Apply ws-addressing if client: if not options: options = client.service._binding_options if operation_obj.abstract.input_message.wsa_action: envelope, http_headers = wsa.WsAddressingPlugin().egress( envelope, http_headers, operation_obj, options ) # Apply plugins envelope, http_headers = plugins.apply_egress( client, envelope, http_headers, operation_obj, options ) # Apply WSSE if client.wsse: if isinstance(client.wsse, list): for wsse in client.wsse: envelope, http_headers = wsse.apply(envelope, http_headers) else: envelope, http_headers = client.wsse.apply(envelope, http_headers) # Add extra http headers from the setings object if client.settings.extra_http_headers: http_headers.update(client.settings.extra_http_headers) return envelope, http_headers def send(self, client, options, operation, args, kwargs): """Called from the service :param client: The client with which the operation was called :type client: zeep.client.Client :param options: The binding options :type options: dict :param operation: The operation object from which this is a reply :type operation: zeep.wsdl.definitions.Operation :param args: The args to pass to the operation :type args: tuple :param kwargs: The kwargs to pass to the operation :type kwargs: dict """ envelope, http_headers = self._create( operation, args, kwargs, client=client, options=options ) response = client.transport.post_xml(options["address"], envelope, http_headers) operation_obj = self.get(operation) # If the client wants to return the raw data then let's do that. if client.settings.raw_response: return response return self.process_reply(client, operation_obj, response) def process_reply(self, client, operation, response): """Process the XML reply from the server. :param client: The client with which the operation was called :type client: zeep.client.Client :param operation: The operation object from which this is a reply :type operation: zeep.wsdl.definitions.Operation :param response: The response object returned by the remote server :type response: requests.Response """ if response.status_code in (201, 202) and not response.content: return None elif response.status_code != 200 and not response.content: raise TransportError( u"Server returned HTTP status %d (no content available)" % response.status_code, status_code=response.status_code, ) content_type = response.headers.get("Content-Type", "text/xml") media_type = get_media_type(content_type) message_pack = None # If the reply is a multipart/related then we need to retrieve all the # parts if media_type == "multipart/related": decoder = MultipartDecoder( response.content, content_type, response.encoding or "utf-8" ) content = decoder.parts[0].content if len(decoder.parts) > 1: message_pack = MessagePack(parts=decoder.parts[1:]) else: content = response.content try: doc = parse_xml(content, self.transport, settings=client.settings) except XMLSyntaxError as exc: raise TransportError( "Server returned response (%s) with invalid XML: %s.\nContent: %r" % (response.status_code, exc, response.content), status_code=response.status_code, content=response.content, ) # Check if this is an XOP message which we need to decode first if message_pack: if process_xop(doc, message_pack): message_pack = None if client.wsse: client.wsse.verify(doc) doc, http_headers = plugins.apply_ingress( client, doc, response.headers, operation ) # If the response code is not 200 or if there is a Fault node available # then assume that an error occured. fault_node = doc.find("soap-env:Body/soap-env:Fault", namespaces=self.nsmap) if response.status_code != 200 or fault_node is not None: return self.process_error(doc, operation) result = operation.process_reply(doc) if message_pack: message_pack._set_root(result) return message_pack return result def process_error(self, doc, operation): raise NotImplementedError def process_service_port(self, xmlelement, force_https=False): address_node = xmlelement.find("soap:address", namespaces=self.nsmap) if address_node is None: logger.debug("No valid soap:address found for service") return # Force the usage of HTTPS when the force_https boolean is true location = address_node.get("location") if force_https and location: location = url_http_to_https(location) if location != address_node.get("location"): logger.warning("Forcing soap:address location to HTTPS") return {"address": location} @classmethod def parse(cls, definitions, xmlelement): """ Definition:: <wsdl:binding name="nmtoken" type="qname"> * <-- extensibility element (1) --> * <wsdl:operation name="nmtoken"> * <-- extensibility element (2) --> * <wsdl:input name="nmtoken"? > ? <-- extensibility element (3) --> </wsdl:input> <wsdl:output name="nmtoken"? > ? <-- extensibility element (4) --> * </wsdl:output> <wsdl:fault name="nmtoken"> * <-- extensibility element (5) --> * </wsdl:fault> </wsdl:operation> </wsdl:binding> """ name = qname_attr(xmlelement, "name", definitions.target_namespace) port_name = qname_attr(xmlelement, "type", definitions.target_namespace) # The soap:binding element contains the transport method and # default style attribute for the operations. soap_node = xmlelement.find("soap:binding", namespaces=cls.nsmap) transport = soap_node.get("transport") supported_transports = [ "http://schemas.xmlsoap.org/soap/http", "http://www.w3.org/2003/05/soap/bindings/HTTP/", ] if transport not in supported_transports: raise NotImplementedError( "The binding transport %s is not supported (only soap/http)" % (transport) ) default_style = soap_node.get("style", "document") obj = cls(definitions.wsdl, name, port_name, transport, default_style) for node in xmlelement.findall("wsdl:operation", namespaces=cls.nsmap): operation = SoapOperation.parse(definitions, node, obj, nsmap=cls.nsmap) obj._operation_add(operation) return obj class Soap11Binding(SoapBinding): nsmap = { "soap": ns.SOAP_11, "soap-env": ns.SOAP_ENV_11, "wsdl": ns.WSDL, "xsd": ns.XSD, } def process_error(self, doc, operation): fault_node = doc.find("soap-env:Body/soap-env:Fault", namespaces=self.nsmap) if fault_node is None: raise Fault( message="Unknown fault occured", code=None, actor=None, detail=etree_to_string(doc), ) def get_text(name): child = fault_node.find(name) if child is not None: return child.text raise Fault( message=get_text("faultstring"), code=get_text("faultcode"), actor=get_text("faultactor"), detail=fault_node.find("detail"), ) def _set_http_headers(self, serialized, operation): serialized.headers["Content-Type"] = "text/xml; charset=utf-8" class Soap12Binding(SoapBinding): nsmap = { "soap": ns.SOAP_12, "soap-env": ns.SOAP_ENV_12, "wsdl": ns.WSDL, "xsd": ns.XSD, } def process_error(self, doc, operation): fault_node = doc.find("soap-env:Body/soap-env:Fault", namespaces=self.nsmap) if fault_node is None: raise Fault( message="Unknown fault occured", code=None, actor=None, detail=etree_to_string(doc), ) def get_text(name): child = fault_node.find(name) if child is not None: return child.text message = fault_node.findtext( "soap-env:Reason/soap-env:Text", namespaces=self.nsmap ) code = fault_node.findtext( "soap-env:Code/soap-env:Value", namespaces=self.nsmap ) # Extract the fault subcodes. These can be nested, as in subcodes can # also contain other subcodes. subcodes = [] subcode_element = fault_node.find( "soap-env:Code/soap-env:Subcode", namespaces=self.nsmap ) while subcode_element is not None: subcode_value_element = subcode_element.find( "soap-env:Value", namespaces=self.nsmap ) subcode_qname = as_qname( subcode_value_element.text, subcode_value_element.nsmap, None ) subcodes.append(subcode_qname) subcode_element = subcode_element.find( "soap-env:Subcode", namespaces=self.nsmap ) # TODO: We should use the fault message as defined in the wsdl. detail_node = fault_node.find("soap-env:Detail", namespaces=self.nsmap) raise Fault( message=message, code=code, actor=None, detail=detail_node, subcodes=subcodes, ) def _set_http_headers(self, serialized, operation): serialized.headers["Content-Type"] = "; ".join( [ "application/soap+xml", "charset=utf-8", 'action="%s"' % operation.soapaction, ] ) class SoapOperation(Operation): """Represent's an operation within a specific binding.""" def __init__(self, name, binding, nsmap, soapaction, style): super(SoapOperation, self).__init__(name, binding) self.nsmap = nsmap self.soapaction = soapaction self.style = style def process_reply(self, envelope): envelope_qname = etree.QName(self.nsmap["soap-env"], "Envelope") if envelope.tag != envelope_qname: raise XMLSyntaxError( ( "The XML returned by the server does not contain a valid " + "{%s}Envelope root element. The root element found is %s " ) % (envelope_qname.namespace, envelope.tag) ) if self.output: return self.output.deserialize(envelope) @classmethod def parse(cls, definitions, xmlelement, binding, nsmap): """ Definition:: <wsdl:operation name="nmtoken"> * <soap:operation soapAction="uri"? style="rpc|document"?>? <wsdl:input name="nmtoken"? > ? <soap:body use="literal"/> </wsdl:input> <wsdl:output name="nmtoken"? > ? <-- extensibility element (4) --> * </wsdl:output> <wsdl:fault name="nmtoken"> * <-- extensibility element (5) --> * </wsdl:fault> </wsdl:operation> Example:: <wsdl:operation name="GetLastTradePrice"> <soap:operation soapAction="http://example.com/GetLastTradePrice"/> <wsdl:input> <soap:body use="literal"/> </wsdl:input> <wsdl:output> </wsdl:output> <wsdl:fault name="dataFault"> <soap:fault name="dataFault" use="literal"/> </wsdl:fault> </operation> """ name = xmlelement.get("name") # The soap:operation element is required for soap/http bindings # and may be omitted for other bindings. soap_node = xmlelement.find("soap:operation", namespaces=binding.nsmap) action = None if soap_node is not None: action = soap_node.get("soapAction") style = soap_node.get("style", binding.default_style) else: style = binding.default_style obj = cls(name, binding, nsmap, action, style) if style == "rpc": message_class = RpcMessage else: message_class = DocumentMessage for node in xmlelement: tag_name = etree.QName(node.tag).localname if tag_name not in ("input", "output", "fault"): continue msg = message_class.parse( definitions=definitions, xmlelement=node, operation=obj, nsmap=nsmap, type=tag_name, ) if tag_name == "fault": obj.faults[msg.name] = msg else: setattr(obj, tag_name, msg) return obj def resolve(self, definitions): super(SoapOperation, self).resolve(definitions) for name, fault in self.faults.items(): if name in self.abstract.fault_messages: fault.resolve(definitions, self.abstract.fault_messages[name]) if self.output: self.output.resolve(definitions, self.abstract.output_message) if self.input: self.input.resolve(definitions, self.abstract.input_message)
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/src/zeep/wsdl/bindings/soap.py
soap.py
import logging import six from lxml import etree from zeep import ns from zeep.exceptions import Fault from zeep.utils import qname_attr from zeep.wsdl import messages from zeep.wsdl.definitions import Binding, Operation logger = logging.getLogger(__name__) NSMAP = {"http": ns.HTTP, "wsdl": ns.WSDL, "mime": ns.MIME} class HttpBinding(Binding): def create_message(self, operation, *args, **kwargs): if isinstance(operation, six.string_types): operation = self.get(operation) if not operation: raise ValueError("Operation not found") return operation.create(*args, **kwargs) def process_service_port(self, xmlelement, force_https=False): address_node = xmlelement.find("http:address", namespaces=NSMAP) if address_node is None: raise ValueError("No `http:address` node found") # Force the usage of HTTPS when the force_https boolean is true location = address_node.get("location") if force_https and location and location.startswith("http://"): logger.warning("Forcing http:address location to HTTPS") location = "https://" + location[8:] return {"address": location} @classmethod def parse(cls, definitions, xmlelement): name = qname_attr(xmlelement, "name", definitions.target_namespace) port_name = qname_attr(xmlelement, "type", definitions.target_namespace) obj = cls(definitions.wsdl, name, port_name) for node in xmlelement.findall("wsdl:operation", namespaces=NSMAP): operation = HttpOperation.parse(definitions, node, obj) obj._operation_add(operation) return obj def process_reply(self, client, operation, response): if response.status_code != 200: return self.process_error(response.content) raise NotImplementedError("No error handling yet!") return operation.process_reply(response.content) def process_error(self, doc): raise Fault(message=doc) class HttpPostBinding(HttpBinding): def send(self, client, options, operation, args, kwargs): """Called from the service""" operation_obj = self.get(operation) if not operation_obj: raise ValueError("Operation %r not found" % operation) serialized = operation_obj.create(*args, **kwargs) url = options["address"] + serialized.path response = client.transport.post( url, serialized.content, headers=serialized.headers ) return self.process_reply(client, operation_obj, response) @classmethod def match(cls, node): """Check if this binding instance should be used to parse the given node. :param node: The node to match against :type node: lxml.etree._Element """ http_node = node.find(etree.QName(NSMAP["http"], "binding")) return http_node is not None and http_node.get("verb") == "POST" class HttpGetBinding(HttpBinding): def send(self, client, options, operation, args, kwargs): """Called from the service""" operation_obj = self.get(operation) if not operation_obj: raise ValueError("Operation %r not found" % operation) serialized = operation_obj.create(*args, **kwargs) url = options["address"] + serialized.path response = client.transport.get( url, serialized.content, headers=serialized.headers ) return self.process_reply(client, operation_obj, response) @classmethod def match(cls, node): """Check if this binding instance should be used to parse the given node. :param node: The node to match against :type node: lxml.etree._Element """ http_node = node.find(etree.QName(ns.HTTP, "binding")) return http_node is not None and http_node.get("verb") == "GET" class HttpOperation(Operation): def __init__(self, name, binding, location): super(HttpOperation, self).__init__(name, binding) self.location = location def process_reply(self, envelope): return self.output.deserialize(envelope) @classmethod def parse(cls, definitions, xmlelement, binding): """ <wsdl:operation name="GetLastTradePrice"> <http:operation location="GetLastTradePrice"/> <wsdl:input> <mime:content type="application/x-www-form-urlencoded"/> </wsdl:input> <wsdl:output> <mime:mimeXml/> </wsdl:output> </wsdl:operation> """ name = xmlelement.get("name") http_operation = xmlelement.find("http:operation", namespaces=NSMAP) location = http_operation.get("location") obj = cls(name, binding, location) for node in xmlelement: tag_name = etree.QName(node.tag).localname if tag_name not in ("input", "output"): continue # XXX Multiple mime types may be declared as alternatives message_node = None nodes = list(node) if len(nodes) > 0: message_node = nodes[0] message_class = None if message_node is not None: if message_node.tag == etree.QName(ns.HTTP, "urlEncoded"): message_class = messages.UrlEncoded elif message_node.tag == etree.QName(ns.HTTP, "urlReplacement"): message_class = messages.UrlReplacement elif message_node.tag == etree.QName(ns.MIME, "content"): message_class = messages.MimeContent elif message_node.tag == etree.QName(ns.MIME, "mimeXml"): message_class = messages.MimeXML if message_class: msg = message_class.parse(definitions, node, obj) assert msg setattr(obj, tag_name, msg) return obj def resolve(self, definitions): super(HttpOperation, self).resolve(definitions) if self.output: self.output.resolve(definitions, self.abstract.output_message) if self.input: self.input.resolve(definitions, self.abstract.input_message)
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/src/zeep/wsdl/bindings/http.py
http.py
import base64 import hashlib import os from zeep import ns from zeep.wsse import utils class UsernameToken(object): """UsernameToken Profile 1.1 https://docs.oasis-open.org/wss/v1.1/wss-v1.1-spec-os-UsernameTokenProfile.pdf Example response using PasswordText:: <wsse:Security> <wsse:UsernameToken> <wsse:Username>scott</wsse:Username> <wsse:Password Type="wsse:PasswordText">password</wsse:Password> </wsse:UsernameToken> </wsse:Security> Example using PasswordDigest:: <wsse:Security> <wsse:UsernameToken> <wsse:Username>NNK</wsse:Username> <wsse:Password Type="wsse:PasswordDigest"> weYI3nXd8LjMNVksCKFV8t3rgHh3Rw== </wsse:Password> <wsse:Nonce>WScqanjCEAC4mQoBE07sAQ==</wsse:Nonce> <wsu:Created>2003-07-16T01:24:32Z</wsu:Created> </wsse:UsernameToken> </wsse:Security> """ username_token_profile_ns = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0" # noqa soap_message_secutity_ns = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0" # noqa def __init__( self, username, password=None, password_digest=None, use_digest=False, nonce=None, created=None, timestamp_token=None, ): self.username = username self.password = password self.password_digest = password_digest self.nonce = nonce self.created = created self.use_digest = use_digest self.timestamp_token = timestamp_token def apply(self, envelope, headers): security = utils.get_security_header(envelope) # The token placeholder might already exists since it is specified in # the WSDL. token = security.find("{%s}UsernameToken" % ns.WSSE) if token is None: token = utils.WSSE.UsernameToken() security.append(token) if self.timestamp_token is not None: security.append(self.timestamp_token) # Create the sub elements of the UsernameToken element elements = [utils.WSSE.Username(self.username)] if self.password is not None or self.password_digest is not None: if self.use_digest: elements.extend(self._create_password_digest()) else: elements.extend(self._create_password_text()) token.extend(elements) return envelope, headers def verify(self, envelope): pass def _create_password_text(self): return [ utils.WSSE.Password( self.password, Type="%s#PasswordText" % self.username_token_profile_ns ) ] def _create_password_digest(self): if self.nonce: nonce = self.nonce.encode("utf-8") else: nonce = os.urandom(16) timestamp = utils.get_timestamp(self.created) # digest = Base64 ( SHA-1 ( nonce + created + password ) ) if not self.password_digest: digest = base64.b64encode( hashlib.sha1( nonce + timestamp.encode("utf-8") + self.password.encode("utf-8") ).digest() ).decode("ascii") else: digest = self.password_digest return [ utils.WSSE.Password( digest, Type="%s#PasswordDigest" % self.username_token_profile_ns ), utils.WSSE.Nonce( base64.b64encode(nonce).decode("utf-8"), EncodingType="%s#Base64Binary" % self.soap_message_secutity_ns, ), utils.WSU.Created(timestamp), ]
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/src/zeep/wsse/username.py
username.py
from lxml import etree from lxml.etree import QName from zeep import ns from zeep.exceptions import SignatureVerificationFailed from zeep.utils import detect_soap_env from zeep.wsse.utils import ensure_id, get_security_header try: import xmlsec except ImportError: xmlsec = None # SOAP envelope SOAP_NS = "http://schemas.xmlsoap.org/soap/envelope/" def _read_file(f_name): with open(f_name, "rb") as f: return f.read() def _make_sign_key(key_data, cert_data, password): key = xmlsec.Key.from_memory(key_data, xmlsec.KeyFormat.PEM, password) key.load_cert_from_memory(cert_data, xmlsec.KeyFormat.PEM) return key def _make_verify_key(cert_data): key = xmlsec.Key.from_memory(cert_data, xmlsec.KeyFormat.CERT_PEM, None) return key class MemorySignature(object): """Sign given SOAP envelope with WSSE sig using given key and cert.""" def __init__( self, key_data, cert_data, password=None, signature_method=None, digest_method=None, ): check_xmlsec_import() self.key_data = key_data self.cert_data = cert_data self.password = password self.digest_method = digest_method self.signature_method = signature_method def apply(self, envelope, headers): key = _make_sign_key(self.key_data, self.cert_data, self.password) _sign_envelope_with_key( envelope, key, self.signature_method, self.digest_method ) return envelope, headers def verify(self, envelope): key = _make_verify_key(self.cert_data) _verify_envelope_with_key(envelope, key) return envelope class Signature(MemorySignature): """Sign given SOAP envelope with WSSE sig using given key file and cert file.""" def __init__( self, key_file, certfile, password=None, signature_method=None, digest_method=None, ): super(Signature, self).__init__( _read_file(key_file), _read_file(certfile), password, signature_method, digest_method, ) class BinarySignature(Signature): """Sign given SOAP envelope with WSSE sig using given key file and cert file. Place the key information into BinarySecurityElement.""" def apply(self, envelope, headers): key = _make_sign_key(self.key_data, self.cert_data, self.password) _sign_envelope_with_key_binary( envelope, key, self.signature_method, self.digest_method ) return envelope, headers def check_xmlsec_import(): if xmlsec is None: raise ImportError( "The xmlsec module is required for wsse.Signature()\n" + "You can install xmlsec with: pip install xmlsec\n" + "or install zeep via: pip install zeep[xmlsec]\n" ) def sign_envelope( envelope, keyfile, certfile, password=None, signature_method=None, digest_method=None, ): """Sign given SOAP envelope with WSSE sig using given key and cert. Sign the wsu:Timestamp node in the wsse:Security header and the soap:Body; both must be present. Add a ds:Signature node in the wsse:Security header containing the signature. Use EXCL-C14N transforms to normalize the signed XML (so that irrelevant whitespace or attribute ordering changes don't invalidate the signature). Use SHA1 signatures. Expects to sign an incoming document something like this (xmlns attributes omitted for readability): <soap:Envelope> <soap:Header> <wsse:Security mustUnderstand="true"> <wsu:Timestamp> <wsu:Created>2015-06-25T21:53:25.246276+00:00</wsu:Created> <wsu:Expires>2015-06-25T21:58:25.246276+00:00</wsu:Expires> </wsu:Timestamp> </wsse:Security> </soap:Header> <soap:Body> ... </soap:Body> </soap:Envelope> After signing, the sample document would look something like this (note the added wsu:Id attr on the soap:Body and wsu:Timestamp nodes, and the added ds:Signature node in the header, with ds:Reference nodes with URI attribute referencing the wsu:Id of the signed nodes): <soap:Envelope> <soap:Header> <wsse:Security mustUnderstand="true"> <Signature xmlns="http://www.w3.org/2000/09/xmldsig#"> <SignedInfo> <CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/> <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/> <Reference URI="#id-d0f9fd77-f193-471f-8bab-ba9c5afa3e76"> <Transforms> <Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/> </Transforms> <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/> <DigestValue>nnjjqTKxwl1hT/2RUsBuszgjTbI=</DigestValue> </Reference> <Reference URI="#id-7c425ac1-534a-4478-b5fe-6cae0690f08d"> <Transforms> <Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/> </Transforms> <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/> <DigestValue>qAATZaSqAr9fta9ApbGrFWDuCCQ=</DigestValue> </Reference> </SignedInfo> <SignatureValue>Hz8jtQb...bOdT6ZdTQ==</SignatureValue> <KeyInfo> <wsse:SecurityTokenReference> <X509Data> <X509Certificate>MIIDnzC...Ia2qKQ==</X509Certificate> <X509IssuerSerial> <X509IssuerName>...</X509IssuerName> <X509SerialNumber>...</X509SerialNumber> </X509IssuerSerial> </X509Data> </wsse:SecurityTokenReference> </KeyInfo> </Signature> <wsu:Timestamp wsu:Id="id-7c425ac1-534a-4478-b5fe-6cae0690f08d"> <wsu:Created>2015-06-25T22:00:29.821700+00:00</wsu:Created> <wsu:Expires>2015-06-25T22:05:29.821700+00:00</wsu:Expires> </wsu:Timestamp> </wsse:Security> </soap:Header> <soap:Body wsu:Id="id-d0f9fd77-f193-471f-8bab-ba9c5afa3e76"> ... </soap:Body> </soap:Envelope> """ # Load the signing key and certificate. key = _make_sign_key(_read_file(keyfile), _read_file(certfile), password) return _sign_envelope_with_key(envelope, key, signature_method, digest_method) def _signature_prepare(envelope, key, signature_method, digest_method): """Prepare envelope and sign.""" soap_env = detect_soap_env(envelope) # Create the Signature node. signature = xmlsec.template.create( envelope, xmlsec.Transform.EXCL_C14N, signature_method or xmlsec.Transform.RSA_SHA1, ) # Add a KeyInfo node with X509Data child to the Signature. XMLSec will fill # in this template with the actual certificate details when it signs. key_info = xmlsec.template.ensure_key_info(signature) x509_data = xmlsec.template.add_x509_data(key_info) xmlsec.template.x509_data_add_issuer_serial(x509_data) xmlsec.template.x509_data_add_certificate(x509_data) # Insert the Signature node in the wsse:Security header. security = get_security_header(envelope) security.insert(0, signature) # Perform the actual signing. ctx = xmlsec.SignatureContext() ctx.key = key _sign_node(ctx, signature, envelope.find(QName(soap_env, "Body")), digest_method) timestamp = security.find(QName(ns.WSU, "Timestamp")) if timestamp != None: _sign_node(ctx, signature, timestamp) ctx.sign(signature) # Place the X509 data inside a WSSE SecurityTokenReference within # KeyInfo. The recipient expects this structure, but we can't rearrange # like this until after signing, because otherwise xmlsec won't populate # the X509 data (because it doesn't understand WSSE). sec_token_ref = etree.SubElement(key_info, QName(ns.WSSE, "SecurityTokenReference")) return security, sec_token_ref, x509_data def _sign_envelope_with_key(envelope, key, signature_method, digest_method): _, sec_token_ref, x509_data = _signature_prepare( envelope, key, signature_method, digest_method ) sec_token_ref.append(x509_data) def _sign_envelope_with_key_binary(envelope, key, signature_method, digest_method): security, sec_token_ref, x509_data = _signature_prepare( envelope, key, signature_method, digest_method ) ref = etree.SubElement( sec_token_ref, QName(ns.WSSE, "Reference"), { "ValueType": "http://docs.oasis-open.org/wss/2004/01/" "oasis-200401-wss-x509-token-profile-1.0#X509v3" }, ) bintok = etree.Element( QName(ns.WSSE, "BinarySecurityToken"), { "ValueType": "http://docs.oasis-open.org/wss/2004/01/" "oasis-200401-wss-x509-token-profile-1.0#X509v3", "EncodingType": "http://docs.oasis-open.org/wss/2004/01/" "oasis-200401-wss-soap-message-security-1.0#Base64Binary", }, ) ref.attrib["URI"] = "#" + ensure_id(bintok) bintok.text = x509_data.find(QName(ns.DS, "X509Certificate")).text security.insert(1, bintok) x509_data.getparent().remove(x509_data) def verify_envelope(envelope, certfile): """Verify WS-Security signature on given SOAP envelope with given cert. Expects a document like that found in the sample XML in the ``sign()`` docstring. Raise SignatureVerificationFailed on failure, silent on success. """ key = _make_verify_key(_read_file(certfile)) return _verify_envelope_with_key(envelope, key) def _verify_envelope_with_key(envelope, key): soap_env = detect_soap_env(envelope) header = envelope.find(QName(soap_env, "Header")) if header is None: raise SignatureVerificationFailed() security = header.find(QName(ns.WSSE, "Security")) signature = security.find(QName(ns.DS, "Signature")) ctx = xmlsec.SignatureContext() # Find each signed element and register its ID with the signing context. refs = signature.xpath("ds:SignedInfo/ds:Reference", namespaces={"ds": ns.DS}) for ref in refs: # Get the reference URI and cut off the initial '#' referenced_id = ref.get("URI")[1:] referenced = envelope.xpath( "//*[@wsu:Id='%s']" % referenced_id, namespaces={"wsu": ns.WSU} )[0] ctx.register_id(referenced, "Id", ns.WSU) ctx.key = key try: ctx.verify(signature) except xmlsec.Error: # Sadly xmlsec gives us no details about the reason for the failure, so # we have nothing to pass on except that verification failed. raise SignatureVerificationFailed() def _sign_node(ctx, signature, target, digest_method=None): """Add sig for ``target`` in ``signature`` node, using ``ctx`` context. Doesn't actually perform the signing; ``ctx.sign(signature)`` should be called later to do that. Adds a Reference node to the signature with URI attribute pointing to the target node, and registers the target node's ID so XMLSec will be able to find the target node by ID when it signs. """ # Ensure the target node has a wsu:Id attribute and get its value. node_id = ensure_id(target) # Unlike HTML, XML doesn't have a single standardized Id. WSSE suggests the # use of the wsu:Id attribute for this purpose, but XMLSec doesn't # understand that natively. So for XMLSec to be able to find the referenced # node by id, we have to tell xmlsec about it using the register_id method. ctx.register_id(target, "Id", ns.WSU) # Add reference to signature with URI attribute pointing to that ID. ref = xmlsec.template.add_reference( signature, digest_method or xmlsec.Transform.SHA1, uri="#" + node_id ) # This is an XML normalization transform which will be performed on the # target node contents before signing. This ensures that changes to # irrelevant whitespace, attribute ordering, etc won't invalidate the # signature. xmlsec.template.add_transform(ref, xmlsec.Transform.EXCL_C14N)
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/src/zeep/wsse/signature.py
signature.py
import asyncio import logging import aiohttp from requests import Response from zeep.asyncio import bindings from zeep.exceptions import TransportError from zeep.transports import Transport from zeep.utils import get_version from zeep.wsdl.utils import etree_to_string try: from async_timeout import timeout as aio_timeout # Python 3.6+ except ImportError: from aiohttp import Timeout as aio_timeout # Python 3.5, aiohttp < 3 __all__ = ["AsyncTransport"] class AsyncTransport(Transport): """Asynchronous Transport class using aiohttp.""" binding_classes = [bindings.AsyncSoap11Binding, bindings.AsyncSoap12Binding] def __init__( self, loop, cache=None, timeout=300, operation_timeout=None, session=None, verify_ssl=True, proxy=None, ): self.loop = loop if loop else asyncio.get_event_loop() self.cache = cache self.load_timeout = timeout self.operation_timeout = operation_timeout self.logger = logging.getLogger(__name__) self.verify_ssl = verify_ssl self.proxy = proxy self.session = session or aiohttp.ClientSession(loop=self.loop) self._close_session = session is None self.session._default_headers[ "User-Agent" ] = "Zeep/%s (www.python-zeep.org)" % (get_version()) def __del__(self): if self._close_session: # aiohttp.ClientSession.close() is async, # call the underlying sync function instead. if self.session.connector is not None: self.session.connector.close() def _load_remote_data(self, url): result = None if self.loop.is_running(): raise RuntimeError( "WSDL loading is not asynchronous yet. " "Instantiate the zeep client outside the asyncio event loop." ) async def _load_remote_data_async(): nonlocal result with aio_timeout(self.load_timeout): response = await self.session.get(url) result = await response.read() try: response.raise_for_status() except aiohttp.ClientError as exc: raise TransportError( message=str(exc), status_code=response.status, content=result ).with_traceback(exc.__traceback__) from exc # Block until we have the data self.loop.run_until_complete(_load_remote_data_async()) return result async def post(self, address, message, headers): self.logger.debug("HTTP Post to %s:\n%s", address, message) with aio_timeout(self.operation_timeout): response = await self.session.post( address, data=message, headers=headers, verify_ssl=self.verify_ssl, proxy=self.proxy, ) self.logger.debug( "HTTP Response from %s (status: %d):\n%s", address, response.status, await response.read(), ) return response async def post_xml(self, address, envelope, headers): message = etree_to_string(envelope) response = await self.post(address, message, headers) return await self.new_response(response) async def get(self, address, params, headers): with aio_timeout(self.operation_timeout): response = await self.session.get( address, params=params, headers=headers, verify_ssl=self.verify_ssl, proxy=self.proxy, ) return await self.new_response(response) async def new_response(self, response): """Convert an aiohttp.Response object to a requests.Response object""" new = Response() new._content = await response.read() new.status_code = response.status new.headers = response.headers new.cookies = response.cookies new.encoding = response.charset return new
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/src/zeep/asyncio/transport.py
transport.py
import logging import urllib from requests import Response, Session from requests.auth import HTTPBasicAuth, HTTPDigestAuth from tornado import gen, httpclient from zeep.tornado import bindings from zeep.transports import Transport from zeep.utils import get_version from zeep.wsdl.utils import etree_to_string __all__ = ["TornadoAsyncTransport"] class TornadoAsyncTransport(Transport): """Asynchronous Transport class using tornado gen.""" binding_classes = [bindings.AsyncSoap11Binding, bindings.AsyncSoap12Binding] def __init__(self, cache=None, timeout=300, operation_timeout=None, session=None): self.cache = cache self.load_timeout = timeout self.operation_timeout = operation_timeout self.logger = logging.getLogger(__name__) self.session = session or Session() self.session.headers["User-Agent"] = "Zeep/%s (www.python-zeep.org)" % ( get_version() ) def _load_remote_data(self, url): client = httpclient.HTTPClient() kwargs = { "method": "GET", "connect_timeout": self.load_timeout, "request_timeout": self.load_timeout, } http_req = httpclient.HTTPRequest(url, **kwargs) response = client.fetch(http_req) return response.body @gen.coroutine def post(self, address, message, headers): response = yield self.fetch(address, "POST", headers, message) raise gen.Return(response) @gen.coroutine def post_xml(self, address, envelope, headers): message = etree_to_string(envelope) response = yield self.post(address, message, headers) raise gen.Return(response) @gen.coroutine def get(self, address, params, headers): if params: address += "?" + urllib.urlencode(params) response = yield self.fetch(address, "GET", headers) raise gen.Return(response) @gen.coroutine def fetch(self, address, method, headers, message=None): async_client = httpclient.AsyncHTTPClient() # extracting auth auth_username = None auth_password = None auth_mode = None if self.session.auth: if type(self.session.auth) is tuple: auth_username = self.session.auth[0] auth_password = self.session.auth[1] auth_mode = "basic" elif type(self.session.auth) is HTTPBasicAuth: auth_username = self.session.username auth_password = self.session.password auth_mode = "basic" elif type(self.session.auth) is HTTPDigestAuth: auth_username = self.session.username auth_password = self.session.password auth_mode = "digest" else: raise Exception("Not supported authentication.") # extracting client cert client_cert = None client_key = None ca_certs = None if self.session.cert: if type(self.session.cert) is str: ca_certs = self.session.cert elif type(self.session.cert) is tuple: client_cert = self.session.cert[0] client_key = self.session.cert[1] session_headers = dict(self.session.headers.items()) kwargs = { "method": method, "connect_timeout": self.operation_timeout, "request_timeout": self.operation_timeout, "headers": dict(headers, **session_headers), "auth_username": auth_username, "auth_password": auth_password, "auth_mode": auth_mode, "validate_cert": bool(self.session.verify), "ca_certs": ca_certs, "client_key": client_key, "client_cert": client_cert, } if message: kwargs["body"] = message http_req = httpclient.HTTPRequest(address, **kwargs) response = yield async_client.fetch(http_req, raise_error=False) raise gen.Return(self.new_response(response)) @staticmethod def new_response(response): """Convert an tornado.HTTPResponse object to a requests.Response object""" new = Response() new._content = response.body new.status_code = response.code new.headers = dict(response.headers.get_all()) return new
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/src/zeep/tornado/transport.py
transport.py
import logging from collections import OrderedDict from lxml import etree from zeep import exceptions, ns from zeep.loader import load_external from zeep.settings import Settings from zeep.xsd import const from zeep.xsd.elements import builtins as xsd_builtins_elements from zeep.xsd.types import builtins as xsd_builtins_types from zeep.xsd.visitor import SchemaVisitor logger = logging.getLogger(__name__) class Schema(object): """A schema is a collection of schema documents.""" def __init__(self, node=None, transport=None, location=None, settings=None): """ :param node: :param transport: :param location: :param settings: The settings object """ self.settings = settings or Settings() self._transport = transport self.documents = _SchemaContainer() self._prefix_map_auto = {} self._prefix_map_custom = {} self._load_default_documents() if not isinstance(node, list): nodes = [node] if node is not None else [] else: nodes = node self.add_documents(nodes, location) def __repr__(self): main_doc = self.root_document if main_doc: return "<Schema(location=%r, tns=%r)>" % ( main_doc._location, main_doc._target_namespace, ) return "<Schema()>" @property def prefix_map(self): retval = {} retval.update(self._prefix_map_custom) retval.update( {k: v for k, v in self._prefix_map_auto.items() if v not in retval.values()} ) return retval @property def root_document(self): return next((doc for doc in self.documents if not doc._is_internal), None) @property def is_empty(self): """Boolean to indicate if this schema contains any types or elements""" return all(document.is_empty for document in self.documents) @property def namespaces(self): return self.documents.get_all_namespaces() @property def elements(self): """Yield all globla xsd.Type objects :rtype: Iterable of zeep.xsd.Element """ seen = set() for document in self.documents: for element in document._elements.values(): if element.qname not in seen: yield element seen.add(element.qname) @property def types(self): """Yield all global xsd.Type objects :rtype: Iterable of zeep.xsd.ComplexType """ seen = set() for document in self.documents: for type_ in document._types.values(): if type_.qname not in seen: yield type_ seen.add(type_.qname) def add_documents(self, schema_nodes, location): """ :type schema_nodes: List[lxml.etree._Element] :type location: str :type target_namespace: Optional[str] """ resolve_queue = [] for node in schema_nodes: document = self.create_new_document(node, location) resolve_queue.append(document) for document in resolve_queue: document.resolve() self._prefix_map_auto = self._create_prefix_map() def add_document_by_url(self, url): schema_node = load_external(url, self._transport, settings=self.settings) document = self.create_new_document(schema_node, url=url) document.resolve() def get_element(self, qname): """Return a global xsd.Element object with the given qname :rtype: zeep.xsd.Group """ qname = self._create_qname(qname) return self._get_instance(qname, "get_element", "element") def get_type(self, qname, fail_silently=False): """Return a global xsd.Type object with the given qname :rtype: zeep.xsd.ComplexType or zeep.xsd.AnySimpleType """ qname = self._create_qname(qname) try: return self._get_instance(qname, "get_type", "type") except exceptions.NamespaceError as exc: if fail_silently: logger.debug(str(exc)) else: raise def get_group(self, qname): """Return a global xsd.Group object with the given qname. :rtype: zeep.xsd.Group """ return self._get_instance(qname, "get_group", "group") def get_attribute(self, qname): """Return a global xsd.attributeGroup object with the given qname :rtype: zeep.xsd.Attribute """ return self._get_instance(qname, "get_attribute", "attribute") def get_attribute_group(self, qname): """Return a global xsd.attributeGroup object with the given qname :rtype: zeep.xsd.AttributeGroup """ return self._get_instance(qname, "get_attribute_group", "attributeGroup") def set_ns_prefix(self, prefix, namespace): self._prefix_map_custom[prefix] = namespace def get_ns_prefix(self, prefix): try: try: return self._prefix_map_custom[prefix] except KeyError: return self._prefix_map_auto[prefix] except KeyError: raise ValueError("No such prefix %r" % prefix) def get_shorthand_for_ns(self, namespace): for prefix, other_namespace in self._prefix_map_auto.items(): if namespace == other_namespace: return prefix for prefix, other_namespace in self._prefix_map_custom.items(): if namespace == other_namespace: return prefix if namespace == "http://schemas.xmlsoap.org/soap/envelope/": return "soap-env" return namespace def create_new_document(self, node, url, base_url=None, target_namespace=None): """ :rtype: zeep.xsd.schema.SchemaDocument """ namespace = node.get("targetNamespace") if node is not None else None if not namespace: namespace = target_namespace if base_url is None: base_url = url schema = SchemaDocument(namespace, url, base_url) self.documents.add(schema) schema.load(self, node) return schema def merge(self, schema): """Merge an other XSD schema in this one""" for document in schema.documents: self.documents.add(document) self._prefix_map_auto = self._create_prefix_map() def deserialize(self, node): elm = self.get_element(node.tag) return elm.parse(node, schema=self) def _load_default_documents(self): schema = SchemaDocument(ns.XSD, None, None) for cls in xsd_builtins_types._types: instance = cls(is_global=True) schema.register_type(cls._default_qname, instance) for cls in xsd_builtins_elements._elements: instance = cls() schema.register_element(cls.qname, instance) schema._is_internal = True self.documents.add(schema) return schema def _get_instance(self, qname, method_name, name): """Return an object from one of the SchemaDocument's""" qname = self._create_qname(qname) try: last_exception = None for schema in self._get_schema_documents(qname.namespace): method = getattr(schema, method_name) try: return method(qname) except exceptions.LookupError as exc: last_exception = exc continue raise last_exception except exceptions.NamespaceError: raise exceptions.NamespaceError( ( "Unable to resolve %s %s. " + "No schema available for the namespace %r." ) % (name, qname.text, qname.namespace) ) def _create_qname(self, name): """Create an `lxml.etree.QName()` object for the given qname string. This also expands the shorthand notation. :rtype: lxml.etree.QNaame """ if isinstance(name, etree.QName): return name if not name.startswith("{") and ":" in name and self._prefix_map_auto: prefix, localname = name.split(":", 1) if prefix in self._prefix_map_custom: return etree.QName(self._prefix_map_custom[prefix], localname) elif prefix in self._prefix_map_auto: return etree.QName(self._prefix_map_auto[prefix], localname) else: raise ValueError("No namespace defined for the prefix %r" % prefix) else: return etree.QName(name) def _create_prefix_map(self): prefix_map = {"xsd": "http://www.w3.org/2001/XMLSchema"} i = 0 for namespace in self.documents.get_all_namespaces(): if namespace is None or namespace in prefix_map.values(): continue prefix_map["ns%d" % i] = namespace i += 1 return prefix_map def _get_schema_documents(self, namespace, fail_silently=False): """Return a list of SchemaDocument's for the given namespace. :rtype: list of SchemaDocument """ if ( not self.documents.has_schema_document_for_ns(namespace) and namespace in const.AUTO_IMPORT_NAMESPACES ): logger.debug("Auto importing missing known schema: %s", namespace) self.add_document_by_url(namespace) return self.documents.get_by_namespace(namespace, fail_silently) class _SchemaContainer(object): """Container instances to store multiple SchemaDocument objects per namespace. """ def __init__(self): self._instances = OrderedDict() def __iter__(self): for document in self.values(): yield document def add(self, document): """Append a schema document :param document: zeep.xsd.schema.SchemaDocument """ logger.debug( "Add document with tns %s to schema %s", document.namespace, id(self) ) documents = self._instances.setdefault(document.namespace, []) documents.append(document) def get_all_namespaces(self): return self._instances.keys() def get_by_namespace(self, namespace, fail_silently): if namespace not in self._instances: if fail_silently: return [] raise exceptions.NamespaceError( "No schema available for the namespace %r" % namespace ) return self._instances[namespace] def get_by_namespace_and_location(self, namespace, location): """Return list of SchemaDocument's for the given namespace AND location. :rtype: zeep.xsd.schema.SchemaDocument """ documents = self.get_by_namespace(namespace, fail_silently=True) for document in documents: if document._location == location: return document def has_schema_document_for_ns(self, namespace): """Return a boolean if there is a SchemaDocument for the namespace. :rtype: boolean """ return namespace in self._instances def values(self): for documents in self._instances.values(): for document in documents: yield document class SchemaDocument(object): """A Schema Document consists of a set of schema components for a specific target namespace. """ def __init__(self, namespace, location, base_url): logger.debug("Init schema document for %r", location) # Internal self._base_url = base_url or location self._location = location self._target_namespace = namespace self._is_internal = False self._has_empty_import = False # Containers for specific types self._attribute_groups = {} self._attributes = {} self._elements = {} self._groups = {} self._types = {} self._imports = OrderedDict() self._element_form = "unqualified" self._attribute_form = "unqualified" self._resolved = False # self._xml_schema = None def __repr__(self): return "<SchemaDocument(location=%r, tns=%r, is_empty=%r)>" % ( self._location, self._target_namespace, self.is_empty, ) @property def namespace(self): return self._target_namespace @property def is_empty(self): return not bool(self._imports or self._types or self._elements) def load(self, schema, node): """Load the XML Schema passed in via the node attribute. :type schema: zeep.xsd.schema.Schema :type node: etree._Element """ if node is None: return if not schema.documents.has_schema_document_for_ns(self._target_namespace): raise RuntimeError( "The document needs to be registered in the schema before " + "it can be loaded" ) # Disable XML schema validation for now # if len(node) > 0: # self.xml_schema = etree.XMLSchema(node) visitor = SchemaVisitor(schema, self) visitor.visit_schema(node) def resolve(self): logger.debug("Resolving in schema %s", self) if self._resolved: return self._resolved = True for schemas in self._imports.values(): for schema in schemas: schema.resolve() def _resolve_dict(val): try: for key, obj in val.items(): new = obj.resolve() assert new is not None, "resolve() should return an object" val[key] = new except exceptions.LookupError as exc: raise exceptions.LookupError( ( "Unable to resolve %(item_name)s %(qname)s in " "%(file)s. (via %(parent)s)" ) % { "item_name": exc.item_name, "qname": exc.qname, "file": exc.location, "parent": obj.qname, } ) _resolve_dict(self._attribute_groups) _resolve_dict(self._attributes) _resolve_dict(self._elements) _resolve_dict(self._groups) _resolve_dict(self._types) def register_import(self, namespace, schema): """Register an import for an other schema document. :type namespace: str :type schema: zeep.xsd.schema.SchemaDocument """ schemas = self._imports.setdefault(namespace, []) schemas.append(schema) def is_imported(self, namespace): return namespace in self._imports def register_type(self, qname, value): """Register a xsd.Type in this schema :type qname: str or etree.QName :type value: zeep.xsd.Type """ self._add_component(qname, value, self._types, "type") def register_element(self, qname, value): """Register a xsd.Element in this schema :type qname: str or etree.QName :type value: zeep.xsd.Element """ self._add_component(qname, value, self._elements, "element") def register_group(self, qname, value): """Register a xsd.Element in this schema :type qname: str or etree.QName :type value: zeep.xsd.Element """ self._add_component(qname, value, self._groups, "group") def register_attribute(self, qname, value): """Register a xsd.Element in this schema :type qname: str or etree.QName :type value: zeep.xsd.Attribute """ self._add_component(qname, value, self._attributes, "attribute") def register_attribute_group(self, qname, value): """Register a xsd.Element in this schema :type qname: str or etree.QName :type value: zeep.xsd.Group """ self._add_component(qname, value, self._attribute_groups, "attribute_group") def get_type(self, qname): """Return a xsd.Type object from this schema :rtype: zeep.xsd.ComplexType or zeep.xsd.AnySimpleType """ return self._get_component(qname, self._types, "type") def get_element(self, qname): """Return a xsd.Element object from this schema :rtype: zeep.xsd.Element """ return self._get_component(qname, self._elements, "element") def get_group(self, qname): """Return a xsd.Group object from this schema. :rtype: zeep.xsd.Group """ return self._get_component(qname, self._groups, "group") def get_attribute(self, qname): """Return a xsd.Attribute object from this schema :rtype: zeep.xsd.Attribute """ return self._get_component(qname, self._attributes, "attribute") def get_attribute_group(self, qname): """Return a xsd.AttributeGroup object from this schema :rtype: zeep.xsd.AttributeGroup """ return self._get_component(qname, self._attribute_groups, "attributeGroup") def _add_component(self, name, value, items, item_name): if isinstance(name, etree.QName): name = name.text logger.debug("register_%s(%r, %r)", item_name, name, value) items[name] = value def _get_component(self, qname, items, item_name): try: return items[qname] except KeyError: known_items = ", ".join(items.keys()) raise exceptions.LookupError( ( "No %(item_name)s '%(localname)s' in namespace %(namespace)s. " + "Available %(item_name_plural)s are: %(known_items)s" ) % { "item_name": item_name, "item_name_plural": item_name + "s", "localname": qname.localname, "namespace": qname.namespace, "known_items": known_items or " - ", }, qname=qname, item_name=item_name, location=self._location, )
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/src/zeep/xsd/schema.py
schema.py
from collections import OrderedDict from six import StringIO class PrettyPrinter(object): """Cleaner pprint output. Heavily inspired by the Python pprint module, but more basic for now. """ def pformat(self, obj): stream = StringIO() self._format(obj, stream) return stream.getvalue() def _format(self, obj, stream, indent=4, level=1): _repr = getattr(type(obj), "__repr__", None) write = stream.write if (isinstance(obj, dict) and _repr is dict.__repr__) or ( isinstance(obj, OrderedDict) and _repr == OrderedDict.__repr__ ): write("{\n") num = len(obj) if num > 0: for i, (key, value) in enumerate(obj.items()): write(" " * (indent * level)) write("'%s'" % key) write(": ") self._format(value, stream, level=level + 1) if i < num - 1: write(",") write("\n") write(" " * (indent * (level - 1))) write("}") elif isinstance(obj, list) and _repr is list.__repr__: write("[") num = len(obj) if num > 0: write("\n") for i, value in enumerate(obj): write(" " * (indent * level)) self._format(value, stream, level=level + 1) if i < num - 1: write(",") write("\n") write(" " * (indent * (level - 1))) write("]") else: value = repr(obj) if "\n" in value: lines = value.split("\n") num = len(lines) for i, line in enumerate(lines): if i > 0: write(" " * (indent * (level - 1))) write(line) if i < num - 1: write("\n") else: write(value)
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/src/zeep/xsd/printer.py
printer.py
import keyword import logging import re from lxml import etree from zeep.exceptions import XMLParseError from zeep.loader import absolute_location, load_external, normalize_location from zeep.utils import as_qname, qname_attr from zeep.xsd import elements as xsd_elements from zeep.xsd import types as xsd_types from zeep.xsd.const import AUTO_IMPORT_NAMESPACES, xsd_ns from zeep.xsd.types.unresolved import UnresolvedCustomType, UnresolvedType logger = logging.getLogger(__name__) class tags(object): pass for name in [ "schema", "import", "include", "annotation", "element", "simpleType", "complexType", "simpleContent", "complexContent", "sequence", "group", "choice", "all", "list", "union", "attribute", "any", "anyAttribute", "attributeGroup", "restriction", "extension", "notation", ]: attr = name if name not in keyword.kwlist else name + "_" setattr(tags, attr, xsd_ns(name)) class SchemaVisitor(object): """Visitor which processes XSD files and registers global elements and types in the given schema. :param schema: :type schema: zeep.xsd.schema.Schema :param document: :type document: zeep.xsd.schema.SchemaDocument """ def __init__(self, schema, document): self.document = document self.schema = schema self._includes = set() def register_element(self, qname, instance): self.document.register_element(qname, instance) def register_attribute(self, name, instance): self.document.register_attribute(name, instance) def register_type(self, qname, instance): self.document.register_type(qname, instance) def register_group(self, qname, instance): self.document.register_group(qname, instance) def register_attribute_group(self, qname, instance): self.document.register_attribute_group(qname, instance) def register_import(self, namespace, document): self.document.register_import(namespace, document) def process(self, node, parent): visit_func = self.visitors.get(node.tag) if not visit_func: raise ValueError("No visitor defined for %r" % node.tag) result = visit_func(self, node, parent) return result def process_ref_attribute(self, node, array_type=None): ref = qname_attr(node, "ref") if ref: ref = self._create_qname(ref) # Some wsdl's reference to xs:schema, we ignore that for now. It # might be better in the future to process the actual schema file # so that it is handled correctly if ref.namespace == "http://www.w3.org/2001/XMLSchema": return return xsd_elements.RefAttribute( node.tag, ref, self.schema, array_type=array_type ) def process_reference(self, node, **kwargs): ref = qname_attr(node, "ref") if not ref: return ref = self._create_qname(ref) if node.tag == tags.element: cls = xsd_elements.RefElement elif node.tag == tags.attribute: cls = xsd_elements.RefAttribute elif node.tag == tags.group: cls = xsd_elements.RefGroup elif node.tag == tags.attributeGroup: cls = xsd_elements.RefAttributeGroup return cls(node.tag, ref, self.schema, **kwargs) def visit_schema(self, node): """Visit the xsd:schema element and process all the child elements Definition:: <schema attributeFormDefault = (qualified | unqualified): unqualified blockDefault = (#all | List of (extension | restriction | substitution) : '' elementFormDefault = (qualified | unqualified): unqualified finalDefault = (#all | List of (extension | restriction | list | union): '' id = ID targetNamespace = anyURI version = token xml:lang = language {any attributes with non-schema Namespace}...> Content: ( (include | import | redefine | annotation)*, (((simpleType | complexType | group | attributeGroup) | element | attribute | notation), annotation*)*) </schema> :param node: The XML node :type node: lxml.etree._Element """ assert node is not None # A schema should always have a targetNamespace attribute, otherwise # it is called a chameleon schema. In that case the schema will inherit # the namespace of the enclosing schema/node. tns = node.get("targetNamespace") if tns: self.document._target_namespace = tns self.document._element_form = node.get("elementFormDefault", "unqualified") self.document._attribute_form = node.get("attributeFormDefault", "unqualified") for child in node: self.process(child, parent=node) def visit_import(self, node, parent): """ Definition:: <import id = ID namespace = anyURI schemaLocation = anyURI {any attributes with non-schema Namespace}...> Content: (annotation?) </import> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ schema_node = None namespace = node.get("namespace") location = node.get("schemaLocation") if location: location = normalize_location( self.schema.settings, location, self.document._base_url ) if not namespace and not self.document._target_namespace: raise XMLParseError( "The attribute 'namespace' must be existent if the " "importing schema has no target namespace.", filename=self._document.location, sourceline=node.sourceline, ) # We found an empty <import/> statement, this needs to trigger 4.1.2 # from https://www.w3.org/TR/2012/REC-xmlschema11-1-20120405/#src-resolve # for QName resolving. # In essence this means we will resolve QNames without a namespace to no # namespace instead of the target namespace. # The following code snippet works because imports have to occur before we # visit elements. if not namespace and not location: self.document._has_empty_import = True # Check if the schema is already imported before based on the # namespace. Schema's without namespace are registered as 'None' document = self.schema.documents.get_by_namespace_and_location( namespace, location ) if document: logger.debug("Returning existing schema: %r", location) self.register_import(namespace, document) return document # Hardcode the mapping between the xml namespace and the xsd for now. # This seems to fix issues with exchange wsdl's, see #220 if not location and namespace == "http://www.w3.org/XML/1998/namespace": location = "https://www.w3.org/2001/xml.xsd" # Silently ignore import statements which we can't resolve via the # namespace and doesn't have a schemaLocation attribute. if not location: logger.debug( "Ignoring import statement for namespace %r " + "(missing schemaLocation)", namespace, ) return # Load the XML schema_node = load_external( location, transport=self.schema._transport, base_url=self.document._location, settings=self.schema.settings, ) # Check if the xsd:import namespace matches the targetNamespace. If # the xsd:import statement didn't specify a namespace then make sure # that the targetNamespace wasn't declared by another schema yet. schema_tns = schema_node.get("targetNamespace") if namespace and schema_tns and namespace != schema_tns: raise XMLParseError( ( "The namespace defined on the xsd:import doesn't match the " "imported targetNamespace located at %r " ) % (location), filename=self.document._location, sourceline=node.sourceline, ) # If the imported schema doesn't define a target namespace and the # node doesn't specify it either then inherit the existing target # namespace. elif not schema_tns and not namespace: namespace = self.document._target_namespace schema = self.schema.create_new_document( schema_node, location, target_namespace=namespace ) self.register_import(namespace, schema) return schema def visit_include(self, node, parent): """ Definition:: <include id = ID schemaLocation = anyURI {any attributes with non-schema Namespace}...> Content: (annotation?) </include> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ if not node.get("schemaLocation"): raise NotImplementedError("schemaLocation is required") location = node.get("schemaLocation") if location in self._includes: return schema_node = load_external( location, self.schema._transport, base_url=self.document._base_url, settings=self.schema.settings, ) self._includes.add(location) # When the included document has no default namespace defined but the # parent document does have this then we should (atleast for #360) # transfer the default namespace to the included schema. We can't # update the nsmap of elements in lxml so we create a new schema with # the correct nsmap and move all the content there. # Included schemas must have targetNamespace equal to parent schema (the including) or None. # If included schema doesn't have default ns, then it should be set to parent's targetNs. # See Chameleon Inclusion https://www.w3.org/TR/xmlschema11-1/#chameleon-xslt if not schema_node.nsmap.get(None) and ( node.nsmap.get(None) or parent.attrib.get("targetNamespace") ): nsmap = {None: node.nsmap.get(None) or parent.attrib["targetNamespace"]} nsmap.update(schema_node.nsmap) new = etree.Element(schema_node.tag, nsmap=nsmap) for child in schema_node: new.append(child) for key, value in schema_node.attrib.items(): new.set(key, value) if not new.attrib.get("targetNamespace"): new.attrib["targetNamespace"] = parent.attrib["targetNamespace"] schema_node = new # Use the element/attribute form defaults from the schema while # processing the nodes. element_form_default = self.document._element_form attribute_form_default = self.document._attribute_form base_url = self.document._base_url self.document._element_form = schema_node.get( "elementFormDefault", "unqualified" ) self.document._attribute_form = schema_node.get( "attributeFormDefault", "unqualified" ) self.document._base_url = absolute_location(location, self.document._base_url) # Iterate directly over the children. for child in schema_node: self.process(child, parent=schema_node) self.document._element_form = element_form_default self.document._attribute_form = attribute_form_default self.document._base_url = base_url def visit_element(self, node, parent): """ Definition:: <element abstract = Boolean : false block = (#all | List of (extension | restriction | substitution)) default = string final = (#all | List of (extension | restriction)) fixed = string form = (qualified | unqualified) id = ID maxOccurs = (nonNegativeInteger | unbounded) : 1 minOccurs = nonNegativeInteger : 1 name = NCName nillable = Boolean : false ref = QName substitutionGroup = QName type = QName {any attributes with non-schema Namespace}...> Content: (annotation?, ( (simpleType | complexType)?, (unique | key | keyref)*)) </element> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ is_global = parent.tag == tags.schema # minOccurs / maxOccurs are not allowed on global elements if not is_global: min_occurs, max_occurs = _process_occurs_attrs(node) else: max_occurs = 1 min_occurs = 1 # If the element has a ref attribute then all other attributes cannot # be present. Short circuit that here. # Ref is prohibited on global elements (parent = schema) if not is_global: # Naive workaround to mark fields which are part of a choice element # as optional if parent.tag == tags.choice: min_occurs = 0 result = self.process_reference( node, min_occurs=min_occurs, max_occurs=max_occurs ) if result: return result element_form = node.get("form", self.document._element_form) if element_form == "qualified" or is_global: qname = qname_attr(node, "name", self.document._target_namespace) else: qname = etree.QName(node.get("name").strip()) children = list(node) xsd_type = None if children: value = None for child in children: if child.tag == tags.annotation: continue elif child.tag in (tags.simpleType, tags.complexType): assert not value xsd_type = self.process(child, node) if not xsd_type: node_type = qname_attr(node, "type") if node_type: xsd_type = self._get_type(node_type.text) else: xsd_type = xsd_types.AnyType() nillable = node.get("nillable") == "true" default = node.get("default") element = xsd_elements.Element( name=qname, type_=xsd_type, min_occurs=min_occurs, max_occurs=max_occurs, nillable=nillable, default=default, is_global=is_global, ) # Only register global elements if is_global: self.register_element(qname, element) return element def visit_attribute(self, node, parent): """Declares an attribute. Definition:: <attribute default = string fixed = string form = (qualified | unqualified) id = ID name = NCName ref = QName type = QName use = (optional | prohibited | required): optional {any attributes with non-schema Namespace...}> Content: (annotation?, (simpleType?)) </attribute> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ is_global = parent.tag == tags.schema # Check of wsdl:arayType array_type = node.get("{http://schemas.xmlsoap.org/wsdl/}arrayType") if array_type: match = re.match(r"([^\[]+)", array_type) if match: array_type = match.groups()[0] qname = as_qname(array_type, node.nsmap) array_type = UnresolvedType(qname, self.schema) # If the elment has a ref attribute then all other attributes cannot # be present. Short circuit that here. # Ref is prohibited on global elements (parent = schema) if not is_global: result = self.process_ref_attribute(node, array_type=array_type) if result: return result attribute_form = node.get("form", self.document._attribute_form) if attribute_form == "qualified" or is_global: name = qname_attr(node, "name", self.document._target_namespace) else: name = etree.QName(node.get("name")) annotation, items = self._pop_annotation(list(node)) if items: xsd_type = self.visit_simple_type(items[0], node) else: node_type = qname_attr(node, "type") if node_type: xsd_type = self._get_type(node_type) else: xsd_type = xsd_types.AnyType() # TODO: We ignore 'prohobited' for now required = node.get("use") == "required" default = node.get("default") attr = xsd_elements.Attribute( name, type_=xsd_type, default=default, required=required ) # Only register global elements if is_global: self.register_attribute(name, attr) return attr def visit_simple_type(self, node, parent): """ Definition:: <simpleType final = (#all | (list | union | restriction)) id = ID name = NCName {any attributes with non-schema Namespace}...> Content: (annotation?, (restriction | list | union)) </simpleType> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ if parent.tag == tags.schema: name = node.get("name") is_global = True else: name = parent.get("name", "Anonymous") is_global = False base_type = "{http://www.w3.org/2001/XMLSchema}string" qname = as_qname(name, node.nsmap, self.document._target_namespace) annotation, items = self._pop_annotation(list(node)) child = items[0] if child.tag == tags.restriction: base_type = self.visit_restriction_simple_type(child, node) xsd_type = UnresolvedCustomType(qname, base_type, self.schema) elif child.tag == tags.list: xsd_type = self.visit_list(child, node) elif child.tag == tags.union: xsd_type = self.visit_union(child, node) else: raise AssertionError("Unexpected child: %r" % child.tag) assert xsd_type is not None if is_global: self.register_type(qname, xsd_type) return xsd_type def visit_complex_type(self, node, parent): """ Definition:: <complexType abstract = Boolean : false block = (#all | List of (extension | restriction)) final = (#all | List of (extension | restriction)) id = ID mixed = Boolean : false name = NCName {any attributes with non-schema Namespace...}> Content: (annotation?, (simpleContent | complexContent | ((group | all | choice | sequence)?, ((attribute | attributeGroup)*, anyAttribute?)))) </complexType> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ children = [] base_type = "{http://www.w3.org/2001/XMLSchema}anyType" # If the complexType's parent is an element then this type is # anonymous and should have no name defined. Otherwise it's global if parent.tag == tags.schema: name = node.get("name") is_global = True else: name = parent.get("name") is_global = False qname = as_qname(name, node.nsmap, self.document._target_namespace) cls_attributes = {"__module__": "zeep.xsd.dynamic_types", "_xsd_name": qname} xsd_cls = type(name, (xsd_types.ComplexType,), cls_attributes) xsd_type = None # Process content annotation, children = self._pop_annotation(list(node)) first_tag = children[0].tag if children else None if first_tag == tags.simpleContent: base_type, attributes = self.visit_simple_content(children[0], node) xsd_type = xsd_cls( attributes=attributes, extension=base_type, qname=qname, is_global=is_global, ) elif first_tag == tags.complexContent: kwargs = self.visit_complex_content(children[0], node) xsd_type = xsd_cls(qname=qname, is_global=is_global, **kwargs) elif first_tag: element = None if first_tag in (tags.group, tags.all, tags.choice, tags.sequence): child = children.pop(0) element = self.process(child, node) attributes = self._process_attributes(node, children) xsd_type = xsd_cls( element=element, attributes=attributes, qname=qname, is_global=is_global ) else: xsd_type = xsd_cls(qname=qname, is_global=is_global) if is_global: self.register_type(qname, xsd_type) return xsd_type def visit_complex_content(self, node, parent): """The complexContent element defines extensions or restrictions on a complex type that contains mixed content or elements only. Definition:: <complexContent id = ID mixed = Boolean {any attributes with non-schema Namespace}...> Content: (annotation?, (restriction | extension)) </complexContent> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ children = list(node) child = children[-1] if child.tag == tags.restriction: base, element, attributes = self.visit_restriction_complex_content( child, node ) return {"attributes": attributes, "element": element, "restriction": base} elif child.tag == tags.extension: base, element, attributes = self.visit_extension_complex_content( child, node ) return {"attributes": attributes, "element": element, "extension": base} def visit_simple_content(self, node, parent): """Contains extensions or restrictions on a complexType element with character data or a simpleType element as content and contains no elements. Definition:: <simpleContent id = ID {any attributes with non-schema Namespace}...> Content: (annotation?, (restriction | extension)) </simpleContent> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ children = list(node) child = children[-1] if child.tag == tags.restriction: return self.visit_restriction_simple_content(child, node) elif child.tag == tags.extension: return self.visit_extension_simple_content(child, node) raise AssertionError("Expected restriction or extension") def visit_restriction_simple_type(self, node, parent): """ Definition:: <restriction base = QName id = ID {any attributes with non-schema Namespace}...> Content: (annotation?, (simpleType?, ( minExclusive | minInclusive | maxExclusive | maxInclusive | totalDigits |fractionDigits | length | minLength | maxLength | enumeration | whiteSpace | pattern)*)) </restriction> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ base_name = qname_attr(node, "base") if base_name: return self._get_type(base_name) annotation, children = self._pop_annotation(list(node)) if children[0].tag == tags.simpleType: return self.visit_simple_type(children[0], node) def visit_restriction_simple_content(self, node, parent): """ Definition:: <restriction base = QName id = ID {any attributes with non-schema Namespace}...> Content: (annotation?, (simpleType?, ( minExclusive | minInclusive | maxExclusive | maxInclusive | totalDigits |fractionDigits | length | minLength | maxLength | enumeration | whiteSpace | pattern)* )?, ((attribute | attributeGroup)*, anyAttribute?)) </restriction> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ base_name = qname_attr(node, "base") base_type = self._get_type(base_name) return base_type, [] def visit_restriction_complex_content(self, node, parent): """ Definition:: <restriction base = QName id = ID {any attributes with non-schema Namespace}...> Content: (annotation?, (group | all | choice | sequence)?, ((attribute | attributeGroup)*, anyAttribute?)) </restriction> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ base_name = qname_attr(node, "base") base_type = self._get_type(base_name) annotation, children = self._pop_annotation(list(node)) element = None attributes = [] if children: child = children[0] if child.tag in (tags.group, tags.all, tags.choice, tags.sequence): children.pop(0) element = self.process(child, node) attributes = self._process_attributes(node, children) return base_type, element, attributes def visit_extension_complex_content(self, node, parent): """ Definition:: <extension base = QName id = ID {any attributes with non-schema Namespace}...> Content: (annotation?, ( (group | all | choice | sequence)?, ((attribute | attributeGroup)*, anyAttribute?))) </extension> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ base_name = qname_attr(node, "base") base_type = self._get_type(base_name) annotation, children = self._pop_annotation(list(node)) element = None attributes = [] if children: child = children[0] if child.tag in (tags.group, tags.all, tags.choice, tags.sequence): children.pop(0) element = self.process(child, node) attributes = self._process_attributes(node, children) return base_type, element, attributes def visit_extension_simple_content(self, node, parent): """ Definition:: <extension base = QName id = ID {any attributes with non-schema Namespace}...> Content: (annotation?, ((attribute | attributeGroup)*, anyAttribute?)) </extension> """ base_name = qname_attr(node, "base") base_type = self._get_type(base_name) annotation, children = self._pop_annotation(list(node)) attributes = self._process_attributes(node, children) return base_type, attributes def visit_annotation(self, node, parent): """Defines an annotation. Definition:: <annotation id = ID {any attributes with non-schema Namespace}...> Content: (appinfo | documentation)* </annotation> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ return def visit_any(self, node, parent): """ Definition:: <any id = ID maxOccurs = (nonNegativeInteger | unbounded) : 1 minOccurs = nonNegativeInteger : 1 namespace = "(##any | ##other) | List of (anyURI | (##targetNamespace | ##local))) : ##any processContents = (lax | skip | strict) : strict {any attributes with non-schema Namespace...}> Content: (annotation?) </any> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ min_occurs, max_occurs = _process_occurs_attrs(node) process_contents = node.get("processContents", "strict") return xsd_elements.Any( max_occurs=max_occurs, min_occurs=min_occurs, process_contents=process_contents, ) def visit_sequence(self, node, parent): """ Definition:: <sequence id = ID maxOccurs = (nonNegativeInteger | unbounded) : 1 minOccurs = nonNegativeInteger : 1 {any attributes with non-schema Namespace}...> Content: (annotation?, (element | group | choice | sequence | any)*) </sequence> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ sub_types = [ tags.annotation, tags.any, tags.choice, tags.element, tags.group, tags.sequence, ] min_occurs, max_occurs = _process_occurs_attrs(node) result = xsd_elements.Sequence(min_occurs=min_occurs, max_occurs=max_occurs) annotation, children = self._pop_annotation(list(node)) for child in children: if child.tag not in sub_types: raise self._create_error( "Unexpected element %s in xsd:sequence" % child.tag, child ) item = self.process(child, node) assert item is not None result.append(item) assert None not in result return result def visit_all(self, node, parent): """Allows the elements in the group to appear (or not appear) in any order in the containing element. Definition:: <all id = ID maxOccurs= 1: 1 minOccurs= (0 | 1): 1 {any attributes with non-schema Namespace...}> Content: (annotation?, element*) </all> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ sub_types = [tags.annotation, tags.element] result = xsd_elements.All() annotation, children = self._pop_annotation(list(node)) for child in children: assert child.tag in sub_types, child item = self.process(child, node) result.append(item) assert None not in result return result def visit_group(self, node, parent): """Groups a set of element declarations so that they can be incorporated as a group into complex type definitions. Definition:: <group name= NCName id = ID maxOccurs = (nonNegativeInteger | unbounded) : 1 minOccurs = nonNegativeInteger : 1 name = NCName ref = QName {any attributes with non-schema Namespace}...> Content: (annotation?, (all | choice | sequence)) </group> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ min_occurs, max_occurs = _process_occurs_attrs(node) result = self.process_reference( node, min_occurs=min_occurs, max_occurs=max_occurs ) if result: return result qname = qname_attr(node, "name", self.document._target_namespace) # There should be only max nodes, first node (annotation) is irrelevant annotation, children = self._pop_annotation(list(node)) child = children[0] item = self.process(child, parent) elm = xsd_elements.Group(name=qname, child=item) if parent.tag == tags.schema: self.register_group(qname, elm) return elm def visit_list(self, node, parent): """ Definition:: <list id = ID itemType = QName {any attributes with non-schema Namespace}...> Content: (annotation?, (simpleType?)) </list> The use of the simpleType element child and the itemType attribute is mutually exclusive. :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ item_type = qname_attr(node, "itemType") if item_type: sub_type = self._get_type(item_type.text) else: subnodes = list(node) child = subnodes[-1] # skip annotation sub_type = self.visit_simple_type(child, node) return xsd_types.ListType(sub_type) def visit_choice(self, node, parent): """ Definition:: <choice id = ID maxOccurs= (nonNegativeInteger | unbounded) : 1 minOccurs= nonNegativeInteger : 1 {any attributes with non-schema Namespace}...> Content: (annotation?, (element | group | choice | sequence | any)*) </choice> """ min_occurs, max_occurs = _process_occurs_attrs(node) annotation, children = self._pop_annotation(list(node)) choices = [] for child in children: elm = self.process(child, node) choices.append(elm) return xsd_elements.Choice( choices, min_occurs=min_occurs, max_occurs=max_occurs ) def visit_union(self, node, parent): """Defines a collection of multiple simpleType definitions. Definition:: <union id = ID memberTypes = List of QNames {any attributes with non-schema Namespace}...> Content: (annotation?, (simpleType*)) </union> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ # TODO members = node.get("memberTypes") types = [] if members: for member in members.split(): qname = as_qname(member, node.nsmap) xsd_type = self._get_type(qname) types.append(xsd_type) else: annotation, types = self._pop_annotation(list(node)) types = [self.visit_simple_type(t, node) for t in types] return xsd_types.UnionType(types) def visit_unique(self, node, parent): """Specifies that an attribute or element value (or a combination of attribute or element values) must be unique within the specified scope. The value must be unique or nil. Definition:: <unique id = ID name = NCName {any attributes with non-schema Namespace}...> Content: (annotation?, (selector, field+)) </unique> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ # TODO pass def visit_attribute_group(self, node, parent): """ Definition:: <attributeGroup id = ID name = NCName ref = QName {any attributes with non-schema Namespace...}> Content: (annotation?), ((attribute | attributeGroup)*, anyAttribute?)) </attributeGroup> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ ref = self.process_reference(node) if ref: return ref qname = qname_attr(node, "name", self.document._target_namespace) annotation, children = self._pop_annotation(list(node)) attributes = self._process_attributes(node, children) attribute_group = xsd_elements.AttributeGroup(qname, attributes) self.register_attribute_group(qname, attribute_group) def visit_any_attribute(self, node, parent): """ Definition:: <anyAttribute id = ID namespace = ((##any | ##other) | List of (anyURI | (##targetNamespace | ##local))) : ##any processContents = (lax | skip | strict): strict {any attributes with non-schema Namespace...}> Content: (annotation?) </anyAttribute> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ process_contents = node.get("processContents", "strict") return xsd_elements.AnyAttribute(process_contents=process_contents) def visit_notation(self, node, parent): """Contains the definition of a notation to describe the format of non-XML data within an XML document. An XML Schema notation declaration is a reconstruction of XML 1.0 NOTATION declarations. Definition:: <notation id = ID name = NCName public = Public identifier per ISO 8879 system = anyURI {any attributes with non-schema Namespace}...> Content: (annotation?) </notation> :param node: The XML node :type node: lxml.etree._Element :param parent: The parent XML node :type parent: lxml.etree._Element """ pass def _get_type(self, name): assert name is not None name = self._create_qname(name) return UnresolvedType(name, self.schema) def _create_qname(self, name): if not isinstance(name, etree.QName): name = etree.QName(name) # Handle reserved namespace if name.namespace == "xml": name = etree.QName("http://www.w3.org/XML/1998/namespace", name.localname) # Various xsd builders assume that some schema's are available by # default (actually this is mostly just the soap-enc ns). So live with # that fact and handle it by auto-importing the schema if it is # referenced. if name.namespace in AUTO_IMPORT_NAMESPACES and not self.document.is_imported( name.namespace ): logger.debug("Auto importing missing known schema: %s", name.namespace) import_node = etree.Element( tags.import_, namespace=name.namespace, schemaLocation=name.namespace ) self.visit_import(import_node, None) if ( not name.namespace and self.document._element_form == "qualified" and self.document._target_namespace and not self.document._has_empty_import ): name = etree.QName(self.document._target_namespace, name.localname) return name def _pop_annotation(self, items): if not len(items): return None, [] if items[0].tag == tags.annotation: annotation = self.visit_annotation(items[0], None) return annotation, items[1:] return None, items def _process_attributes(self, node, items): attributes = [] for child in items: if child.tag in (tags.attribute, tags.attributeGroup, tags.anyAttribute): attribute = self.process(child, node) attributes.append(attribute) else: raise self._create_error("Unexpected tag `%s`" % (child.tag), node) return attributes def _create_error(self, message, node): return XMLParseError( message, filename=self.document._location, sourceline=node.sourceline ) visitors = { tags.any: visit_any, tags.element: visit_element, tags.choice: visit_choice, tags.simpleType: visit_simple_type, tags.anyAttribute: visit_any_attribute, tags.complexType: visit_complex_type, tags.simpleContent: None, tags.complexContent: None, tags.sequence: visit_sequence, tags.all: visit_all, tags.group: visit_group, tags.attribute: visit_attribute, tags.import_: visit_import, tags.include: visit_include, tags.annotation: visit_annotation, tags.attributeGroup: visit_attribute_group, tags.notation: visit_notation, } def _process_occurs_attrs(node): """Process the min/max occurrence indicators""" max_occurs = node.get("maxOccurs", "1") min_occurs = int(node.get("minOccurs", "1")) if max_occurs == "unbounded": max_occurs = "unbounded" else: max_occurs = int(max_occurs) return min_occurs, max_occurs
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/src/zeep/xsd/visitor.py
visitor.py
import copy from collections import OrderedDict from zeep.xsd.printer import PrettyPrinter __all__ = ["AnyObject", "CompoundValue"] class AnyObject(object): """Create an any object :param xsd_object: the xsd type :param value: The value """ def __init__(self, xsd_object, value): self.xsd_obj = xsd_object self.value = value def __repr__(self): return "<%s(type=%r, value=%r)>" % ( self.__class__.__name__, self.xsd_elm, self.value, ) def __deepcopy__(self, memo): return type(self)(self.xsd_elm, copy.deepcopy(self.value)) @property def xsd_type(self): return self.xsd_obj @property def xsd_elm(self): return self.xsd_obj def _unpickle_compound_value(name, values): """Helper function to recreate pickled CompoundValue. See CompoundValue.__reduce__ """ cls = type( name, (CompoundValue,), {"_xsd_type": None, "__module__": "zeep.objects"} ) obj = cls() obj.__values__ = values return obj class ArrayValue(list): def __init__(self, items): super(ArrayValue, self).__init__(items) def as_value_object(self): anon_type = type( self.__class__.__name__, (CompoundValue,), {"_xsd_type": self._xsd_type, "__module__": "zeep.objects"}, ) return anon_type(list(self)) @classmethod def from_value_object(cls, obj): items = next(iter(obj.__values__.values())) return cls(items or []) class CompoundValue(object): """Represents a data object for a specific xsd:complexType.""" def __init__(self, *args, **kwargs): values = OrderedDict() # Can be done after unpickle if self._xsd_type is None: return # Set default values for container_name, container in self._xsd_type.elements_nested: elm_values = container.default_value if isinstance(elm_values, dict): values.update(elm_values) else: values[container_name] = elm_values # Set attributes for attribute_name, attribute in self._xsd_type.attributes: values[attribute_name] = attribute.default_value # Set elements items = _process_signature(self._xsd_type, args, kwargs) for key, value in items.items(): values[key] = value self.__values__ = values def __reduce__(self): return (_unpickle_compound_value, (self.__class__.__name__, self.__values__)) def __contains__(self, key): return self.__values__.__contains__(key) def __eq__(self, other): if self.__class__ != other.__class__: return False other_values = {key: other[key] for key in other} return other_values == self.__values__ def __len__(self): return self.__values__.__len__() def __iter__(self): return self.__values__.__iter__() def __dir__(self): return list(self.__values__.keys()) def __repr__(self): return PrettyPrinter().pformat(self.__values__) def __delitem__(self, key): return self.__values__.__delitem__(key) def __getitem__(self, key): return self.__values__[key] def __setitem__(self, key, value): self.__values__[key] = value def __setattr__(self, key, value): if key.startswith("__") or key in ("_xsd_type", "_xsd_elm"): return super(CompoundValue, self).__setattr__(key, value) self.__values__[key] = value def __getattribute__(self, key): if key.startswith("__") or key in ("_xsd_type", "_xsd_elm"): return super(CompoundValue, self).__getattribute__(key) try: return self.__values__[key] except KeyError: raise AttributeError( "%s instance has no attribute '%s'" % (self.__class__.__name__, key) ) def __deepcopy__(self, memo): new = type(self)() new.__values__ = copy.deepcopy(self.__values__) for attr, value in self.__dict__.items(): if attr != "__values__": setattr(new, attr, value) return new def __json__(self): return self.__values__ def _process_signature(xsd_type, args, kwargs): """Return a dict with the args/kwargs mapped to the field name. Special handling is done for Choice elements since we need to record which element the user intends to use. :param fields: List of tuples (name, element) :type fields: list :param args: arg tuples :type args: tuple :param kwargs: kwargs :type kwargs: dict """ result = OrderedDict() # Process the positional arguments. args is currently still modified # in-place here if args: args = list(args) num_args = len(args) index = 0 for element_name, element in xsd_type.elements_nested: values, args, index = element.parse_args(args, index) if not values: break result.update(values) for attribute_name, attribute in xsd_type.attributes: if num_args <= index: break result[attribute_name] = args[index] index += 1 if num_args > index: raise TypeError( "__init__() takes at most %s positional arguments (%s given)" % (len(result), num_args) ) # Process the named arguments (sequence/group/all/choice). The # available_kwargs set is modified in-place. available_kwargs = set(kwargs.keys()) for element_name, element in xsd_type.elements_nested: if element.accepts_multiple: values = element.parse_kwargs(kwargs, element_name, available_kwargs) else: values = element.parse_kwargs(kwargs, None, available_kwargs) if values is not None: for key, value in values.items(): if key not in result: result[key] = value # Process the named arguments for attributes if available_kwargs: for attribute_name, attribute in xsd_type.attributes: if attribute_name in available_kwargs: available_kwargs.remove(attribute_name) result[attribute_name] = kwargs[attribute_name] # _raw_elements is a special kwarg used for unexpected unparseable xml # elements (e.g. for soap:header or when strict is disabled) if "_raw_elements" in available_kwargs and kwargs["_raw_elements"]: result["_raw_elements"] = kwargs["_raw_elements"] available_kwargs.remove("_raw_elements") if available_kwargs: raise TypeError( ("%s() got an unexpected keyword argument %r. " + "Signature: `%s`") % ( xsd_type.qname or "ComplexType", next(iter(available_kwargs)), xsd_type.signature(standalone=False), ) ) return result
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/src/zeep/xsd/valueobjects.py
valueobjects.py
import copy import operator from collections import OrderedDict, defaultdict, deque from cached_property import threaded_cached_property from zeep.exceptions import UnexpectedElementError, ValidationError from zeep.xsd.const import NotSet, SkipValue from zeep.xsd.elements import Any, Element from zeep.xsd.elements.base import Base from zeep.xsd.utils import ( NamePrefixGenerator, UniqueNameGenerator, create_prefixed_name, max_occurs_iter) __all__ = ["All", "Choice", "Group", "Sequence"] class Indicator(Base): """Base class for the other indicators""" def __repr__(self): return "<%s(%s)>" % (self.__class__.__name__, super(Indicator, self).__repr__()) @property def default_value(self): values = OrderedDict( [(name, element.default_value) for name, element in self.elements] ) if self.accepts_multiple: return {"_value_1": values} return values def clone(self, name, min_occurs=1, max_occurs=1): raise NotImplementedError() class OrderIndicator(Indicator, list): """Base class for All, Choice and Sequence classes.""" name = None def __init__(self, elements=None, min_occurs=1, max_occurs=1): self.min_occurs = min_occurs self.max_occurs = max_occurs super(OrderIndicator, self).__init__() if elements is not None: self.extend(elements) def clone(self, name, min_occurs=1, max_occurs=1): return self.__class__( elements=list(self), min_occurs=min_occurs, max_occurs=max_occurs ) @threaded_cached_property def elements(self): """List of tuples containing the element name and the element""" result = [] for name, elm in self.elements_nested: if name is None: result.extend(elm.elements) else: result.append((name, elm)) return result @threaded_cached_property def elements_nested(self): """List of tuples containing the element name and the element""" result = [] generator = NamePrefixGenerator() generator_2 = UniqueNameGenerator() for elm in self: if isinstance(elm, (All, Choice, Group, Sequence)): if elm.accepts_multiple: result.append((generator.get_name(), elm)) else: for sub_name, sub_elm in elm.elements: sub_name = generator_2.create_name(sub_name) result.append((None, elm)) elif isinstance(elm, (Any, Choice)): result.append((generator.get_name(), elm)) else: name = generator_2.create_name(elm.attr_name) result.append((name, elm)) return result def accept(self, values): """Return the number of values which are accepted by this choice. If not all required elements are available then 0 is returned. """ if not self.accepts_multiple: values = [values] results = set() for value in values: num = 0 for name, element in self.elements_nested: if isinstance(element, Element): if element.name in value and value[element.name] is not None: num += 1 else: num += element.accept(value) results.add(num) return max(results) def parse_args(self, args, index=0): # If the sequence contains an choice element then we can't convert # the args to kwargs since Choice elements don't work with position # arguments for name, elm in self.elements_nested: if isinstance(elm, Choice): raise TypeError("Choice elements only work with keyword arguments") result = {} for name, element in self.elements: if index >= len(args): break result[name] = args[index] index += 1 return result, args, index def parse_kwargs(self, kwargs, name, available_kwargs): """Apply the given kwarg to the element. The available_kwargs is modified in-place. Returns a dict with the result. :param kwargs: The kwargs :type kwargs: dict :param name: The name as which this type is registered in the parent :type name: str :param available_kwargs: The kwargs keys which are still available, modified in place :type available_kwargs: set :rtype: dict """ if self.accepts_multiple: assert name if name: if name not in available_kwargs: return {} assert self.accepts_multiple # Make sure we have a list, lame lame item_kwargs = kwargs.get(name) if not isinstance(item_kwargs, list): item_kwargs = [item_kwargs] result = [] for item_value in max_occurs_iter(self.max_occurs, item_kwargs): try: item_kwargs = set(item_value.keys()) except AttributeError: raise TypeError( "A list of dicts is expected for unbounded Sequences" ) subresult = OrderedDict() for item_name, element in self.elements: value = element.parse_kwargs(item_value, item_name, item_kwargs) if value is not None: subresult.update(value) if item_kwargs: raise TypeError( ("%s() got an unexpected keyword argument %r.") % (self, list(item_kwargs)[0]) ) result.append(subresult) result = {name: result} # All items consumed if not any(filter(None, item_kwargs)): available_kwargs.remove(name) return result else: assert not self.accepts_multiple result = OrderedDict() for elm_name, element in self.elements_nested: sub_result = element.parse_kwargs(kwargs, elm_name, available_kwargs) if sub_result: result.update(sub_result) return result def resolve(self): for i, elm in enumerate(self): self[i] = elm.resolve() return self def render(self, parent, value, render_path): """Create subelements in the given parent object.""" if not isinstance(value, list): values = [value] else: values = value self.validate(values, render_path) for value in max_occurs_iter(self.max_occurs, values): for name, element in self.elements_nested: if name: if name in value: element_value = value[name] child_path = render_path + [name] else: element_value = NotSet child_path = render_path else: element_value = value child_path = render_path if element_value is SkipValue: continue if element_value is not None or not element.is_optional: element.render(parent, element_value, child_path) def validate(self, value, render_path): for item in value: if item is NotSet: raise ValidationError("No value set", path=render_path) def signature(self, schema=None, standalone=True): parts = [] for name, element in self.elements_nested: if isinstance(element, Indicator): parts.append(element.signature(schema, standalone=False)) else: value = element.signature(schema, standalone=False) parts.append("%s: %s" % (name, value)) part = ", ".join(parts) if self.accepts_multiple: return "[%s]" % (part,) return part class All(OrderIndicator): """Allows the elements in the group to appear (or not appear) in any order in the containing element. """ def __init__(self, elements=None, min_occurs=1, max_occurs=1, consume_other=False): super(All, self).__init__(elements, min_occurs, max_occurs) self._consume_other = consume_other def parse_xmlelements(self, xmlelements, schema, name=None, context=None): """Consume matching xmlelements :param xmlelements: Dequeue of XML element objects :type xmlelements: collections.deque of lxml.etree._Element :param schema: The parent XML schema :type schema: zeep.xsd.Schema :param name: The name of the parent element :type name: str :param context: Optional parsing context (for inline schemas) :type context: zeep.xsd.context.XmlParserContext :rtype: dict or None """ result = OrderedDict() expected_tags = {element.qname for __, element in self.elements} consumed_tags = set() values = defaultdict(deque) for i, elm in enumerate(xmlelements): if elm.tag in expected_tags: consumed_tags.add(i) values[elm.tag].append(elm) # Remove the consumed tags from the xmlelements for i in sorted(consumed_tags, reverse=True): del xmlelements[i] for name, element in self.elements: sub_elements = values.get(element.qname) if sub_elements: result[name] = element.parse_xmlelements( sub_elements, schema, context=context ) if self._consume_other and xmlelements: result["_raw_elements"] = list(xmlelements) xmlelements.clear() return result class Choice(OrderIndicator): """Permits one and only one of the elements contained in the group.""" def parse_args(self, args, index=0): if args: raise TypeError("Choice elements only work with keyword arguments") @property def is_optional(self): return True @property def default_value(self): return OrderedDict() def parse_xmlelements(self, xmlelements, schema, name=None, context=None): """Consume matching xmlelements :param xmlelements: Dequeue of XML element objects :type xmlelements: collections.deque of lxml.etree._Element :param schema: The parent XML schema :type schema: zeep.xsd.Schema :param name: The name of the parent element :type name: str :param context: Optional parsing context (for inline schemas) :type context: zeep.xsd.context.XmlParserContext :rtype: dict or None """ result = [] for _unused in max_occurs_iter(self.max_occurs): if not xmlelements: break # Choose out of multiple options = [] for element_name, element in self.elements_nested: local_xmlelements = copy.copy(xmlelements) try: sub_result = element.parse_xmlelements( xmlelements=local_xmlelements, schema=schema, name=element_name, context=context, ) except UnexpectedElementError: continue if isinstance(element, Element): sub_result = {element_name: sub_result} num_consumed = len(xmlelements) - len(local_xmlelements) if num_consumed: options.append((num_consumed, sub_result)) if not options: xmlelements = [] break # Sort on least left options = sorted(options, key=operator.itemgetter(0), reverse=True) if options: result.append(options[0][1]) for i in range(options[0][0]): xmlelements.popleft() else: break if self.accepts_multiple: result = {name: result} else: result = result[0] if result else {} return result def parse_kwargs(self, kwargs, name, available_kwargs): """Processes the kwargs for this choice element. Returns a dict containing the values found. This handles two distinct initialization methods: 1. Passing the choice elements directly to the kwargs (unnested) 2. Passing the choice elements into the `name` kwarg (_value_1) (nested). This case is required when multiple choice elements are given. :param name: Name of the choice element (_value_1) :type name: str :param element: Choice element object :type element: zeep.xsd.Choice :param kwargs: dict (or list of dicts) of kwargs for initialization :type kwargs: list / dict """ if name and name in available_kwargs: assert self.accepts_multiple values = kwargs[name] or [] available_kwargs.remove(name) result = [] if isinstance(values, dict): values = [values] # TODO: Use most greedy choice instead of first matching for value in values: for element in self: if isinstance(element, OrderIndicator): choice_value = value[name] if name in value else value if element.accept(choice_value): result.append(choice_value) break else: if isinstance(element, Any): result.append(value) break elif element.name in value: choice_value = value.get(element.name) result.append({element.name: choice_value}) break else: raise TypeError( "No complete xsd:Sequence found for the xsd:Choice %r.\n" "The signature is: %s" % (name, self.signature()) ) if not self.accepts_multiple: result = result[0] if result else None else: # Direct use-case isn't supported when maxOccurs > 1 if self.accepts_multiple: return {} result = {} # When choice elements are specified directly in the kwargs found = False for name, choice in self.elements_nested: temp_kwargs = copy.copy(available_kwargs) subresult = choice.parse_kwargs(kwargs, name, temp_kwargs) if subresult: if not any(subresult.values()): available_kwargs.intersection_update(temp_kwargs) result.update(subresult) elif not found: available_kwargs.intersection_update(temp_kwargs) result.update(subresult) found = True if found: for choice_name, choice in self.elements: result.setdefault(choice_name, None) else: result = {} if name and self.accepts_multiple: result = {name: result} return result def render(self, parent, value, render_path): """Render the value to the parent element tree node. This is a bit more complex then the order render methods since we need to search for the best matching choice element. """ if not self.accepts_multiple: value = [value] self.validate(value, render_path) for item in value: result = self._find_element_to_render(item) if result: element, choice_value = result element.render(parent, choice_value, render_path) def validate(self, value, render_path): found = 0 for item in value: result = self._find_element_to_render(item) if result: found += 1 if not found and not self.is_optional: raise ValidationError("Missing choice values", path=render_path) def accept(self, values): """Return the number of values which are accepted by this choice. If not all required elements are available then 0 is returned. """ nums = set() for name, element in self.elements_nested: if isinstance(element, Element): if self.accepts_multiple: if all(name in item and item[name] for item in values): nums.add(1) else: if name in values and values[name]: nums.add(1) else: num = element.accept(values) nums.add(num) return max(nums) if nums else 0 def _find_element_to_render(self, value): """Return a tuple (element, value) for the best matching choice. This is used to decide which choice child is best suitable for rendering the available data. """ matches = [] for name, element in self.elements_nested: if isinstance(element, Element): if element.name in value: try: choice_value = value[element.name] except KeyError: choice_value = value if choice_value is not None: matches.append((1, element, choice_value)) else: if name is not None: try: choice_value = value[name] except (KeyError, TypeError): choice_value = value else: choice_value = value score = element.accept(choice_value) if score: matches.append((score, element, choice_value)) if matches: matches = sorted(matches, key=operator.itemgetter(0), reverse=True) return matches[0][1:] def signature(self, schema=None, standalone=True): parts = [] for name, element in self.elements_nested: if isinstance(element, OrderIndicator): parts.append("{%s}" % (element.signature(schema, standalone=False))) else: parts.append( "{%s: %s}" % (name, element.signature(schema, standalone=False)) ) part = "(%s)" % " | ".join(parts) if self.accepts_multiple: return "%s[]" % (part,) return part class Sequence(OrderIndicator): """Requires the elements in the group to appear in the specified sequence within the containing element. """ def parse_xmlelements(self, xmlelements, schema, name=None, context=None): """Consume matching xmlelements :param xmlelements: Dequeue of XML element objects :type xmlelements: collections.deque of lxml.etree._Element :param schema: The parent XML schema :type schema: zeep.xsd.Schema :param name: The name of the parent element :type name: str :param context: Optional parsing context (for inline schemas) :type context: zeep.xsd.context.XmlParserContext :rtype: dict or None """ result = [] if self.accepts_multiple: assert name for _unused in max_occurs_iter(self.max_occurs): if not xmlelements: break item_result = OrderedDict() for elm_name, element in self.elements: try: item_subresult = element.parse_xmlelements( xmlelements, schema, name, context=context ) except UnexpectedElementError: if schema.settings.strict: raise item_subresult = None # Unwrap if allowed if isinstance(element, OrderIndicator): item_result.update(item_subresult) else: item_result[elm_name] = item_subresult if not xmlelements: break if item_result: result.append(item_result) if not self.accepts_multiple: return result[0] if result else None return {name: result} class Group(Indicator): """Groups a set of element declarations so that they can be incorporated as a group into complex type definitions. """ def __init__(self, name, child, max_occurs=1, min_occurs=1): super(Group, self).__init__() self.child = child self.qname = name self.name = name.localname if name else None self.max_occurs = max_occurs self.min_occurs = min_occurs def __str__(self): return self.signature() def __iter__(self, *args, **kwargs): for item in self.child: yield item @threaded_cached_property def elements(self): if self.accepts_multiple: return [("_value_1", self.child)] return self.child.elements def clone(self, name, min_occurs=1, max_occurs=1): return self.__class__( name=None, child=self.child, min_occurs=min_occurs, max_occurs=max_occurs ) def accept(self, values): """Return the number of values which are accepted by this choice. If not all required elements are available then 0 is returned. """ return self.child.accept(values) def parse_args(self, args, index=0): return self.child.parse_args(args, index) def parse_kwargs(self, kwargs, name, available_kwargs): if self.accepts_multiple: if name not in kwargs: return {} available_kwargs.remove(name) item_kwargs = kwargs[name] result = [] sub_name = "_value_1" if self.child.accepts_multiple else None for sub_kwargs in max_occurs_iter(self.max_occurs, item_kwargs): available_sub_kwargs = set(sub_kwargs.keys()) subresult = self.child.parse_kwargs( sub_kwargs, sub_name, available_sub_kwargs ) if available_sub_kwargs: raise TypeError( ("%s() got an unexpected keyword argument %r.") % (self, list(available_sub_kwargs)[0]) ) if subresult: result.append(subresult) if result: result = {name: result} else: result = self.child.parse_kwargs(kwargs, name, available_kwargs) return result def parse_xmlelements(self, xmlelements, schema, name=None, context=None): """Consume matching xmlelements :param xmlelements: Dequeue of XML element objects :type xmlelements: collections.deque of lxml.etree._Element :param schema: The parent XML schema :type schema: zeep.xsd.Schema :param name: The name of the parent element :type name: str :param context: Optional parsing context (for inline schemas) :type context: zeep.xsd.context.XmlParserContext :rtype: dict or None """ result = [] for _unused in max_occurs_iter(self.max_occurs): result.append( self.child.parse_xmlelements(xmlelements, schema, name, context=context) ) if not xmlelements: break if not self.accepts_multiple and result: return result[0] return {name: result} def render(self, parent, value, render_path): if not isinstance(value, list): values = [value] else: values = value for value in values: self.child.render(parent, value, render_path) def resolve(self): self.child = self.child.resolve() return self def signature(self, schema=None, standalone=True): name = create_prefixed_name(self.qname, schema) if standalone: return "%s(%s)" % (name, self.child.signature(schema, standalone=False)) else: return self.child.signature(schema, standalone=False)
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/src/zeep/xsd/elements/indicators.py
indicators.py
import logging from lxml import etree from zeep import exceptions, ns from zeep.utils import qname_attr from zeep.xsd.const import NotSet, xsi_ns from zeep.xsd.elements.base import Base from zeep.xsd.utils import max_occurs_iter from zeep.xsd.valueobjects import AnyObject logger = logging.getLogger(__name__) __all__ = ["Any", "AnyAttribute"] class Any(Base): name = None def __init__( self, max_occurs=1, min_occurs=1, process_contents="strict", restrict=None ): """ :param process_contents: Specifies how the XML processor should handle validation against the elements specified by this any element :type process_contents: str (strict, lax, skip) """ super(Any, self).__init__() self.max_occurs = max_occurs self.min_occurs = min_occurs self.restrict = restrict self.process_contents = process_contents # cyclic import from zeep.xsd import AnyType self.type = AnyType() def __call__(self, any_object): return any_object def __repr__(self): return "<%s(name=%r)>" % (self.__class__.__name__, self.name) def accept(self, value): return True def parse(self, xmlelement, schema, context=None): if self.process_contents == "skip": return xmlelement # If a schema was passed inline then check for a matching one qname = etree.QName(xmlelement.tag) if context and context.schemas: for context_schema in context.schemas: if context_schema.documents.has_schema_document_for_ns(qname.namespace): schema = context_schema break else: # Try to parse the any result by iterating all the schemas for context_schema in context.schemas: try: data = context_schema.deserialize(list(xmlelement)[0]) return data except LookupError: continue # Lookup type via xsi:type attribute xsd_type = qname_attr(xmlelement, xsi_ns("type")) if xsd_type is not None: xsd_type = schema.get_type(xsd_type) return xsd_type.parse_xmlelement(xmlelement, schema, context=context) # Check if a restrict is used if self.restrict: return self.restrict.parse_xmlelement(xmlelement, schema, context=context) try: element = schema.get_element(xmlelement.tag) return element.parse(xmlelement, schema, context=context) except (exceptions.NamespaceError, exceptions.LookupError): return xmlelement def parse_kwargs(self, kwargs, name, available_kwargs): if name in available_kwargs: available_kwargs.remove(name) value = kwargs[name] return {name: value} return {} def parse_xmlelements(self, xmlelements, schema, name=None, context=None): """Consume matching xmlelements and call parse() on each of them :param xmlelements: Dequeue of XML element objects :type xmlelements: collections.deque of lxml.etree._Element :param schema: The parent XML schema :type schema: zeep.xsd.Schema :param name: The name of the parent element :type name: str :param context: Optional parsing context (for inline schemas) :type context: zeep.xsd.context.XmlParserContext :return: dict or None """ result = [] for _unused in max_occurs_iter(self.max_occurs): if xmlelements: xmlelement = xmlelements.popleft() item = self.parse(xmlelement, schema, context=context) if item is not None: result.append(item) else: break if not self.accepts_multiple: result = result[0] if result else None return result def render(self, parent, value, render_path=None): assert parent is not None self.validate(value, render_path) if self.accepts_multiple and isinstance(value, list): from zeep.xsd import AnySimpleType if isinstance(self.restrict, AnySimpleType): for val in value: node = etree.SubElement(parent, "item") node.set(xsi_ns("type"), self.restrict.qname) self._render_value_item(node, val, render_path) elif self.restrict: for val in value: node = etree.SubElement(parent, self.restrict.name) # node.set(xsi_ns('type'), self.restrict.qname) self._render_value_item(node, val, render_path) else: for val in value: self._render_value_item(parent, val, render_path) else: self._render_value_item(parent, value, render_path) def _render_value_item(self, parent, value, render_path): if value in (None, NotSet): # can be an lxml element return elif isinstance(value, etree._Element): parent.append(value) elif self.restrict: if isinstance(value, list): for val in value: self.restrict.render(parent, val, None, render_path) else: self.restrict.render(parent, value, None, render_path) else: if isinstance(value.value, list): for val in value.value: value.xsd_elm.render(parent, val, render_path) else: value.xsd_elm.render(parent, value.value, render_path) def validate(self, value, render_path): if self.accepts_multiple and isinstance(value, list): # Validate bounds if len(value) < self.min_occurs: raise exceptions.ValidationError( "Expected at least %d items (minOccurs check)" % self.min_occurs ) if self.max_occurs != "unbounded" and len(value) > self.max_occurs: raise exceptions.ValidationError( "Expected at most %d items (maxOccurs check)" % self.min_occurs ) for val in value: self._validate_item(val, render_path) else: if not self.is_optional and value in (None, NotSet): raise exceptions.ValidationError("Missing element for Any") self._validate_item(value, render_path) def _validate_item(self, value, render_path): if value is None: # can be an lxml element return # Check if we received a proper value object. If we receive the wrong # type then return a nice error message if self.restrict: expected_types = (etree._Element, dict) + self.restrict.accepted_types else: expected_types = (etree._Element, dict, AnyObject) if value in (None, NotSet): if not self.is_optional: raise exceptions.ValidationError( "Missing element %s" % (self.name), path=render_path ) elif not isinstance(value, expected_types): type_names = ["%s.%s" % (t.__module__, t.__name__) for t in expected_types] err_message = "Any element received object of type %r, expected %s" % ( type(value).__name__, " or ".join(type_names), ) raise TypeError( "\n".join( ( err_message, "See http://docs.python-zeep.org/en/master/datastructures.html" "#any-objects for more information", ) ) ) def resolve(self): return self def signature(self, schema=None, standalone=True): if self.restrict: base = self.restrict.name else: base = "ANY" if self.accepts_multiple: return "%s[]" % base return base class AnyAttribute(Base): name = None _ignore_attributes = [etree.QName(ns.XSI, "type")] def __init__(self, process_contents="strict"): self.qname = None self.process_contents = process_contents def parse(self, attributes, context=None): result = {} for key, value in attributes.items(): if key not in self._ignore_attributes: result[key] = value return result def resolve(self): return self def render(self, parent, value, render_path=None): if value in (None, NotSet): return for name, val in value.items(): parent.set(name, val) def signature(self, schema=None, standalone=True): return "{}"
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/src/zeep/xsd/elements/any.py
any.py
import copy import logging from lxml import etree from zeep import exceptions from zeep.exceptions import UnexpectedElementError from zeep.utils import qname_attr from zeep.xsd.const import Nil, NotSet, xsi_ns from zeep.xsd.context import XmlParserContext from zeep.xsd.elements.base import Base from zeep.xsd.utils import create_prefixed_name, max_occurs_iter logger = logging.getLogger(__name__) __all__ = ["Element"] class Element(Base): def __init__( self, name, type_=None, min_occurs=1, max_occurs=1, nillable=False, default=None, is_global=False, attr_name=None, ): if name is None: raise ValueError("name cannot be None", self.__class__) if not isinstance(name, etree.QName): name = etree.QName(name) self.name = name.localname if name else None self.qname = name self.type = type_ self.min_occurs = min_occurs self.max_occurs = max_occurs self.nillable = nillable self.is_global = is_global self.default = default self.attr_name = attr_name or self.name # assert type_ def __str__(self): if self.type: if self.type.is_global: return "%s(%s)" % (self.name, self.type.qname) else: return "%s(%s)" % (self.name, self.type.signature()) return "%s()" % self.name def __call__(self, *args, **kwargs): instance = self.type(*args, **kwargs) if hasattr(instance, "_xsd_type"): instance._xsd_elm = self return instance def __repr__(self): return "<%s(name=%r, type=%r)>" % ( self.__class__.__name__, self.name, self.type, ) def __eq__(self, other): return ( other is not None and self.__class__ == other.__class__ and self.__dict__ == other.__dict__ ) def get_prefixed_name(self, schema): return create_prefixed_name(self.qname, schema) @property def default_value(self): if self.accepts_multiple: return [] if self.is_optional: return None return self.default def clone(self, name=None, min_occurs=1, max_occurs=1): new = copy.copy(self) if name: if not isinstance(name, etree.QName): name = etree.QName(name) new.name = name.localname new.qname = name new.attr_name = new.name new.min_occurs = min_occurs new.max_occurs = max_occurs return new def parse(self, xmlelement, schema, allow_none=False, context=None): """Process the given xmlelement. If it has an xsi:type attribute then use that for further processing. This should only be done for subtypes of the defined type but for now we just accept everything. This is the entrypoint for parsing an xml document. :param xmlelement: The XML element to parse :type xmlelements: lxml.etree._Element :param schema: The parent XML schema :type schema: zeep.xsd.Schema :param allow_none: Allow none :type allow_none: bool :param context: Optional parsing context (for inline schemas) :type context: zeep.xsd.context.XmlParserContext :return: dict or None """ context = context or XmlParserContext() instance_type = qname_attr(xmlelement, xsi_ns("type")) xsd_type = None if instance_type: xsd_type = schema.get_type(instance_type, fail_silently=True) xsd_type = xsd_type or self.type return xsd_type.parse_xmlelement( xmlelement, schema, allow_none=allow_none, context=context, schema_type=self.type, ) def parse_kwargs(self, kwargs, name, available_kwargs): return self.type.parse_kwargs(kwargs, name or self.attr_name, available_kwargs) def parse_xmlelements(self, xmlelements, schema, name=None, context=None): """Consume matching xmlelements and call parse() on each of them :param xmlelements: Dequeue of XML element objects :type xmlelements: collections.deque of lxml.etree._Element :param schema: The parent XML schema :type schema: zeep.xsd.Schema :param name: The name of the parent element :type name: str :param context: Optional parsing context (for inline schemas) :type context: zeep.xsd.context.XmlParserContext :return: dict or None """ result = [] num_matches = 0 for _unused in max_occurs_iter(self.max_occurs): if not xmlelements: break # Workaround for SOAP servers which incorrectly use unqualified # or qualified elements in the responses (#170, #176). To make the # best of it we compare the full uri's if both elements have a # namespace. If only one has a namespace then only compare the # localname. # If both elements have a namespace and they don't match then skip element_tag = etree.QName(xmlelements[0].tag) if ( element_tag.namespace and self.qname.namespace and element_tag.namespace != self.qname.namespace and schema.settings.strict ): break # Only compare the localname if element_tag.localname == self.qname.localname: xmlelement = xmlelements.popleft() num_matches += 1 item = self.parse(xmlelement, schema, allow_none=True, context=context) result.append(item) elif ( schema is not None and schema.settings.xsd_ignore_sequence_order and list( filter( lambda elem: etree.QName(elem.tag).localname == self.qname.localname, xmlelements, ) ) ): # Search for the field in remaining elements, not only the leftmost xmlelement = list( filter( lambda elem: etree.QName(elem.tag).localname == self.qname.localname, xmlelements, ) )[0] xmlelements.remove(xmlelement) num_matches += 1 item = self.parse(xmlelement, schema, allow_none=True, context=context) result.append(item) else: # If the element passed doesn't match and the current one is # not optional then throw an error if num_matches == 0 and not self.is_optional: raise UnexpectedElementError( "Unexpected element %r, expected %r" % (element_tag.text, self.qname.text) ) break if not self.accepts_multiple: result = result[0] if result else None return result def render(self, parent, value, render_path=None): """Render the value(s) on the parent lxml.Element. This actually just calls _render_value_item for each value. """ if not render_path: render_path = [self.qname.localname] assert parent is not None self.validate(value, render_path) if self.accepts_multiple and isinstance(value, list): for val in value: self._render_value_item(parent, val, render_path) else: self._render_value_item(parent, value, render_path) def _render_value_item(self, parent, value, render_path): """Render the value on the parent lxml.Element""" if value is Nil: elm = etree.SubElement(parent, self.qname) elm.set(xsi_ns("nil"), "true") return if value is None or value is NotSet: if self.is_optional: return elm = etree.SubElement(parent, self.qname) if self.nillable: elm.set(xsi_ns("nil"), "true") return node = etree.SubElement(parent, self.qname) xsd_type = getattr(value, "_xsd_type", self.type) if xsd_type != self.type: return value._xsd_type.render(node, value, xsd_type, render_path) return self.type.render(node, value, None, render_path) def validate(self, value, render_path=None): """Validate that the value is valid""" if self.accepts_multiple and isinstance(value, list): # Validate bounds if len(value) < self.min_occurs: raise exceptions.ValidationError( "Expected at least %d items (minOccurs check) %d items found." % (self.min_occurs, len(value)), path=render_path, ) elif self.max_occurs != "unbounded" and len(value) > self.max_occurs: raise exceptions.ValidationError( "Expected at most %d items (maxOccurs check) %d items found." % (self.max_occurs, len(value)), path=render_path, ) for val in value: self._validate_item(val, render_path) else: if not self.is_optional and not self.nillable and value in (None, NotSet): raise exceptions.ValidationError( "Missing element %s" % (self.name), path=render_path ) self._validate_item(value, render_path) def _validate_item(self, value, render_path): if self.nillable and value in (None, NotSet): return try: self.type.validate(value, required=True) except exceptions.ValidationError as exc: raise exceptions.ValidationError( "The element %s is not valid: %s" % (self.qname, exc.message), path=render_path, ) def resolve_type(self): self.type = self.type.resolve() def resolve(self): self.resolve_type() return self def signature(self, schema=None, standalone=True): from zeep.xsd import ComplexType if self.type.is_global or (not standalone and self.is_global): value = self.type.get_prefixed_name(schema) else: value = self.type.signature(schema, standalone=False) if not standalone and isinstance(self.type, ComplexType): value = "{%s}" % value if standalone: value = "%s(%s)" % (self.get_prefixed_name(schema), value) if self.accepts_multiple: return "%s[]" % value return value
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/src/zeep/xsd/elements/element.py
element.py
import logging from lxml import etree from zeep import exceptions from zeep.xsd.const import NotSet from zeep.xsd.elements.element import Element logger = logging.getLogger(__name__) __all__ = ["Attribute", "AttributeGroup"] class Attribute(Element): def __init__(self, name, type_=None, required=False, default=None): super(Attribute, self).__init__(name=name, type_=type_, default=default) self.required = required self.array_type = None def parse(self, value): try: return self.type.pythonvalue(value) except (TypeError, ValueError): logger.exception("Error during xml -> python translation") return None def render(self, parent, value, render_path=None): if value in (None, NotSet) and not self.required: return self.validate(value, render_path) value = self.type.xmlvalue(value) parent.set(self.qname, value) def validate(self, value, render_path): try: self.type.validate(value, required=self.required) except exceptions.ValidationError as exc: raise exceptions.ValidationError( "The attribute %s is not valid: %s" % (self.qname, exc.message), path=render_path, ) def clone(self, *args, **kwargs): array_type = kwargs.pop("array_type", None) new = super(Attribute, self).clone(*args, **kwargs) new.array_type = array_type return new def resolve(self): retval = super(Attribute, self).resolve() self.type = self.type.resolve() if self.array_type: retval.array_type = self.array_type.resolve() return retval class AttributeGroup(object): def __init__(self, name, attributes): if not isinstance(name, etree.QName): name = etree.QName(name) self.name = name.localname self.qname = name self.type = None self._attributes = attributes self.is_global = True @property def attributes(self): result = [] for attr in self._attributes: if isinstance(attr, AttributeGroup): result.extend(attr.attributes) else: result.append(attr) return result def resolve(self): resolved = [] for attribute in self._attributes: value = attribute.resolve() assert value is not None if isinstance(value, list): resolved.extend(value) else: resolved.append(value) self._attributes = resolved return self def signature(self, schema=None, standalone=True): return ", ".join(attr.signature(schema) for attr in self._attributes)
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/src/zeep/xsd/elements/attribute.py
attribute.py
import logging import six from lxml import etree from zeep.exceptions import ValidationError from zeep.xsd.const import Nil, xsd_ns, xsi_ns from zeep.xsd.types.any import AnyType logger = logging.getLogger(__name__) __all__ = ["AnySimpleType"] @six.python_2_unicode_compatible class AnySimpleType(AnyType): _default_qname = xsd_ns("anySimpleType") def __init__(self, qname=None, is_global=False): super(AnySimpleType, self).__init__( qname or etree.QName(self._default_qname), is_global ) def __call__(self, *args, **kwargs): """Return the xmlvalue for the given value. Expects only one argument 'value'. The args, kwargs handling is done here manually so that we can return readable error messages instead of only '__call__ takes x arguments' """ num_args = len(args) + len(kwargs) if num_args != 1: raise TypeError( ( "%s() takes exactly 1 argument (%d given). " + "Simple types expect only a single value argument" ) % (self.__class__.__name__, num_args) ) if kwargs and "value" not in kwargs: raise TypeError( ( "%s() got an unexpected keyword argument %r. " + "Simple types expect only a single value argument" ) % (self.__class__.__name__, next(six.iterkeys(kwargs))) ) value = args[0] if args else kwargs["value"] return self.xmlvalue(value) def __eq__(self, other): return ( other is not None and self.__class__ == other.__class__ and self.__dict__ == other.__dict__ ) def __str__(self): return "%s(value)" % (self.__class__.__name__) def parse_xmlelement( self, xmlelement, schema=None, allow_none=True, context=None, schema_type=None ): if xmlelement.text is None: return try: return self.pythonvalue(xmlelement.text) except (TypeError, ValueError): logger.exception("Error during xml -> python translation") return None def pythonvalue(self, value, schema=None): return value def render(self, parent, value, xsd_type=None, render_path=None): if value is Nil: parent.set(xsi_ns("nil"), "true") return parent.text = self.xmlvalue(value) def signature(self, schema=None, standalone=True): return self.get_prefixed_name(schema) def validate(self, value, required=False): if required and value is None: raise ValidationError("Value is required")
zeep-roboticia
/zeep-roboticia-3.4.0.tar.gz/zeep-roboticia-3.4.0/src/zeep/xsd/types/simple.py
simple.py