def __init__( self, location, transport: typing.Type["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, str): 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 = ( {} ) # type: typing.Dict[typing.Tuple[str, str], "Definition"] self.types = Schema( node=None, transport=self.transport, location=self.location, settings=self.settings, ) self.load(location)
def __init__( self, wsdl, wsse=None, wsse_verify=True, 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 self._default_transport() ) self.wsdl = Document(wsdl, self.transport, settings=self.settings) self.wsse = wsse self.wsse_verify = wsse_verify 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
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 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 getRpoInfo(Barcode): url = 'https://tracking.russianpost.ru/rtm34?wsdl' settings = Settings(strict=False, xml_huge_tree=True) client = Client(url, settings=settings) barcode = str(Barcode) print("Вы ввели: " + barcode) my_login = os.environ.get('RPO_LOGIN') my_password = os.environ.get('RPO_PASS') result = client.service.getOperationHistory(OperationHistoryRequest={ 'Barcode': barcode, 'MessageType': 0 }, AuthorizationHeader={ 'login': my_login, 'password': my_password }) myans = '' for rec in result: myans += '\n' + (str(rec.OperationParameters.OperDate) + ', ' + rec.AddressParameters.OperationAddress.Description + ', ' + rec.OperationParameters.OperAttr.Name) return myans
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 test_huge_text(): # libxml2>=2.7.3 has XML_MAX_TEXT_LENGTH 10000000 without XML_PARSE_HUGE settings = Settings(xml_huge_tree=True) tree = parse_xml(u""" <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <s:Body> <HugeText xmlns="http://hugetext">%s</HugeText> </s:Body> </s:Envelope> """ % (u'\u00e5' * 10000001), DummyTransport(), settings=settings) assert tree[0][0].text == u'\u00e5' * 10000001
def test_allow_entities_and_dtd(): xml = u""" <!DOCTYPE Author [ <!ENTITY writer "Donald Duck."> ]> <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <s:Body> <Author>&writer;</Author> </s:Body> </s:Envelope> """ # DTD is allowed by default in defusexml so we follow this behaviour with pytest.raises(DTDForbidden): parse_xml(xml, DummyTransport(), settings=Settings(forbid_dtd=True)) with pytest.raises(EntitiesForbidden): parse_xml(xml, DummyTransport()) tree = parse_xml(xml, DummyTransport(), settings=Settings(forbid_entities=False)) assert tree[0][0].tag == "Author"
def test_settings_set_context_raw_response(): settings = Settings() assert settings.raw_response is False with settings(raw_response=True): assert settings.raw_response is True with settings(): # Check that raw_response is not changed by default value assert settings.raw_response is True # Check that the original value returned assert settings.raw_response is False
def test_settings_set_context_with_exception(): settings = Settings() assert settings.raw_response is False try: with settings(raw_response=True): assert settings.raw_response is True raise RuntimeError except RuntimeError: pass # Check that the original value returned assert settings.raw_response is False
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()
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()
def on_input(servicename): service_name = servicename wsdl = api.config.wsdl strict = api.config.strict xml_huge_tree = api.config.xmlHugeTree setting = None try: setting = Settings(strict=strict, xml_huge_tree=xml_huge_tree) except Exception as other: api.send("debug", str(other)) port_name = None if api.config.portName: port_name = api.config.portName op_name = None if api.config.operationName: op_name = api.config.operationName op_params = None try: if api.config.operationParameters: op_params = api.config.operationParameters.split(',') except Exception as other: api.send("debug", str(other)) transport = populate_transport() lst_normalized_header = populate_soap_header() try: client = Client(wsdl=wsdl, transport=transport, service_name=service_name, port_name=port_name, settings=setting) if op_name: response = client.service[op_name]( *op_params, _soapheaders=lst_normalized_header) api.send("response", str(response)) else: api.send("debug", 'No Operation Name specified!') except Exception as other: api.send("debug", str(other))
def createWSClient(wsdl, username, password, proxy): session = Session() session.verify = CA proxies = {'http': proxy, 'https': proxy} session.proxies = proxies transport = Transport(session=session) settings = Settings(xml_huge_tree=True) try: client = Client(wsdl=wsdl, wsse=UsernameToken(username, password), transport=transport, settings=settings) except Exception as e: logger.error(e) sys.exit(1) return client
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 parse_xml(content: str, 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 = XMLParser( remove_comments=True, resolve_entities=False, recover=recover, huge_tree=settings.xml_huge_tree, ) parser.resolvers.add(ImportResolver(transport)) try: elementtree = fromstring(content, parser=parser, base_url=base_url) docinfo = elementtree.getroottree().docinfo if docinfo.doctype: if settings.forbid_dtd: raise DTDForbidden(docinfo.doctype, docinfo.system_url, docinfo.public_id) if settings.forbid_entities: for dtd in docinfo.internalDTD, docinfo.externalDTD: if dtd is None: continue for entity in dtd.iterentities(): raise EntitiesForbidden(entity.name, entity.content) return elementtree except etree.XMLSyntaxError as exc: raise XMLSyntaxError("Invalid XML content received (%s)" % exc.msg, content=content)
def test_xml_sequence_recover_from_missing_element(): schema = xsd.Schema( load_xml( """ <schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://tests.python-zeep.org/" elementFormDefault="qualified" targetNamespace="http://tests.python-zeep.org/"> <complexType name="container"> <sequence> <element name="item_1" type="xsd:string"/> <element name="item_2" type="xsd:string"/> <element name="item_3" type="xsd:string"/> <element name="item_4" type="xsd:string"/> </sequence> </complexType> </schema> """ ), settings=Settings(strict=False), ) xml = load_xml( """ <tns:container xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tns="http://tests.python-zeep.org/"> <tns:item_1>text-1</tns:item_1> <tns:item_3>text-3</tns:item_3> <tns:item_4>text-4</tns:item_4> </tns:container> """ ) elm_type = schema.get_type("{http://tests.python-zeep.org/}container") result = elm_type.parse_xmlelement(xml, schema) assert result.item_1 == "text-1" assert result.item_2 is None assert result.item_3 == "text-3" assert result.item_4 == "text-4"
async def initialize(self) -> bool: try: logging.getLogger('urllib3.connectionpool').setLevel(logging.WARNING) logging.getLogger('zeep.wsdl.wsdl').setLevel(logging.WARNING) logging.getLogger('zeep.xsd.schema').setLevel(logging.WARNING) logging.getLogger('zeep.transports').setLevel(logging.WARNING) self.__server_url = f"{self.server_address}" self.logger.info( f"Trying to connect.\nURL: {self.__server_url}\nClient supported protocols: {json.dumps(self.protocols)}" ) wsdl_file_path = f"{os.path.dirname(os.path.realpath(__file__))}/wsdl/server-201206.wsdl" self._client = Client( wsdl=wsdl_file_path, settings=Settings( raw_response=False, ), plugins=[WsAddressingExtensionPlugin(self.from_address)] ) self._client_service = self._client.create_service( '{urn://Ocpp/Cs/2012/06/}CentralSystemServiceSoap', self.__server_url ) await asyncio.sleep(1) if self.register_on_initialize: await self.action_register() await self.action_heart_beat() return True except ValueError as err: await self.handle_error(ErrorMessage(err).get(), ErrorReasons.InvalidResponse) return False except BaseException as err: await self.handle_error(ErrorMessage(err).get(), ErrorReasons.InvalidResponse) return False
def test_force_wsa_soap12(recwarn, monkeypatch): monkeypatch.setattr( uuid, 'uuid4', lambda: uuid.UUID('ada686f9-5995-4088-bea4-239f694b2eaf')) wsdl_main = StringIO(""" <?xml version="1.0"?> <wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://tests.python-zeep.org/xsd-main" xmlns:sec="http://tests.python-zeep.org/wsdl-secondary" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap12/" targetNamespace="http://tests.python-zeep.org/xsd-main"> <wsdl:types> <xsd:schema targetNamespace="http://tests.python-zeep.org/xsd-main" xmlns:tns="http://tests.python-zeep.org/xsd-main"> <xsd:element name="input" type="xsd:string"/> <xsd:element name="input2" type="xsd:string"/> </xsd:schema> </wsdl:types> <wsdl:message name="dummyRequest"> <wsdl:part name="response" element="tns:input"/> </wsdl:message> <wsdl:message name="dummyResponse"> <wsdl:part name="response" element="tns:input2"/> </wsdl:message> <wsdl:portType name="TestPortType"> <wsdl:operation name="TestOperation1"> <wsdl:input message="dummyRequest"/> <wsdl:output message="dummyResponse"/> </wsdl:operation> </wsdl:portType> <wsdl:binding name="TestBinding" type="tns:TestPortType"> <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> <wsdl:operation name="TestOperation1"> <soap:operation soapAction="urn:dummyRequest"/> <wsdl:input> <soap:body use="literal"/> </wsdl:input> <wsdl:output> <soap:body use="literal"/> </wsdl:output> </wsdl:operation> </wsdl:binding> <wsdl:service name="TestService"> <wsdl:documentation>Test service</wsdl:documentation> <wsdl:port name="TestPortType" binding="tns:TestBinding"> <soap:address location="http://tests.python-zeep.org/test"/> </wsdl:port> </wsdl:service> </wsdl:definitions> """.strip()) client = stub(plugins=[wsa.WsAddressingPlugin()], wsse=None) transport = DummyTransport() doc = wsdl.Document(wsdl_main, transport, settings=Settings()) binding = doc.services.get('TestService').ports.get('TestPortType').binding envelope, headers = binding._create( 'TestOperation1', args=['foo'], kwargs={}, client=client, options={'address': 'http://tests.python-zeep.org/test'}) expected = """ <soap-env:Envelope xmlns:soap-env="http://www.w3.org/2003/05/soap-envelope"> <soap-env:Header xmlns:wsa="http://www.w3.org/2005/08/addressing"> <wsa:Action>urn:dummyRequest</wsa:Action> <wsa:MessageID>urn:uuid:ada686f9-5995-4088-bea4-239f694b2eaf</wsa:MessageID> <wsa:To>http://tests.python-zeep.org/test</wsa:To> </soap-env:Header> <soap-env:Body> <ns0:input xmlns:ns0="http://tests.python-zeep.org/xsd-main">foo</ns0:input> </soap-env:Body> </soap-env:Envelope> """ assert_nodes_equal(expected, envelope) assert headers['Content-Type'] == ( 'application/soap+xml; charset=utf-8; action="urn:dummyRequest"')
def create_soap_client(self, url_or_path, timeout=90, username=None, password=None, auth_type='NONE', settings={}, cache=None): """Creates a Soap client using the zeep library ----- Param *url_or_path :: string* The URL or path to the webservice. The client can read either a remote webservice or a local file from the OS ----- Param *timeout :: integer [90]* The number of seconds before the request to the webservice times out ----- Param *username :: string [None]* The username used for authenticating against webservices. If this is set, then the auth_type must also be set to something other than None ----- Param *password :: string [None]* The password used for authenticating against webservices ----- Param *auth_type :: string ["NONE"]* The authentication type to use when communicating with the webservice. Options are NONE, BASIC, PROXY and DIGEST. Any other than None requires that credentials also be supplied ----- Param *Settings :: dict [Empty]* The settings allows the user to specify various settings to use when communicating with the webservice. They are detailed here: https://python-zeep.readthedocs.io/en/master/settings.html ----- Return *Client* The client used for communicating with the webservice ----- | A simple example | | | ${client}= | Create Soap Client | http://some-web-url.com/webservice?wsdl | | | ${answer}= | Call Soap Method | ${client} | getTheAnswer | | Settings example | | | &{settings}= | Create Dictionary | strict=False | raw_response=True | | | ${client}= | Create Soap Client | http://some-web-url.com/webservice?wsdl | settings=&{settings} | | | ${answer}= | Call Soap Method | ${client} | getTheAnswer | | Basic authentication example | | | ${client}= | Create Soap Client | http://some-web-url.com/webservice?wsdl | username=bob | password=bobspassword | auth_type=BASIC | | | ${answer}= | Call Soap Method | ${client} | getTheAnswer | """ url = url_or_path transport = Transport(timeout=timeout, cache=cache) if auth_type != 'NONE': session = Session() if auth_type == 'BASIC': session.auth = HTTPBasicAuth(username, password) elif auth_type == 'PROXY': session.auth = HTTPProxyAuth(username, password) elif auth_type == 'DIGEST': session.auth = HTTPDigestAuth(username, password) transport = Transport(session=session, timeout=timeout, cache=cache) client_settings = Settings() if len(settings) > 0: available_settings = [ 'strict', 'raw_response', 'forbid_dtd', 'forbid_entities', 'forbid_external', 'xml_huge_tree', 'force_https', 'extra_http_headers' ] for key in settings: if key in available_settings: if key == 'strict': client_settings.strict = settings[key] elif key == 'raw_response': client_settings.raw_response = settings[key] elif key == 'forbid_dtd': client_settings.forbid_dtd = settings[key] elif key == 'forbid_entities': client_settings.forbid_entities = settings[key] elif key == 'forbid_external': client_settings.forbid_external = settings[key] elif key == 'xml_huge_tree': client_settings.xml_huge_tree = settings[key] elif key == 'force_https': client_settings.force_https = settings[key] elif key == 'extra_http_headers': client_settings.extra_http_headers = settings[key] client = Client(url, transport=transport, plugins=[HistoryPlugin()], settings=client_settings) return client
def setup(self): public_portal_service_url = self.url_ + '/pearson-rest/services/PublicPortalServiceJSON' settings = Settings(strict=False, raw_response=True, forbid_dtd=False, forbid_entities=False, forbid_external=False, xsd_ignore_sequence_order=True) self.client_ = Client(wsdl=public_portal_service_url + '?wsdl', transport=Transport(session=self.session_), settings=settings)
def parse_xml(data): return zeep.loader.parse_xml(data, None, settings=Settings())
def __init__(self, settings=None): self.schemas = [] self.settings = settings or Settings()