def consulta_distribuicao_nfe(certificado, **kwargs): if "xml" not in kwargs: kwargs['xml'] = xml_consulta_distribuicao_nfe(certificado, **kwargs) xml_send = kwargs["xml"] base_url = localizar_url( 'NFeDistribuicaoDFe', kwargs['estado'], kwargs['modelo'], kwargs['ambiente']) cert, key = extract_cert_and_key_from_pfx( certificado.pfx, certificado.password) cert, key = save_cert_key(cert, key) session = Session() session.cert = (cert, key) session.verify = False transport = Transport(session=session) xml = etree.fromstring(xml_send) xml_um = etree.fromstring('<nfeCabecMsg xmlns="http://www.portalfiscal.inf.br/nfe/wsdl/"><cUF>AN</cUF><versaoDados>1.00</versaoDados></nfeCabecMsg>') client = Client(base_url, transport=transport) port = next(iter(client.wsdl.port_types)) first_operation = next(iter(client.wsdl.port_types[port].operations)) with client.settings(raw_response=True): response = client.service[first_operation](nfeDadosMsg=xml, _soapheaders=[xml_um]) response, obj = sanitize_response(response.text) return { 'sent_xml': xml_send, 'received_xml': response, 'object': obj.Body.nfeDistDFeInteresseResponse.nfeDistDFeInteresseResult }
def _send(certificado, method, **kwargs): xml_send = kwargs["xml"] base_url = localizar_url( method, kwargs['estado'], kwargs['modelo'], kwargs['ambiente']) cert, key = extract_cert_and_key_from_pfx( certificado.pfx, certificado.password) cert, key = save_cert_key(cert, key) session = Session() session.cert = (cert, key) session.verify = False transport = Transport(session=session) xml = etree.fromstring(xml_send) client = Client(base_url, transport=transport) port = next(iter(client.wsdl.port_types)) first_operation = next(iter(client.wsdl.port_types[port].operations)) namespaceNFe = xml.find(".//{http://www.portalfiscal.inf.br/nfe}NFe") if namespaceNFe is not None: namespaceNFe.set('xmlns', 'http://www.portalfiscal.inf.br/nfe') with client.settings(raw_response=True): response = client.service[first_operation](xml) response, obj = sanitize_response(response.text) return { 'sent_xml': xml_send, 'received_xml': response, 'object': obj.Body.getchildren()[0] }
def test_factory_ns_custom_prefix(): client = Client('tests/wsdl_files/soap.wsdl') client.set_ns_prefix('sq', 'http://example.com/stockquote.xsd') factory = client.type_factory('sq') obj = factory.Address(NameFirst='Michael', NameLast='van Tellingen') assert obj.NameFirst == 'Michael' assert obj.NameLast == 'van Tellingen'
def test_parse_soap_wsdl(): client = Client('tests/wsdl_files/soap.wsdl', transport=Transport(),) response = """ <?xml version="1.0"?> <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:stoc="http://example.com/stockquote.xsd"> <soapenv:Header/> <soapenv:Body> <stoc:TradePrice> <price>120.123</price> </stoc:TradePrice> </soapenv:Body> </soapenv:Envelope> """.strip() client.set_ns_prefix('stoc', 'http://example.com/stockquote.xsd') with requests_mock.mock() as m: m.post('http://example.com/stockquote', text=response) account_type = client.get_type('stoc:account') account = account_type(id=100) account.user = '******' country = client.get_element('stoc:country').type() country.name = 'The Netherlands' country.code = 'NL' result = client.service.GetLastTradePrice( tickerSymbol='foobar', account=account, country=country) assert result == 120.123 request = m.request_history[0] # Compare request body expected = """ <soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:stoc="http://example.com/stockquote.xsd"> <soap-env:Body> <stoc:TradePriceRequest> <tickerSymbol>foobar</tickerSymbol> <account> <id>100</id> <user>mvantellingen</user> </account> <stoc:country> <name>The Netherlands</name> <code>NL</code> </stoc:country> </stoc:TradePriceRequest> </soap-env:Body> </soap-env:Envelope> """ assert_nodes_equal(expected, request.body)
def test_factory_no_reference(): client = Client('tests/wsdl_files/soap.wsdl') obj_1 = client.get_type('ns0:ArrayOfAddress')() obj_1.Address.append({ 'NameFirst': 'J', 'NameLast': 'Doe', }) obj_2 = client.get_type('ns0:ArrayOfAddress')() assert len(obj_2.Address) == 0
def __init__(self, api_key=None, sandbox=False): if not any([api_key, sandbox]): raise AttributeError('Api key is required.') self.api_key = api_key self.sandbox = sandbox if sandbox: self.api_key = api_key or 'abcde12345abcde12345' self.endpoint = ENDPOINT_SANDBOX transport = Transport(session=Session()) transport.session.headers = self.headers client = Client(WSDL, transport=transport) self.service = client.create_service('{http://tempuri.org/}e3', self.endpoint) self.headers.update({'sid': self._service('Zaloguj', self.api_key)})
def setUp(self): from spyne.test.interop._test_soap_client_base import run_server run_server('http') transport = Transport(cache=False) self.client = Client("http://localhost:9754/?wsdl", transport=transport) self.ns = "spyne.test.interop.server"
def setUp(self): from spyne.test.interop._test_soap_client_base import run_server run_server('http') port, = server_started.keys() transport = Transport(cache=False) self.client = Client("http://localhost:%d/?wsdl" % port, transport=transport) self.ns = "spyne.test.interop.server"
def __init__(self): if settings.GP_WS_ENABLED: cache = SqliteCache(timeout=30 * 24 * 60 * 60) session = Session() session.auth = HttpNtlmAuth( settings.GP_WS_USERNAME, settings.GP_WS_PASSWORD) self.client = Client( settings.GP_WS_URL, transport=Transport(session=session, cache=cache) ) self.ws_factory1 = self.client.type_factory('ns1') self.ws_factory2 = self.client.type_factory('ns2') company = self.ws_factory2.CompanyKey(settings.GP_COMPANY_ID) self.service_context = self.ws_factory2.Context( OrganizationKey=company, CurrencyType='Local' )
def __init__(self, url, location, sslverify, **kwargs): if "session" in kwargs: session = kwargs["session"] del kwargs["session"] transport = Transport(session=session) else: transport = Transport() if "auth" in kwargs: transport.session.auth = kwargs["auth"] del kwargs["auth"] transport.session.verify = sslverify self.sessionplugin=SessionPlugin(self) plugins=[self.sessionplugin] if "log" in kwargs: log = kwargs.get("log") if isinstance(log, Plugin): plugins.append(log) elif log == True: plugins.append(LogRequest()) del kwargs["log"] self.client = Client(url, transport=transport, # cache=None, unwrap=False, plugins=plugins) self.service = self.client.create_service(ns_name(schema_xmla,"MsXmlAnalysisSoap"), location) self.client.set_ns_prefix(None, schema_xmla) # optional, call might fail self.getMDSchemaLevels = lambda *args, **kw: self.Discover("MDSCHEMA_LEVELS", *args, **kw) self.setListenOnSessionId(False) self.setSessionId(None) self._soapheaders=None
def test_factory_ns_unknown_prefix(): client = Client('tests/wsdl_files/soap.wsdl') with pytest.raises(ValueError): client.type_factory('bla')
def test_factory_ns_auto_prefix(): client = Client('tests/wsdl_files/soap.wsdl') factory = client.type_factory('ns0') obj = factory.Address(NameFirst='Michael', NameLast='van Tellingen') assert obj.NameFirst == 'Michael' assert obj.NameLast == 'van Tellingen'
class TestZeep(unittest.TestCase): def setUp(self): from spyne.test.interop._test_soap_client_base import run_server run_server('http') self.client = Client("http://localhost:9754/?wsdl") self.ns = "spyne.test.interop.server" def get_inst(self, what): return self.client.get_type(what)() def test_echo_datetime(self): # ZEEP doesn't support microseconds val = datetime.now().replace(microsecond=0) ret = self.client.service.echo_datetime(val) assert val == ret def test_echo_datetime_with_invalid_format(self): # ZEEP doesn't support microseconds val = datetime.now().replace(microsecond=0) ret = self.client.service.echo_datetime_with_invalid_format(val) assert val == ret def test_echo_date(self): val = datetime.now().date() ret = self.client.service.echo_date(val) assert val == ret def test_echo_date_with_invalid_format(self): val = datetime.now().date() ret = self.client.service.echo_date_with_invalid_format(val) assert val == ret def test_echo_time(self): # ZEEP doesnt support microseconds val = datetime.now().replace(microsecond=0).time() ret = self.client.service.echo_time(val) assert val == ret def test_echo_time_with_invalid_format(self): # ZEEP doesnt support microseconds val = datetime.now().replace(microsecond=0).time() ret = self.client.service.echo_time_with_invalid_format(val) assert val == ret def test_echo_simple_boolean_array(self): val = [False, False, False, True] ret = self.client.service.echo_simple_boolean_array(val) assert val == ret def test_echo_boolean(self): val = True ret = self.client.service.echo_boolean(val) self.assertEquals(val, ret) val = False ret = self.client.service.echo_boolean(val) self.assertEquals(val, ret) def test_enum(self): val = self.client.get_type("{%s}DaysOfWeekEnum" % self.ns)('Monday') ret = self.client.service.echo_enum(val) assert val == ret def test_bytearray(self): val = b"\x00\x01\x02\x03\x04" ret = self.client.service.echo_bytearray(val) assert val == ret def test_validation(self): non_nillable_class = self.client.get_type("{hunk.sunk}NonNillableClass")() non_nillable_class.i = 6 non_nillable_class.s = None try: self.client.service.non_nillable(non_nillable_class) except ZeepError as e: pass else: raise Exception("must fail") def test_echo_integer_array(self): ia = self.client.get_type('{%s}integerArray' % self.ns)() ia.integer.extend([1, 2, 3, 4, 5]) self.client.service.echo_integer_array(ia) # FIXME: Figure how this is supposed to work def _test_echo_in_header(self): in_header = self.client.get_type('{%s}InHeader' % self.ns)() in_header.s = 'a' in_header.i = 3 self.client.set_options(soapheaders=in_header) ret = self.client.service.echo_in_header() self.client.set_options(soapheaders=None) print(ret) self.assertEquals(in_header.s, ret.s) self.assertEquals(in_header.i, ret.i) # FIXME: Figure how this is supposed to work def _test_echo_in_complex_header(self): in_header = self.client.get_type('{%s}InHeader' % self.ns)() in_header.s = 'a' in_header.i = 3 in_trace_header = self.client.get_type('{%s}InTraceHeader' % self.ns)() in_trace_header.client = 'suds' in_trace_header.callDate = datetime(year=2000, month=1, day=1, hour=0, minute=0, second=0, microsecond=0) self.client.set_options(soapheaders=(in_header, in_trace_header)) ret = self.client.service.echo_in_complex_header() self.client.set_options(soapheaders=None) print(ret) self.assertEquals(in_header.s, ret[0].s) self.assertEquals(in_header.i, ret[0].i) self.assertEquals(in_trace_header.client, ret[1].client) self.assertEquals(in_trace_header.callDate, ret[1].callDate) def test_send_out_header(self): out_header = self.client.get_type('{%s}OutHeader' % self.ns)() out_header.dt = datetime(year=2000, month=1, day=1) out_header.f = 3.141592653 ret = self.client.service.send_out_header() self.assertEquals(ret.header.OutHeader.dt, out_header.dt) self.assertEquals(ret.header.OutHeader.f, out_header.f) def test_send_out_complex_header(self): out_header = self.client.get_type('{%s}OutHeader' % self.ns)() out_header.dt = datetime(year=2000, month=1, day=1) out_header.f = 3.141592653 out_trace_header = self.client.get_type('{%s}OutTraceHeader' % self.ns)() out_trace_header.receiptDate = datetime(year=2000, month=1, day=1, hour=1, minute=1, second=1, microsecond=1) out_trace_header.returnDate = datetime(year=2000, month=1, day=1, hour=1, minute=1, second=1, microsecond=100) ret = self.client.service.send_out_complex_header() self.assertEquals(ret.header.OutHeader.dt, out_header.dt) self.assertEquals(ret.header.OutHeader.f, out_header.f) self.assertEquals(ret.header.OutTraceHeader.receiptDate, out_trace_header.receiptDate) self.assertEquals(ret.header.OutTraceHeader.returnDate, out_trace_header.returnDate) def test_echo_string(self): test_string = "OK" ret = self.client.service.echo_string(test_string) self.assertEquals(ret, test_string) def __get_xml_test_val(self): return { "test_sub": { "test_subsub1": { "test_subsubsub1": ["subsubsub1 value"] }, "test_subsub2": ["subsub2 value 1", "subsub2 value 2"], "test_subsub3": [ { "test_subsub3sub1": ["subsub3sub1 value"] }, { "test_subsub3sub2": ["subsub3sub2 value"] }, ], "test_subsub4": [], "test_subsub5": ["x"], } } def test_echo_simple_class(self): val = self.client.get_type("{%s}SimpleClass" % self.ns)() val.i = 45 val.s = "asd" # why val loses all its data after being passed to service request? # it doesn't work without deepcopy! ret = self.client.service.echo_simple_class(deepcopy(val)) assert ret.i == val.i assert ret.s == val.s def test_echo_class_with_self_reference(self): val = self.client.get_type("{%s}ClassWithSelfReference" % self.ns)() val.i = 45 val.sr = self.client.get_type("{%s}ClassWithSelfReference" % self.ns)() val.sr.i = 50 val.sr.sr = None # why val loses all its data after being passed to service request? # it doesn't work without deepcopy! ret = self.client.service.echo_class_with_self_reference(deepcopy(val)) assert ret.i == val.i assert ret.sr.i == val.sr.i def test_echo_nested_class(self): val = self.client.get_type("{punk.tunk}NestedClass")() val.i = 45 val.s = "asd" val.f = 12.34 val.ai = self.client.get_type("{%s}integerArray" % self.ns)() val.ai.integer.extend([1, 2, 3, 45, 5, 3, 2, 1, 4]) val.simple = self.client.get_type("{%s}SimpleClassArray" % self.ns)() val.simple.SimpleClass.append(self.client.get_type("{%s}SimpleClass" % self.ns)()) val.simple.SimpleClass.append(self.client.get_type("{%s}SimpleClass" % self.ns)()) val.simple.SimpleClass[0].i = 45 val.simple.SimpleClass[0].s = "asd" val.simple.SimpleClass[1].i = 12 val.simple.SimpleClass[1].s = "qwe" val.other = self.client.get_type("{%s}OtherClass" % self.ns)() # ZEEP doesn't support microseconds val.other.dt = datetime.now().replace(microsecond=0) val.other.d = 123.456 val.other.b = True # why val loses all its data after being passed to service request? # it doesn't work without deepcopy! ret = self.client.service.echo_nested_class(deepcopy(val)) self.assertEquals(ret.i, val.i) self.assertEqual(ret.ai.integer, val.ai.integer) self.assertEqual(ret.ai.integer[0], val.ai.integer[0]) self.assertEquals(ret.simple.SimpleClass[0].s, val.simple.SimpleClass[0].s) self.assertEqual(ret.other.dt, val.other.dt) def test_huge_number(self): self.assertEquals(self.client.service.huge_number(), 2 ** int(1e5)) def test_long_string(self): self.assertEquals(self.client.service.long_string(), ('0123456789abcdef' * 16384)) def test_empty(self): self.client.service.test_empty() def test_echo_extension_class(self): val = self.client.get_type("{bar}ExtensionClass")() val.i = 45 val.s = "asd" val.f = 12.34 val.simple = self.client.get_type("{%s}SimpleClassArray" % self.ns)() val.simple.SimpleClass.append(self.client.get_type("{%s}SimpleClass" % self.ns)()) val.simple.SimpleClass.append(self.client.get_type("{%s}SimpleClass" % self.ns)()) val.simple.SimpleClass[0].i = 45 val.simple.SimpleClass[0].s = "asd" val.simple.SimpleClass[1].i = 12 val.simple.SimpleClass[1].s = "qwe" val.other = self.client.get_type("{%s}OtherClass" % self.ns)() # ZEEP doesn't support microseconds val.other.dt = datetime.now().replace(microsecond=0) val.other.d = 123.456 val.other.b = True val.p = self.client.get_type("{hunk.sunk}NonNillableClass")() val.p.dt = datetime(2010, 6, 2) val.p.i = 123 val.p.s = "punk" val.l = datetime(2010, 7, 2) val.q = 5 # why val loses all its data after being passed to service request? # it doesn't work without deepcopy! ret = self.client.service.echo_extension_class(deepcopy(val)) print(ret) self.assertEquals(ret.i, val.i) self.assertEquals(ret.s, val.s) self.assertEquals(ret.f, val.f) self.assertEquals(ret.simple.SimpleClass[0].i, val.simple.SimpleClass[0].i) self.assertEquals(ret.other.dt, val.other.dt) self.assertEquals(ret.p.s, val.p.s) def test_python_exception(self): try: self.client.service.python_exception() raise Exception("must fail") except ZeepError as e: pass def test_soap_exception(self): try: self.client.service.soap_exception() raise Exception("must fail") except ZeepError as e: pass def test_complex_return(self): ret = self.client.service.complex_return() self.assertEquals(ret.resultCode, 1) self.assertEquals(ret.resultDescription, "Test") self.assertEquals(ret.transactionId, 123) self.assertEquals(ret.roles.RoleEnum[0], "MEMBER") def test_return_invalid_data(self): try: self.client.service.return_invalid_data() raise Exception("must fail") except: pass def test_custom_messages(self): ret = self.client.service.custom_messages("test") assert ret == 'test' def test_echo_simple_bare(self): ret = self.client.service.echo_simple_bare("test") assert ret == 'test' # # This test is disabled because zeep does not create the right request # object. Opening the first <ns0:string> tag below is wrong. # #<SOAP-ENV:Envelope xmlns:ns0="spyne.test.interop.server" # xmlns:xs="http://www.w3.org/2001/XMLSchema" # xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" # xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" # xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> # <SOAP-ENV:Header/> # <ns1:Body> # <ns0:echo_complex_bare> # <ns0:string> # <ns0:string>abc</ns0:string> # <ns0:string>def</ns0:string> # </ns0:string> # </ns0:echo_complex_bare> # </ns1:Body> #</SOAP-ENV:Envelope> # # The right request looks like this: # # <ns0:echo_complex_bare> # <ns0:string>abc</ns0:string> # <ns0:string>def</ns0:string> # </ns0:echo_complex_bare> # def _test_echo_complex_bare(self): val = ['abc','def'] ia = self.client.get_type('{%s}stringArray' % self.ns)() ia.string.extend(val) ret = self.client.service.echo_complex_bare(ia) assert ret == val
def __init__(self): self.WSDL = os.getenv('DHL.WSDL', None) self.client = Client(wsdl=self.WSDL)
import os from zeep import Client from utils.cache import cache CLIENT_WSDL = Client( os.environ.get( "URL_AMIL", "https://api.amil.com.br/sisamil-credenciado/prestador/conecta?wsdl")) @cache.cached(timeout=50) def get_justification(): response_amil = [] response = CLIENT_WSDL.service.BuscarJustificativaConfirmacaoSemToken() for r in response: response_amil.append({'codigo': r["Codigo"], 'message': r['Mensagem']}) return response_amil def confirm_attendance(data): return CLIENT_WSDL.service.ConfirmarAtendimento( pedido=data["pedido"], prestador=data["prestador"], beneficiario=data["codMatriculaBeneficario"], token=data["token"] if 'token' in data and data["token"] else None, dataAtendimento=data["dataAtendimento"], horaAtendimento=data["horaAtendimento"], justificativaConfirmacaoSemToken=data["retorno"])
def remake_client(self, keyword: str): self.client = Client(_make_client_url(keyword=keyword))
def test_xop(): 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/soap/" xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/" 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:complexType name="responseTypeSimple"> <xsd:sequence> <xsd:element name="BinaryData" type="xsd:base64Binary"/> </xsd:sequence> </xsd:complexType> <xsd:complexType name="BinaryDataType"> <xsd:simpleContent> <xsd:extension base="xsd:base64Binary"> <xsd:anyAttribute namespace="##other" processContents="lax"/> </xsd:extension> </xsd:simpleContent> </xsd:complexType> <xsd:complexType name="responseTypeComplex"> <xsd:sequence> <xsd:element name="BinaryData" type="tns:BinaryDataType"/> </xsd:sequence> </xsd:complexType> <xsd:element name="input" type="xsd:string"/> <xsd:element name="resultSimple" type="tns:responseTypeSimple"/> <xsd:element name="resultComplex" type="tns:responseTypeComplex"/> </xsd:schema> </wsdl:types> <wsdl:message name="dummyRequest"> <wsdl:part name="response" element="tns:input"/> </wsdl:message> <wsdl:message name="dummyResponseSimple"> <wsdl:part name="response" element="tns:resultSimple"/> </wsdl:message> <wsdl:message name="dummyResponseComplex"> <wsdl:part name="response" element="tns:resultComplex"/> </wsdl:message> <wsdl:portType name="TestPortType"> <wsdl:operation name="TestOperation1"> <wsdl:input message="dummyRequest"/> <wsdl:output message="dummyResponseSimple"/> </wsdl:operation> <wsdl:operation name="TestOperation2"> <wsdl:input message="dummyRequest"/> <wsdl:output message="dummyResponseComplex"/> </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:operation name="TestOperation2"> <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 = Client(wsdl_main, transport=Transport()) service = client.create_service( "{http://tests.python-zeep.org/xsd-main}TestBinding", "http://tests.python-zeep.org/test") content_type = 'multipart/related; boundary="boundary"; type="application/xop+xml"; start="<soap:Envelope>"; start-info="application/soap+xml; charset=utf-8"' response1 = '\r\n'.join(line.strip() for line in """ Content-Type: application/xop+xml; charset=utf-8; type="application/soap+xml" Content-Transfer-Encoding: binary Content-ID: <soap:Envelope> <?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xop="http://www.w3.org/2004/08/xop/include" xmlns:test="http://tests.python-zeep.org/xsd-main"> <soap:Body> <test:resultSimple> <test:BinaryData> <xop:Include href="cid:id4"/> </test:BinaryData> </test:resultSimple> </soap:Body> </soap:Envelope> --boundary Content-Type: application/binary Content-Transfer-Encoding: binary Content-ID: <id4> BINARYDATA --boundary-- """.splitlines()) response2 = '\r\n'.join(line.strip() for line in """ Content-Type: application/xop+xml; charset=utf-8; type="application/soap+xml" Content-Transfer-Encoding: binary Content-ID: <soap:Envelope> <?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xop="http://www.w3.org/2004/08/xop/include" xmlns:test="http://tests.python-zeep.org/xsd-main"> <soap:Body> <test:resultComplex> <test:BinaryData> <xop:Include href="cid:id4"/> </test:BinaryData> </test:resultComplex> </soap:Body> </soap:Envelope> --boundary Content-Type: application/binary Content-Transfer-Encoding: binary Content-ID: <id4> BINARYDATA --boundary-- """.splitlines()) print(response1) with requests_mock.mock() as m: m.post('http://tests.python-zeep.org/test', content=response2.encode("utf-8"), headers={"Content-Type": content_type}) result = service.TestOperation2("") assert result["_value_1"] == "BINARYDATA".encode() m.post( 'http://tests.python-zeep.org/test', content=response1.encode("utf-8"), headers={"Content-Type": content_type}) result = service.TestOperation1("") assert result == "BINARYDATA".encode()
def _get_cliente_sigep(): global _cliente_sigep if _cliente_sigep is None: _cliente_sigep = Client(_URL_SIGEP) return _cliente_sigep
def _get_item(self): return Client(self.wsfex.url).get_type('ns0:Item')
def _get_item_array(self): return Client(self.wsfex.url).get_type('ns0:ArrayOfItem')
def _get_document_request(self): return Client(self.wsfex.url).type_factory('ns0').ClsFEXRequest()
# CERT = 'changeme.pem' # session.verify = CERT session.auth = HTTPBasicAuth(creds.USERNAME, creds.PASSWORD) transport = Transport(session=session, timeout=10) # strict=False is not always necessary, but it allows zeep to parse imperfect XML settings = Settings(strict=False, xml_huge_tree=True) # If debug output is requested, add the MyLoggingPlugin callback plugin = [MyLoggingPlugin()] if DEBUG else [] # Create the Zeep client with the specified settings client = Client(WSDL_FILE, settings=settings, transport=transport, plugins=plugin) # Create the Zeep service binding to AXL at the specified CUCM service = client.create_service( "{http://www.cisco.com/AXLAPIService/}AXLAPIBinding", 'https://{cucm}:8443/axl/'.format(cucm=creds.CUCM_ADDRESS)) # Add testPartition1 partition_data = {'name': PARTITION1_NAME} try: resp = service.addRoutePartition(partition_data) except Fault as err: print('Zeep error: addRoutePartition (1 of 2): {err}'.format(err=err)) else:
import os import string from hashlib import sha1 from bson import ObjectId from flask import request, abort, jsonify, Blueprint from pymongo import MongoClient from zeep import Client MONGO_HOST = os.environ.get('MONGO_HOST') USAEPAY_KEY = os.environ.get('USAEPAY_KEY') USAEPAY_PIN = os.environ.get('USAEPAY_PIN') USAEPAY_WSDL = os.environ.get('USAEPAY_WSDL') usaepay_client = Client(USAEPAY_WSDL) factory = usaepay_client.type_factory('ns0') mongo_cli = MongoClient(host=MONGO_HOST) bp_payment = Blueprint('payment', __name__) def build_token(): """Create the request token.""" client_ip = '74.71.168.169' seed = string.ascii_lowercase apikey = USAEPAY_KEY apipin = USAEPAY_PIN prehash = (apikey + seed + apipin).encode('utf-8') pinhash = str(sha1(prehash).hexdigest()) euhash = factory.ueHash(HashValue=pinhash, Seed=seed, Type='sha1') token = factory.ueSecurityToken(ClientIP=client_ip,
def legislation_categories(self): categories = [] for category in Client( _make_client_url(keyword='Legislation')).service.GetTitles(): categories.append(Category(category_data=category)) return categories
from urllib3 import disable_warnings from urllib3.exceptions import InsecureRequestWarning from lxml import etree import getpass # CUCM HostName/ IP Address host = input("CUCM Hostname:") # WSDL Service location download AXLToolKit from Call Manager wsdl = input("WSDL Service path:") # UserName and Password user = input("Username: "******"{http://www.cisco.com/AXLAPIService/}AXLAPIBinding" session = Session() session.verify = False session.auth = HTTPBasicAuth(user, pwd) transport = Transport(cache=SqliteCache(), session=session, timeout=20) history = HistoryPlugin() client = Client(wsdl=wsdl, transport=transport, plugins=[history]) service = client.create_service(binding, location) # user id on CUCM username = input("Username ID:") try: response = service.getUser(userid=username) print(response) except Exception as e: print(str(e))
property['RawValue'] = '{masked}' if (property['Formatted'] != None): property['Formatted'] = '{masked}' property['Creator'] = '{masked}' # Main # # Consume WSDL and generate soap structures try: session = Session() if (args.nosslverify): session.verify = False session.sslverify = False transport = DebugTransport(cache=SqliteCache(), session=session) wudetails = Client(wudetailsservice_wsdl_url, transport=transport) except: logging.critical ('Unable to obtain WSDL from ' +wudetailsservice_wsdl_url) raise try: scopeFilter = wudetails.get_type('ns0:WUScopeFilter') nestedFilter = wudetails.get_type('ns0:WUNestedFilter') propertiesToReturn = wudetails.get_type('ns0:WUPropertiesToReturn') scopeOptions = wudetails.get_type('ns0:WUScopeOptions') propertyOptions = wudetails.get_type('ns0:WUPropertyOptions') extraProperties = wudetails.get_type('ns0:WUExtraProperties') except: logging.critical ('WSDL different from expected') raise
class NetSuiteClient: """The Netsuite client class providing access to the Netsuite SOAP/WSDL web service""" WSDL_URL_TEMPLATE = 'https://{account}.suitetalk.api.netsuite.com/wsdl/v2019_1_0/netsuite.wsdl' DATACENTER_URL_TEMPLATE = 'https://{account}.suitetalk.api.netsuite.com/services/NetSuitePort_2019_1' _search_preferences = None _passport = None _account = None # Used by TBA _consumer_key = None _consumer_secret = None _token_key = None _token_secret = None _app_id = None def __init__(self, account=None, caching=None): """ Initialize the Zeep SOAP client, parse the xsd specifications of Netsuite and store the complex types as attributes of this instance. :param str account: Account ID to connect to :param dict caching: The available cache settings are the following caching['enable'] bool: Indicates if caching['timeout'] int: Timeout in seconds for caching. If None, defaults to 30 days caching['path'] str: The path to store the database files caching['engine'] str: The Database engine used for caching. """ self.logger = logging.getLogger(self.__class__.__name__) assert account, 'Invalid account' assert '-' not in account, 'Account cannot have hyphens, it is likely an underscore' self._account = account self._wsdl_url = self.WSDL_URL_TEMPLATE.format( account=account.replace('_', '-')) self._datacenter_url = self.DATACENTER_URL_TEMPLATE.format( account=account.replace('_', '-')) if caching is None: caching = {} # Make sure that caching argument is an instance of dict assert isinstance( caching, dict), '"caching" argument must be an instance of dict' # Allowed cache setting keys allowed_cache_settings = ['enable', 'engine', 'timeout', 'path'] allowed_cache_engines = ['sqlite'] # Default cache settings cache_settings = { 'enable': True, 'engine': 'sqlite', 'timeout': 2592000, 'path': os.path.dirname(os.path.abspath(__file__)) } # Filter out user input and get only the allowed keys cache_settings_input = { key: caching[key] for key in caching if key in allowed_cache_settings } # Merge default cache settings with input cache settings cache_settings.update(cache_settings_input) # Default transport set to None transport = None if cache_settings['enable']: # Make sure that provided cache engine is allowed assert cache_settings['engine'] in allowed_cache_engines, \ f'Cache engine "{cache_settings["engine"]}" is not available. You can use one of the following engines: ' + ','.join(allowed_cache_engines) path = os.path.join(cache_settings['path'], 'cache.db') timeout = cache_settings['timeout'] # Sqlite cache engine if cache_settings['engine'] == 'sqlite': cache = SqliteCache(path=path, timeout=timeout) transport = Transport(cache=cache) # Initialize the Zeep Client self._client = Client(self._wsdl_url, transport=transport) # default service points to wrong data center. need to create a new service proxy and replace the default one self._service_proxy = self._client.create_service( '{urn:platform_2019_1.webservices.netsuite.com}NetSuiteBinding', self._datacenter_url) # Parse all complex types specified in :const:`~netsuitesdk.netsuite_types.COMPLEX_TYPES` # and store them as attributes of this instance. Same for simple types. self._namespaces = {} self._init_complex_types() self._init_simple_types() self._app_info = None self._is_authenticated = False self.set_search_preferences() def set_search_preferences(self, page_size: int = 5, return_search_columns: bool = False): self._search_preferences = self.SearchPreferences( bodyFieldsOnly=False, pageSize=page_size, returnSearchColumns=return_search_columns) def _init_complex_types(self): self._complex_types = {} for namespace, complex_types in COMPLEX_TYPES.items(): if not namespace in self._namespaces: self._namespaces[namespace] = [] for type_name in complex_types: try: verbose_type_name = '{namespace}:{type_name}'.format( namespace=namespace, type_name=type_name) complex_type = self._client.get_type(verbose_type_name) except ZeepLookupError: self.logger.warning( 'LookupError: Did not find complex type {}'.format( type_name)) else: setattr(self, type_name, complex_type) self._complex_types[type_name] = complex_type self._namespaces[namespace].append(complex_type) def _init_simple_types(self): self._simple_types = {} for namespace, simple_types in SIMPLE_TYPES.items(): if not namespace in self._namespaces: self._namespaces[namespace] = [] for type_name in simple_types: try: verbose_type_name = '{namespace}:{type_name}'.format( namespace=namespace, type_name=type_name) simple_type = self._client.get_type(verbose_type_name) except ZeepLookupError: self.logger.warning( 'LookupError: Did not find simple type {}'.format( type_name)) else: setattr(self, type_name, simple_type) self._simple_types[type_name] = simple_type self._namespaces[namespace].append(simple_type) def get_complex_type(self, type_name): # if ':' in type_name: # namespace, type_name = type_name.split(':') # namespace_index = namespace[2:] return self._complex_types[type_name] def get_simple_type(self, type_name): return self._simple_types[type_name] def get_complex_type_attributes(self, complex_type): if isinstance(complex_type, str): complex_type = self.get_complex_type(complex_type) try: return [(attribute.name, attribute.type.name) for attribute in complex_type._attributes] except AttributeError: return [] def get_complex_type_elements(self, complex_type): if isinstance(complex_type, str): complex_type = self.get_complex_type(complex_type) try: return [(attr_name, element.type.name) for attr_name, element in complex_type.elements] except AttributeError: return [] def get_complex_type_info(self, complex_type): if isinstance(complex_type, str): complex_type = self.get_complex_type(complex_type) label = complex_type else: if hasattr(complex_type, 'name'): label = complex_type.name else: label = str(complex_type) attributes = self.get_complex_type_attributes(complex_type) elements = self.get_complex_type_elements(complex_type) yield 'complexType {}:'.format(label) if attributes: yield 'Attributes:' for name, type_name in attributes: yield '\t{}: {}'.format(name, type_name) else: yield 'No attributes' if elements: yield 'Elements:' for name, type_name in elements: yield '\t{}: {}'.format(name, type_name) else: yield 'No elements' def login(self, email, password, role, application_id): """ Authenticate and login user for a Netsuite session. The passport argument is of type Passport(email, password, role and account) which holds the credentials and can be created with NetSuiteClient.create_password. :param int applicationId: All requests done in this session will be identified with this application id. :param Passport passport: holds the credentials to authenticate the user. :return: the login response which contains the response status and user roles :rtype: LoginResponse :raises :class:`~netsuitesdk.exceptions.NetSuiteLoginError`: if login was not successful. Possible codes are: InsufficientPermissionFault, InvalidAccountFault, InvalidSessionFault, InvalidCredentialsFault and UnexpectedErrorFault """ role = self.RecordRef(internalId=role) self._passport = self.Passport(email=email, password=password, role=role, account=self._account) if self._is_authenticated: self.logout() try: self._app_info = self.ApplicationInfo(applicationId=application_id) response = self._service_proxy.login( self._passport, _soapheaders={'applicationInfo': self._app_info}) if response.status.isSuccess: self._is_authenticated = True return response else: statusDetail = response.status['statusDetail'][0] exc = self._request_error('login', detail=statusDetail, error_cls=NetSuiteLoginError) raise exc except Fault as fault: exc = NetSuiteLoginError(str(fault), code=fault.code) raise exc from None def _generate_token_passport(self): def compute_nonce(length=20): """pseudo-random generated numeric string""" return ''.join([str(random.randint(0, 9)) for i in range(length)]) nonce = compute_nonce(length=20) timestamp = int(time.time()) key = '{}&{}'.format(self._consumer_secret, self._token_secret) base_string = '&'.join([ self._account, self._consumer_key, self._token_key, nonce, str(timestamp) ]) key_bytes = key.encode(encoding='ascii') message_bytes = base_string.encode(encoding='ascii') # compute the signature if self._signature_algorithm == 'HMAC-SHA256': # hash hashed_value = hmac.new(key_bytes, msg=message_bytes, digestmod=hashlib.sha256) elif self._signature_algorithm == 'HMAC-SHA1': hashed_value = hmac.new(key_bytes, msg=message_bytes, digestmod=hashlib.sha1) else: raise NetSuiteError( "signature_algorithm needs to be one of 'HMAC-SHA256', 'HMAC-SHA1'" ) dig = hashed_value.digest() # convert dig (a byte sequence) to a base 64 string value = base64.b64encode(dig).decode() signature = self.TokenPassportSignature( value, algorithm=self._signature_algorithm) return self.TokenPassport(account=self._account, consumerKey=self._consumer_key, token=self._token_key, nonce=nonce, timestamp=timestamp, signature=signature) def connect_tba(self, consumer_key, consumer_secret, token_key, token_secret, signature_algorithm='HMAC-SHA1'): """ Create a TokenPassport object holding credentials for Token based authentication which will be passed to NetSuiteClient.login :param str account: the NetSuite account ID :param str consumer_key: the consumer key for the integration record :param str consumer_secret: the consumer secret :param str token_key: a string identifier of a token representing a unique combination of a user, a role and an integration record :param str token_secret: the token secret :param str signature_algorithm: algorithm to compute the signature value (a hashed value), choices are 'HMAC-SHA256' or 'HMAC-SHA1' """ self._consumer_key = consumer_key self._consumer_secret = consumer_secret self._token_key = token_key self._token_secret = token_secret self._signature_algorithm = signature_algorithm @property def logged_in(self): return self._is_authenticated def logout(self): if not self._is_authenticated: return response = self._service_proxy.logout() self._is_authenticated = False self._consumer_key = None self._consumer_secret = None self._token_key = None self._token_secret = None return response.status def _request_error(self, service_name, detail, error_cls=None): if error_cls is None: error_cls = NetSuiteRequestError exc = error_cls( "An error occured in a {service_name} request: {msg}".format( service_name=service_name, msg=detail['message']), code=detail['code']) # self.logger.error(str(exc)) return exc def _build_soap_headers(self, include_search_preferences: bool = False): """ Generate soap headers dictionary to send with a request :param Passport passport: holds the authentication credentials :param TokenPassport tokenPassport: holds the token based authentication details :param ApplicationInfo applicationInfo: contains the application Id :return: the dictionary representing the headers :rtype: dict :raises :class:`~netsuitesdk.exceptions.NetSuiteError`: if user is neither logged in nor a passport or tokenPassport was passed """ soapheaders = {} if self._is_authenticated: # User is already logged in, so there is no # need to pass authentication details in the header pass elif self._consumer_key is not None: soapheaders['tokenPassport'] = self._generate_token_passport() elif self._passport is not None: soapheaders['passport'] = self._passport else: raise NetSuiteError( 'Must either login first or pass passport or tokenPassport to request header.' ) if include_search_preferences: soapheaders['searchPreferences'] = self._search_preferences return soapheaders def request(self, name, *args, **kwargs): """ Make a NetSuite web service request :param str name: the name of the request service ('get', 'search', ...) :return: the request response object :rtype: the exact type depends on the request """ method = getattr(self._service_proxy, name) # call the service: include_search_preferences = (name == 'search') response = method( *args, _soapheaders=self._build_soap_headers( include_search_preferences=include_search_preferences), **kwargs) return response def get(self, recordType, internalId=None, externalId=None): """ Make a get request to retrieve an object of type recordType specified by either internalId or externalId :param str recordType: the complex type (e.g. 'vendor') :param int internalId: id specifying the record to be retrieved :param str externalId: str specifying the record to be retrieved :return: the matching record in case of success :rtype: Record :raises ValueError: if neither internalId nor externalId was passed """ recordType = recordType[0].lower() + recordType[1:] if internalId is not None: record_ref = self.RecordRef(type=recordType, internalId=internalId) elif externalId is not None: record_ref = self.RecordRef(type=recordType, externalId=externalId) else: raise ValueError( 'Either internalId or externalId is necessary to make a get request.' ) response = self.request('get', baseRef=record_ref) response = response.body.readResponse status = response.status if status.isSuccess: record = response['record'] return record else: exc = self._request_error('get', detail=status['statusDetail'][0]) raise exc def getAll(self, recordType): """ Make a getAll request to retrieve all objects of type recordType. All NetSuite types available for a search are listed under :const:`constants.GET_ALL_RECORD_TYPES`. :param str recordType: the complex type (e.g. 'vendor') :param int internalId: id specifying the record to be retrieved :param str externalId: str specifying the record to be retrieved :return: the matching record in case of success :rtype: Record """ recordType = recordType[0].lower() + recordType[1:] record = self.GetAllRecord(recordType=recordType) response = self.request('getAll', record=record) response = response.body.getAllResult status = response.status if status.isSuccess: records = response['recordList']['record'] return records else: exc = self._request_error('getAll', detail=status['statusDetail'][0]) raise exc def search_factory(self, type_name, **kwargs): _type_name = type_name[0].lower() + type_name[1:] if not _type_name in SEARCH_RECORD_TYPES: raise NetSuiteTypeError( '{} is not a searchable NetSuite type!'.format(type_name)) search_cls_name = '{}Search'.format(type_name) search_cls = self.get_complex_type(search_cls_name) search_record = search_cls(**kwargs) return search_record def basic_search_factory(self, type_name, **kwargs): _type_name = type_name[0].lower() + type_name[1:] if not _type_name in SEARCH_RECORD_TYPES: raise NetSuiteTypeError( '{} is not a searchable NetSuite type!'.format(type_name)) basic_search_cls_name = '{}SearchBasic'.format(type_name) basic_search_cls = self.get_complex_type(basic_search_cls_name) basic_search = basic_search_cls() for key, value in kwargs.items(): setattr(basic_search, key, value) return basic_search def search(self, searchRecord): """ Make a search request to retrieve an object of type recordType specified by internalId. All NetSuite types available for a search are listed under :const:`constants.SEARCH_RECORD_TYPES`. :param Record searchRecord: data object holding all parameters for the search. The utility function `search_factory` can be used to create one. :return: result records and meta data about search result :rtype: SearchResult(type): int totalRecords: total number of records int pageSize: number of records per page int totalPages: number of pages int pageIndex: index of actual returned result page str searchId: identifier for the search list records: the actual records found """ response = self.request('search', searchRecord=searchRecord) result = response.body.searchResult status = result.status success = status.isSuccess if success: if hasattr(result.recordList, 'record'): result.records = result.recordList.record return result else: # Did not find anything result.records = None return result else: exc = self._request_error('search', detail=status['statusDetail'][0]) raise exc def searchMoreWithId(self, searchId, pageIndex): response = self.request('searchMoreWithId', searchId=searchId, pageIndex=pageIndex) result = response.body.searchResult status = result.status success = status.isSuccess if success: result.records = result.recordList.record return result else: exc = self._request_error('searchMoreWithId', detail=status['statusDetail'][0]) raise exc def upsert(self, record): """ Add an object of type recordType with given externalId.. If a record of specified type with matching externalId already exists, it is updated. Usage example: customer = self.Customer() customer.externalId = 'customer_id' customer.companyName = 'Test Inc.' customer.email = '*****@*****.**' self.upsert(record=customer) :param str recordType: the complex type (e.g. either 'Customer' or 'vendors') :param str externalId: str specifying the record to be retrieved :return: a reference to the newly created or updated record (in case of success) :rtype: RecordRef """ response = self.request('upsert', record=record) response = response.body.writeResponse status = response.status if status.isSuccess: record_ref = response['baseRef'] self.logger.debug( 'Successfully updated record of type {type}, internalId: {internalId}, externalId: {externalId}' .format(type=record_ref['type'], internalId=record_ref['internalId'], externalId=record_ref['externalId'])) return record_ref else: exc = self._request_error('upsert', detail=status['statusDetail'][0]) raise exc
class GPWebService(object): """Class for interacting with MS Dynamics GP Web Services""" def __init__(self): if settings.GP_WS_ENABLED: cache = SqliteCache(timeout=30 * 24 * 60 * 60) session = Session() session.auth = HttpNtlmAuth( settings.GP_WS_USERNAME, settings.GP_WS_PASSWORD) self.client = Client( settings.GP_WS_URL, transport=Transport(session=session, cache=cache) ) self.ws_factory1 = self.client.type_factory('ns1') self.ws_factory2 = self.client.type_factory('ns2') company = self.ws_factory2.CompanyKey(settings.GP_COMPANY_ID) self.service_context = self.ws_factory2.Context( OrganizationKey=company, CurrencyType='Local' ) def get_item_by_id(self, item_id): if settings.GP_WS_ENABLED: return self.client.service.GetItemByKey( key=self.ws_factory1.ItemKey(Id=item_id), context=self.service_context ) else: return {'Description': 'Product Description Here'} def get_invoice_list(self, customer_id): if settings.GP_WS_ENABLED: criteria = { 'TransactionState': self.ws_factory1.ListRestrictionOfNullableOfSalesTransactionState( 'Work'), 'CustomerId': self.ws_factory1.LikeRestrictionOfString( customer_id), 'Scope': 'Return All' } return self.client.service.GetSalesInvoiceList( criteria=criteria, context=self.service_context) or [] else: return [{ 'Key': { 'CompanyKey': { 'Id': 2 }, 'Id': '092306' }, }] def get_invoice_detail(self, invoice_id): if settings.GP_WS_ENABLED: return self.client.service.GetSalesInvoiceByKey( key={'Id': invoice_id}, context=self.service_context) else: return { 'Key': { 'CompanyKey': { 'Id': 2L }, 'Id': '092306' }, 'BatchKey': { 'CompanyKey': { 'Id': 1L }, 'Source': 'Sales Entry', 'Id': 'Transfer 02/24', 'CreatedDateTime': datetime.datetime(1900, 1, 1, 0, 0) }, 'Type': 'Invoice', 'Date': datetime.datetime(2017, 2, 8, 0, 0), 'CustomerName': 'Texas Education Agency', 'CustomerPONumber': '00001251811', 'RequestedShipDate': datetime.datetime(2017, 1, 25, 0, 0), 'Comment': 'We Appreciate Your Business', 'LineTotalAmount': { 'Currency': 'USD', 'Value': Decimal('2120.00000'), 'DecimalDigits': 2L }, 'TotalAmount': { 'Currency': 'USD', 'Value': Decimal('2120.00000'), 'DecimalDigits': 2L }, 'ActualShipDate': datetime.datetime(2017, 2, 6, 0, 0), 'InvoiceDate': datetime.datetime(2017, 2, 8, 0, 0), 'OriginalSalesDocumentKey': { 'CompanyKey': None, 'Id': 'TEA0000125614' }, 'ShipToAddressKey': { 'CompanyKey': { 'Id': 2L }, 'CustomerKey': { 'CompanyKey': { 'Id': 2L }, 'Id': '7TEX701' }, 'Id': '187906' }, 'ShipToAddress': { 'Extensions': None, 'Line1': 'Breanna Murphy [email protected]', 'Line2': 'Leggett High School', 'Line3': 'P.O. Box 68', 'City': 'Leggett', 'State': 'TX', 'PostalCode': '77350', 'CountryRegion': 'United States', }, 'UserDefined': { 'Date01': datetime.datetime(2017, 2, 8, 0, 0), 'Date02': None, 'List01': '1', 'List02': '12.00', 'List03': None, 'Text01': '5', 'Text02': None, 'Text03': '0000123394', 'Text04': '0000141474', 'Text05': '1z79x8540353316852' }, 'Lines': { 'SalesInvoiceLine': [ { 'UnitPrice': { 'Currency': 'USD', 'Value': Decimal('801.00000'), 'DecimalDigits': 2 }, 'TotalAmount': { 'Currency': 'USD', 'Value': Decimal('801.00000'), 'DecimalDigits': 2 }, 'Quantity': { 'Value': Decimal('1.00000'), 'DecimalDigits': 0 }, 'Discount': { 'Amount': None, 'Percent': { 'Value': Decimal('0'), 'DecimalDigits': 2L } }, 'ItemDescription': 'Some Product Description', 'UofM': 'Each', 'ItemKey': { 'CompanyKey': { 'Id': 2L }, 'Id': '9781603339056' }, }, ] }, }
def __init__(self, account=None, caching=None): """ Initialize the Zeep SOAP client, parse the xsd specifications of Netsuite and store the complex types as attributes of this instance. :param str account: Account ID to connect to :param dict caching: The available cache settings are the following caching['enable'] bool: Indicates if caching['timeout'] int: Timeout in seconds for caching. If None, defaults to 30 days caching['path'] str: The path to store the database files caching['engine'] str: The Database engine used for caching. """ self.logger = logging.getLogger(self.__class__.__name__) assert account, 'Invalid account' assert '-' not in account, 'Account cannot have hyphens, it is likely an underscore' self._account = account self._wsdl_url = self.WSDL_URL_TEMPLATE.format( account=account.replace('_', '-')) self._datacenter_url = self.DATACENTER_URL_TEMPLATE.format( account=account.replace('_', '-')) if caching is None: caching = {} # Make sure that caching argument is an instance of dict assert isinstance( caching, dict), '"caching" argument must be an instance of dict' # Allowed cache setting keys allowed_cache_settings = ['enable', 'engine', 'timeout', 'path'] allowed_cache_engines = ['sqlite'] # Default cache settings cache_settings = { 'enable': True, 'engine': 'sqlite', 'timeout': 2592000, 'path': os.path.dirname(os.path.abspath(__file__)) } # Filter out user input and get only the allowed keys cache_settings_input = { key: caching[key] for key in caching if key in allowed_cache_settings } # Merge default cache settings with input cache settings cache_settings.update(cache_settings_input) # Default transport set to None transport = None if cache_settings['enable']: # Make sure that provided cache engine is allowed assert cache_settings['engine'] in allowed_cache_engines, \ f'Cache engine "{cache_settings["engine"]}" is not available. You can use one of the following engines: ' + ','.join(allowed_cache_engines) path = os.path.join(cache_settings['path'], 'cache.db') timeout = cache_settings['timeout'] # Sqlite cache engine if cache_settings['engine'] == 'sqlite': cache = SqliteCache(path=path, timeout=timeout) transport = Transport(cache=cache) # Initialize the Zeep Client self._client = Client(self._wsdl_url, transport=transport) # default service points to wrong data center. need to create a new service proxy and replace the default one self._service_proxy = self._client.create_service( '{urn:platform_2019_1.webservices.netsuite.com}NetSuiteBinding', self._datacenter_url) # Parse all complex types specified in :const:`~netsuitesdk.netsuite_types.COMPLEX_TYPES` # and store them as attributes of this instance. Same for simple types. self._namespaces = {} self._init_complex_types() self._init_simple_types() self._app_info = None self._is_authenticated = False self.set_search_preferences()
def main(): global fiasfile global oldfiasfile global config fiasfile = '.\\update\\full\\fias_dbf.rar' oldfiasfile = '.\\update\\full\\fias_dbf.old.rar' wsdl = 'http://fias.nalog.ru/WebServices/Public/DownloadService.asmx?WSDL' # ссылка на сервис получения обновлений сайт Налоговой config = ConfigObj('fias.cfg', encoding='UTF8') use_proxy = config.get('Proxy').as_bool('use_proxy') if use_proxy: proxy_list = config['Proxy']['Proxy'] # proxy = {'http': 'http://' + proxy_list} proxy = {'http': 'http://' + proxy_list, 'https': 'https://' + proxy_list} session = Session() session.verify = False session.proxies = proxy transport = Transport(session=session) client = Client(wsdl=wsdl, transport=transport) else: client = Client(wsdl=wsdl) maxdeltaupdate = int(config['Update']['maxdeltaupdate']) if maxdeltaupdate != 0: # при 0 не используем любое количество delta обновлений currentdeltaupdate = len(os.listdir('.\\update\\delta\\')) if currentdeltaupdate > maxdeltaupdate: # необходимо закачать полную базу и удалить дельты isRen = False if len(os.listdir(".\\update\\full")) != 0: isRen = True fiasfile = ".\\update\\full\\" + os.listdir(".\\update\\full")[0] oldfiasfile = fiasfile + '.old' os.rename(fiasfile, oldfiasfile) try: if download_fias_full(use_proxy, proxy): os.remove(oldfiasfile) del_delta_update() else: os.rename(oldfiasfile, fiasfile) except Exception as inst: if isRen: os.rename(oldfiasfile, fiasfile) print(inst) return else: # делаем все проверки if config['Update']['fullbase'] == '': # в конфиге дата отсутствует. Надо брать полную последнюю базу if len(os.listdir(".\\update\\full")) != 0: # в каталоге полной базы есть файлы if os.path.isfile('.\\update\\full\\fias_dbf.rar'): # получаем размер локального файла localfilesize = os.path.getsize('.\\update\\full\\fias_dbf.rar') # на диске есть файл fias_dbf.rar - определяем за какую он дату spisok = client.service.GetAllDownloadFileInfo() # rint(spisok) check_fias = False for row in spisok: remotefilesize = getRemoteFileLength(row.FiasCompleteDbfUrl, use_proxy, proxy) if localfilesize == remotefilesize: # нашли дату check_fias = True du = datetime.datetime.strptime((row.FiasCompleteDbfUrl).split('/')[-2], "%Y%m%d").date() config['Update']['fullbase'] = du.strftime("%Y%m%d") config.write() break if check_fias: # нашли дату полной базы для файла на диске print('нашли дату полной базы для файла на диске ' + du.strftime("%Y%m%d")) get_delta(spisok, du, use_proxy, proxy) else: # не нашли дату полной базы для файла на диске print('не нашли дату полной базы для файла на диске') else: print('файл есть но он не fias_dbf.rar') else: # Скачиваем файл http://fias.nalog.ru/Public/Downloads/Actual/VerDate.txt определяем дату полной базы if os.path.isfile('.\\update\\VerDate.txt'): os.remove('.\\update\\VerDate.txt') str_lastupdatedate = open(getFile('http://fias.nalog.ru/Public/Downloads/Actual/VerDate.txt', use_proxy, '.\\update\\', proxy), 'r').read() d_lastupdate = datetime.datetime.strptime(str_lastupdatedate, "%d.%m.%Y").date() sd = d_lastupdate.strftime("%Y%m%d") # в каталоге с архивом полной базы файлов нет. Берем качаем последнюю доступную url_fb = 'http://fias.nalog.ru/Public/Downloads/Actual/fias_dbf.rar' remotefilesize = getRemoteFileLength(url_fb, use_proxy, proxy) getFile(url_fb, use_proxy, '.\\update\\full\\', proxy, '.' + sd + '.tmp') # localfilesize = os.path.getsize(getFile(url_fb, use_proxy, '.\\update\\full\\', proxy, '.' + sd + '.tmp')) if os.path.isfile('.\\update\\full\\fias_dbf.rar'): print('скачали полную базу ФИАС за %s' % d_lastupdate.strftime("%d/%m/%Y")) config['Update']['fullbase'] = sd config.write() else: print('не скачали полностью полную базу ФИАС за %s' % d_lastupdate.strftime("%d/%m/%Y")) # print(os.listdir(".\\update\\full")) else: # есть в конфиге последняя дата. Надо проверить нахождение файла на диске # дальше приступаем к проверке дельта обновлений full_base_update_date = datetime.datetime.strptime(config['Update']['fullbase'], '%Y%m%d').date() if os.path.isfile('.\\update\\full\\fias_dbf.rar'): localfilesize = os.path.getsize('.\\update\\full\\fias_dbf.rar') # 'http://fias.nalog.ru/Public/Downloads/20180705/fias_dbf.rar' remotefilesize = getRemoteFileLength('http://fias.nalog.ru/Public/Downloads/' + full_base_update_date.strftime("%Y%m%d") + '/fias_dbf.rar', use_proxy, proxy) if localfilesize == remotefilesize: # размер локального и удаленного файла совпадают spisok = client.service.GetAllDownloadFileInfo() # качаем дельты, если они есть get_delta(spisok, full_base_update_date, use_proxy, proxy) else: # размер локального и удаленного файла не совпадают isRen = False if len(os.listdir(".\\update\\full")) != 0: isRen = True fiasfile = ".\\update\\full\\" + os.listdir(".\\update\\full")[0] oldfiasfile = fiasfile + '.old' os.rename(fiasfile, oldfiasfile) try: if download_fias_full(use_proxy, proxy): os.remove(oldfiasfile) del_delta_update() else: os.rename(oldfiasfile, fiasfile) except Exception as inst: if isRen: os.rename(oldfiasfile, fiasfile) print(inst)
def login(request): logfile = open('AuthServerLog.txt', 'a') time = datetime.now() # print login post to the logfile print("login post " + str(time), file=logfile) # get data from the json posted to the method try: decoded = request.body.decode('utf-8') response = json.loads(decoded) username = response['username'] password = response['password'] except (KeyError, json.JSONDecodeError) as err: print("400 bad credentials " + str(err) + " " + str(time), file=logfile) logfile.close() return JsonResponse(data={ "reason": "Your data is not formatted the proper way", "helper": "[POST] at /login and then a JSON formatted like this, " + "{'username':'******','password':'******'}" }, status=status.HTTP_400_BAD_REQUEST) except RuntimeError: print("500 internal server error when decoding json" + str(time), file=logfile) logfile.close() return JsonResponse(data={ "reason": "There was an internal server error", "helper": "Contact group 20" }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) # Create a soap client object url = 'http://javabog.dk:9901/brugeradmin?wsdl' # try and get the userobject from javabog.dk try: client = Client(url) # Get user and create token response = client.service.hentBruger(username, password) # create the userobject for GameService user_object = { 'player': { "username": response["brugernavn"], "first_name": response["fornavn"], "last_name": response["efternavn"], "email": response["email"], "study_programme": response["studeretning"], "high_score": 0 } } # create the user_token. This should be exchanged for a creation of a JWT. user_token = str(uuid.uuid1()) # Register user at gameservice and get gameservice ip and port game_service_ip, game_service_port, player = register_user_with_game_service( AUTH_SERVICE_ACCESS_KEY, user_token, user_object, logfile) if game_service_ip == None: return JsonResponse(data={ "reason": "Could not login with GameService", "helper": "Contact group 20" }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) # If gameservice responds with proper data, # return the userobject, usertoken and gameservice ip and port to client. user_object['user_token'] = user_token user_object['game_service_ip'] = game_service_ip user_object['game_service_port'] = game_service_port user_object['player'] = player print("user returned to client with token: " + user_token + ", ip: " + game_service_ip + ", port: " + game_service_port + " and player: " + str(player) + ", " + str(time), file=logfile) return JsonResponse(user_object, status=status.HTTP_200_OK) # if the communication with javabog.dk did not go through as expected except RuntimeError as e: print("500 internal server error when fetching user " + str(time) + " error: " + e.__str__(), file=logfile) logfile.close() return JsonResponse(data={ "reason": "There was an internal server error", "helper": "Contact group 20" }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) except Fault as e: if "Forkert brugernavn eller adgangskode" in str(e): print("401 bad credentials " + str(time), file=logfile) return JsonResponse(data={ "reason": "Your credentials were not correct", "helper": "Use the proper credentials" }, status=status.HTTP_401_UNAUTHORIZED) logfile.close() except: print( "user not returned to client, could not register user with javabog.dk due to connection error at, " + str(time), file=logfile) logfile.close() return JsonResponse(data={ "reason": "Could not login with Javabog.dk do to connection error", "helper": "Contact group 20" }, status=status.HTTP_404_NOT_FOUND)
mssg = 'Request Subtracter' # ping if registry is up response = pyping.ping(registry_hard) if response.ret_code == 0: print('registry at ' + registry_hard + ' is up.') registry = registry_hard else: print('registry at ' + registry_hard + ' is down!') registry = replica_hard PORT = PORT2 #create a socket object with IPv4 and TCP protocol s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #connect to a server with registry address and specified port s.connect((registry, PORT)) #send the user input to the server s.send(mssg) #receive and print to a screen wsdl_received = s.recv(1024) print('received the following WSDL from ' + registry + ': ' + wsdl_received) s.close() #generate a SOAP client using the received WSDL client = Client(wsdl_received + '?wsdl') result = client.service.subtractNum(5, 2) print('The difference of 5 and 2 is') print(result)
#-*- coding: utf8 -*- from zeep import Client import datetime # from datetime import datetime import timestring client = Client( 'http://localhost:8733/Design_Time_Addresses/lib_wfc/Service1/?wsdl') isAuth = 0 userСhoice = 0 global TOKEN TOKEN = "" def price_def(order): order_price = 500 if order['quick_price'] == 500: order_price += 500 prices = [2000, 1000, 500, 100] params = [ int(order['lenght']), int(order['width']), int(order['height']), int(order['weight']) ] for param in params: for price in prices: if param > price: order_price += price break return order_price
from zeep import Client # realizando uma integração de um serviço soap com python client = Client('http://www.soapclient.com/xml/soapresponder.wsdl') result = client.service.Method1('Hello', 'Bye') print(result)
from datetime import datetime from pathlib import Path import pandas as pd import pytz import time from zeep import Client from mappings import counties root = Path(__file__).parents[1] client = Client("https://tools.rki.de/SurvStat/SurvStatWebService.svc?wsdl") factory = client.type_factory("ns2") def fetch_county(county): res = client.service.GetOlapData( { "Language": "German", "Measures": {"Count": 0}, "Cube": "SurvStat", # Totals still included, setting `true` yields duplicates "IncludeTotalColumn": False, "IncludeTotalRow": False, "IncludeNullRows": False, "IncludeNullColumns": True,
def setUp(self): from spyne.test.interop._test_soap_client_base import run_server run_server('http') self.client = Client("http://localhost:9754/?wsdl") self.ns = "spyne.test.interop.server"
from django.shortcuts import render from django.views.generic.base import TemplateView from django.views.decorators.csrf import csrf_exempt from django.utils.decorators import method_decorator from django.http import HttpResponse from .utils import search_person_by_fio url = 'http://test.fedresurs.ru/MessageService/WebService.svc?singleWsdl' u = 'demowebuser' p = 'Ax!761BN' session = Session() session.auth = HTTPDigestAuth(u, p) client = Client(url, transport=Transport(session=session)) class LastPeriodFormView(TemplateView): template_name = 'last_period_form.html' class FioFormView(TemplateView): template_name = 'fio_form.html' @method_decorator(csrf_exempt, name='dispatch') class GetIdsView(View): def post(self, request): start = request.POST.get('start') end = request.POST.get('end')
from zeep import Client client = Client('http://localhost:7777/ws/AcademicoWebService?wsdl') while True: print('1 - Listar Estudiantes') print('2 - Consultar una asignatura') print('3 - Consultar un profesor') print('4 - Salir') op = int(input('\nElija la opcion que desea: ')) if (op == 1): list = client.service.getAllEstudiante() for std in list: print("Matricula: {0}. Nombre: {1}.".format( std['matricula'], std['nombre'])) elif (op == 2): asig = input("\nCodigo de la Asignatura: ") print(client.service.getAsignatura(asig)) elif (op == 3): prof = input("\nCodigo del Profesor: ") print(client.service.getProfesor(prof)) elif (op == 4): break
class XMLAConnection(object): @classmethod def addMethod(cls, funcname, func): return setattr(cls, funcname, func) @classmethod def setupMembers(cls): def getFunc(schemaName): return lambda this, *args, **kw: cls.Discover(this, schemaName, *args, **kw) for schemaName in xmla1_1_rowsets: mname = schemaNameToMethodName(schemaName) cls.addMethod( mname, getFunc(schemaName) ) def __init__(self, url, location, sslverify, **kwargs): if "session" in kwargs: session = kwargs["session"] del kwargs["session"] transport = Transport(session=session) else: transport = Transport() if "auth" in kwargs: transport.session.auth = kwargs["auth"] del kwargs["auth"] transport.session.verify = sslverify self.sessionplugin=SessionPlugin(self) plugins=[self.sessionplugin] if "log" in kwargs: log = kwargs.get("log") if isinstance(log, Plugin): plugins.append(log) elif log == True: plugins.append(LogRequest()) del kwargs["log"] self.client = Client(url, transport=transport, # cache=None, unwrap=False, plugins=plugins) self.service = self.client.create_service(ns_name(schema_xmla,"MsXmlAnalysisSoap"), location) self.client.set_ns_prefix(None, schema_xmla) # optional, call might fail self.getMDSchemaLevels = lambda *args, **kw: self.Discover("MDSCHEMA_LEVELS", *args, **kw) self.setListenOnSessionId(False) self.setSessionId(None) self._soapheaders=None def getListenOnSessionId(self): return self.listenOnSessionId def setListenOnSessionId(self, trueOrFalse): self.listenOnSessionId = trueOrFalse def setSessionId(self, sessionId): self.sessionId = sessionId def Discover(self, what, restrictions=None, properties=None): rl = as_etree(restrictions, "RestrictionList") pl = as_etree(properties, "PropertyList") try: #import pdb; pdb.set_trace() doc=self.service.Discover(RequestType=what, Restrictions=rl, Properties=pl, _soapheaders=self._soapheaders) root = fromETree(doc.body["return"]["_value_1"], ns=schema_xmla_rowset) res = getattr(root, "row", []) if res: res = aslist(res) except Fault as fault: raise XMLAException(fault.message, dictify(fromETree(fault.detail, ns=None))) #logger.debug( res ) return res def Execute(self, command, dimformat="Multidimensional", axisFormat="TupleFormat", **kwargs): if isinstance(command, stringtypes): command=as_etree({"Statement": command}) props = {"Format":dimformat, "AxisFormat":axisFormat} props.update(kwargs) plist = as_etree({"PropertyList":props}) try: res = self.service.Execute(Command=command, Properties=plist, _soapheaders=self._soapheaders) root = res.body["return"]["_value_1"] return TupleFormatReader(fromETree(root, ns=schema_xmla_mddataset)) except Fault as fault: raise XMLAException(fault.message, dictify(fromETree(fault.detail, ns=None))) def BeginSession(self): bs= self.client.get_element(ns_name(schema_xmla,"BeginSession"))(mustUnderstand=1) self.setListenOnSessionId(True) cmd = as_etree("Statement") self.service.Execute(Command=cmd,_soapheaders={"BeginSession":bs}) self.setListenOnSessionId(False) sess= self.client.get_element(ns_name(schema_xmla,"Session"))(SessionId=self.sessionId, mustUnderstand = 1) self._soapheaders={"Session":sess} def EndSession(self): if self.sessionId is not None: es= self.client.get_element(ns_name(schema_xmla,"EndSession"))(SessionId=self.sessionId, mustUnderstand = 1) cmd = as_etree("Statement") self.service.Execute(Command=cmd, _soapheaders={"EndSession":es}) self.setSessionId(None) self._soapheaders=None
def request_apple_pay_authorization(self, basket, billing_address, payment_token): """ Authorizes an Apple Pay payment. For details on the process, see the CyberSource Simple Order API documentation at https://www.cybersource.com/developers/integration_methods/apple_pay/. Args: basket (Basket) billing_address (BillingAddress) payment_token (dict) Returns: HandledProcessorResponse Raises: GatewayError """ try: client = Client(self.soap_api_url, wsse=UsernameToken(self.merchant_id, self.transaction_key)) card_type = APPLE_PAY_CYBERSOURCE_CARD_TYPE_MAP[ payment_token['paymentMethod']['network'].lower()] bill_to = { 'firstName': billing_address.first_name, 'lastName': billing_address.last_name, 'street1': billing_address.line1, 'street2': billing_address.line2, 'city': billing_address.line4, 'state': billing_address.state, 'postalCode': billing_address.postcode, 'country': billing_address.country.iso_3166_1_a2, 'email': basket.owner.email, } purchase_totals = { 'currency': basket.currency, 'grandTotalAmount': str(basket.total_incl_tax), } encrypted_payment = { 'descriptor': 'RklEPUNPTU1PTi5BUFBMRS5JTkFQUC5QQVlNRU5U', 'data': base64.b64encode( json.dumps(payment_token['paymentData']).encode('utf-8')), 'encoding': 'Base64', } card = { 'cardType': card_type, } auth_service = { 'run': 'true', } capture_service = { 'run': 'true', } # Enable Export Compliance for SDN validation, amongst other checks. # See https://www.cybersource.com/products/fraud_management/export_compliance/ export_service = { 'run': 'true', } item = [{ 'id': index, 'productCode': line.product.get_product_class().slug, 'productName': clean_field_value(line.product.title), 'quantity': line.quantity, 'productSKU': line.stockrecord.partner_sku, 'taxAmount': str(line.line_tax), 'unitPrice': str(line.unit_price_incl_tax), } for index, line in enumerate(basket.all_lines())] response = client.service.runTransaction( merchantID=self.merchant_id, merchantReferenceCode=basket.order_number, billTo=bill_to, purchaseTotals=purchase_totals, encryptedPayment=encrypted_payment, card=card, ccAuthService=auth_service, ccCaptureService=capture_service, exportService=export_service, paymentSolution='001', item=item, ) except: msg = 'An error occurred while authorizing an Apple Pay (via CyberSource) for basket [{}]'.format( basket.id) logger.exception(msg) raise GatewayError(msg) request_id = response.requestID ppr = self.record_processor_response(serialize_object(response), transaction_id=request_id, basket=basket) if response.decision == 'ACCEPT': currency = basket.currency total = basket.total_incl_tax transaction_id = request_id return HandledProcessorResponse( transaction_id=transaction_id, total=total, currency=currency, card_number='Apple Pay', card_type=CYBERSOURCE_CARD_TYPE_MAP.get(card_type)) else: msg = ( 'CyberSource rejected an Apple Pay authorization request for basket [{basket_id}]. ' 'Complete response has been recorded in entry [{response_id}]') msg = msg.format(basket_id=basket.id, response_id=ppr.id) logger.warning(msg) raise GatewayError(msg)
import simplejson as json from scipy import stats from itertools import chain import csv import warnings import math import time from lib.awdbToolsJson import padMissingData, ordinal, getBasinSites py.init_notebook_mode(connected=True) this_dir = path.dirname(path.abspath(__file__)) master_dir = path.dirname(this_dir) wsdl = r"https://wcc.sc.egov.usda.gov/awdbWebService/services?WSDL" transport = Transport(timeout=300, cache=InMemoryCache()) awdb = Client(wsdl=wsdl, transport=transport, strict=False) dt = datetime.datetime date = datetime.date today = dt.utcnow() - datetime.timedelta(hours=8) def updtChart(basinName, basinSites): basin = basinName print('Working on PREC POR Chart for ' + basinName) statsData = [] minData = [] maxData = [] meanData = [] lowestData = [] highestData = []
from zeep import Client aneroid = '302:OR:SNTL' brighton = '366:UT:SNTL' client = Client(wsdl='https://wcc.sc.egov.usda.gov/awdbWebService/services?WSDL') # service areYouThere takes no parameters print(client.service.areYouThere()) # service getAllForecastsForStation returns an ns0:forecastFull[] list...whatever that means print(len(client.service.getAllForecastsForStation(brighton, '1980-10-01 00:00:00', '2100-01-01 00:00:00'))) def get_metadata(triplet): metadata = client.service.getStationMetadata(triplet) return metadata print(get_metadata(brighton)) print(get_metadata(aneroid))
def test_parse_soap_wsdl(): wsdl_file = io.StringIO(u""" <?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/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/" targetNamespace="http://tests.python-zeep.org/"> <wsdl:types> <xsd:schema targetNamespace="http://tests.python-zeep.org/" xmlns:tns="http://tests.python-zeep.org/" elementFormDefault="qualified"> <xsd:element name="input" type="xsd:string"/> <xsd:element name="output"> <xsd:complexType> <xsd:sequence> <xsd:element name="item_1" type="tns:type_1"/> <xsd:element name="item_2" type="tns:type_2"/> </xsd:sequence> </xsd:complexType> </xsd:element> <xsd:complexType name="type_1"> <xsd:sequence> <xsd:element name="subitem_1" type="xsd:string"/> <xsd:element name="subitem_2" type="xsd:string"/> <xsd:element name="subitem_3" type="tns:type_3"/> </xsd:sequence> </xsd:complexType> <xsd:complexType name="type_2"> <xsd:sequence> <xsd:element name="subitem_1" type="tns:type_1"/> <xsd:element name="subitem_2" type="xsd:string"/> </xsd:sequence> </xsd:complexType> <xsd:complexType name="type_3" nillable="true"> <xsd:sequence> </xsd:sequence> </xsd:complexType> </xsd:schema> </wsdl:types> <wsdl:message name="TestOperationRequest"> <wsdl:part name="response" element="tns:input"/> </wsdl:message> <wsdl:message name="TestOperationResponse"> <wsdl:part name="response" element="tns:output"/> </wsdl:message> <wsdl:portType name="TestPortType"> <wsdl:operation name="TestOperation"> <wsdl:input message="TestOperationRequest"/> <wsdl:output message="TestOperationResponse"/> </wsdl:operation> </wsdl:portType> <wsdl:binding name="TestBinding" type="tns:TestPortType"> <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/> <wsdl:operation name="TestOperation"> <soap:operation soapAction=""/> <wsdl:input name="TestOperationRequest"> <soap:body use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" /> </wsdl:input> <wsdl:output name="TestOperationResponse"> <soap:body use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" /> </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()) content = """ <?xml version="1.0"?> <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tns="http://tests.python-zeep.org/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soapenv:Body> <tns:TestOperationResponse> <tns:output> <tns:item_1 href="#id0"/> <tns:item_2> <tns:subitem_1> <tns:subitem_1>foo</tns:subitem_1> <tns:subitem_2>bar</tns:subitem_2> </tns:subitem_1> <tns:subitem_2>bar</tns:subitem_2> </tns:item_2> </tns:output> </tns:TestOperationResponse> <multiRef id="id0"> <tns:subitem_1>foo</tns:subitem_1> <tns:subitem_2>bar</tns:subitem_2> <tns:subitem_3 xmlns:tns2="http://tests.python-zeep.org/" xsi:type="tns2:type_3"></tns:subitem_3> </multiRef> </soapenv:Body> </soapenv:Envelope> """.strip() client = Client( wsdl_file, transport=Transport(), ) response = stub(status_code=200, headers={}, content=content) operation = client.service._binding._operations['TestOperation'] result = client.service._binding.process_reply(client, operation, response) assert result.item_1.subitem_1 == 'foo' assert result.item_1.subitem_2 == 'bar' assert result.item_2.subitem_1.subitem_1 == 'foo' assert result.item_2.subitem_1.subitem_2 == 'bar' assert result.item_2.subitem_2 == 'bar'
class TestZeep(unittest.TestCase): def setUp(self): from spyne.test.interop._test_soap_client_base import run_server run_server('http') transport = Transport(cache=False) self.client = Client("http://localhost:9754/?wsdl", transport=transport) self.ns = "spyne.test.interop.server" def get_inst(self, what): return self.client.get_type(what)() def test_echo_datetime(self): val = datetime.now() ret = self.client.service.echo_datetime(val) assert val == ret def test_echo_datetime_with_invalid_format(self): val = datetime.now() ret = self.client.service.echo_datetime_with_invalid_format(val) assert val == ret def test_echo_date(self): val = datetime.now().date() ret = self.client.service.echo_date(val) assert val == ret def test_echo_date_with_invalid_format(self): val = datetime.now().date() ret = self.client.service.echo_date_with_invalid_format(val) assert val == ret def test_echo_time(self): val = datetime.now().time() ret = self.client.service.echo_time(val) assert val == ret def test_echo_time_with_invalid_format(self): val = datetime.now().time() ret = self.client.service.echo_time_with_invalid_format(val) assert val == ret def test_echo_simple_boolean_array(self): val = [False, False, False, True] ret = self.client.service.echo_simple_boolean_array(val) assert val == ret def test_echo_boolean(self): val = True ret = self.client.service.echo_boolean(val) self.assertEquals(val, ret) val = False ret = self.client.service.echo_boolean(val) self.assertEquals(val, ret) def test_enum(self): val = self.client.get_type("{%s}DaysOfWeekEnum" % self.ns)('Monday') ret = self.client.service.echo_enum(val) assert val == ret def test_bytearray(self): val = b"\x00\x01\x02\x03\x04" ret = self.client.service.echo_bytearray(val) assert val == ret def test_validation(self): non_nillable_class = self.client.get_type("{hunk.sunk}NonNillableClass")() non_nillable_class.i = 6 non_nillable_class.s = None try: self.client.service.non_nillable(non_nillable_class) except ZeepError as e: pass else: raise Exception("must fail") def test_echo_integer_array(self): ia = self.client.get_type('{%s}integerArray' % self.ns)() ia.integer.extend([1, 2, 3, 4, 5]) self.client.service.echo_integer_array(ia) def test_echo_in_header(self): in_header = self.client.get_type('{%s}InHeader' % self.ns)() in_header.s = 'a' in_header.i = 3 ret = self.client.service.echo_in_header(_soapheaders={ 'InHeader': in_header, }) print(ret) out_header = ret.body.echo_in_headerResult self.assertEquals(in_header.s, out_header.s) self.assertEquals(in_header.i, out_header.i) def test_echo_in_complex_header(self): in_header = self.client.get_type('{%s}InHeader' % self.ns)() in_header.s = 'a' in_header.i = 3 in_trace_header = self.client.get_type('{%s}InTraceHeader' % self.ns)() in_trace_header.client = 'suds' in_trace_header.callDate = datetime(year=2000, month=1, day=1, hour=0, minute=0, second=0, microsecond=0) ret = self.client.service.echo_in_complex_header(_soapheaders={ 'InHeader': in_header, 'InTraceHeader': in_trace_header }) print(ret) out_header = ret.body.echo_in_complex_headerResult0 out_trace_header = ret.body.echo_in_complex_headerResult1 self.assertEquals(in_header.s, out_header.s) self.assertEquals(in_header.i, out_header.i) self.assertEquals(in_trace_header.client, out_trace_header.client) self.assertEquals(in_trace_header.callDate, out_trace_header.callDate) def test_send_out_header(self): out_header = self.client.get_type('{%s}OutHeader' % self.ns)() out_header.dt = datetime(year=2000, month=1, day=1) out_header.f = 3.141592653 ret = self.client.service.send_out_header() self.assertEquals(ret.header.OutHeader.dt, out_header.dt) self.assertEquals(ret.header.OutHeader.f, out_header.f) def test_send_out_complex_header(self): out_header = self.client.get_type('{%s}OutHeader' % self.ns)() out_header.dt = datetime(year=2000, month=1, day=1) out_header.f = 3.141592653 out_trace_header = self.client.get_type('{%s}OutTraceHeader' % self.ns)() out_trace_header.receiptDate = datetime(year=2000, month=1, day=1, hour=1, minute=1, second=1, microsecond=1) out_trace_header.returnDate = datetime(year=2000, month=1, day=1, hour=1, minute=1, second=1, microsecond=100) ret = self.client.service.send_out_complex_header() self.assertEquals(ret.header.OutHeader.dt, out_header.dt) self.assertEquals(ret.header.OutHeader.f, out_header.f) self.assertEquals(ret.header.OutTraceHeader.receiptDate, out_trace_header.receiptDate) self.assertEquals(ret.header.OutTraceHeader.returnDate, out_trace_header.returnDate) def test_echo_string(self): test_string = "OK" ret = self.client.service.echo_string(test_string) self.assertEquals(ret, test_string) def __get_xml_test_val(self): return { "test_sub": { "test_subsub1": { "test_subsubsub1": ["subsubsub1 value"] }, "test_subsub2": ["subsub2 value 1", "subsub2 value 2"], "test_subsub3": [ { "test_subsub3sub1": ["subsub3sub1 value"] }, { "test_subsub3sub2": ["subsub3sub2 value"] }, ], "test_subsub4": [], "test_subsub5": ["x"], } } def test_echo_simple_class(self): val = self.client.get_type("{%s}SimpleClass" % self.ns)() val.i = 45 val.s = "asd" ret = self.client.service.echo_simple_class(val) assert ret.i == val.i assert ret.s == val.s def test_echo_class_with_self_reference(self): val = self.client.get_type("{%s}ClassWithSelfReference" % self.ns)() val.i = 45 val.sr = self.client.get_type("{%s}ClassWithSelfReference" % self.ns)() val.sr.i = 50 val.sr.sr = None ret = self.client.service.echo_class_with_self_reference(val) assert ret.i == val.i assert ret.sr.i == val.sr.i def test_echo_nested_class(self): val = self.client.get_type("{punk.tunk}NestedClass")() val.i = 45 val.s = "asd" val.f = 12.34 val.ai = self.client.get_type("{%s}integerArray" % self.ns)() val.ai.integer.extend([1, 2, 3, 45, 5, 3, 2, 1, 4]) val.simple = self.client.get_type("{%s}SimpleClassArray" % self.ns)() val.simple.SimpleClass.append(self.client.get_type("{%s}SimpleClass" % self.ns)()) val.simple.SimpleClass.append(self.client.get_type("{%s}SimpleClass" % self.ns)()) val.simple.SimpleClass[0].i = 45 val.simple.SimpleClass[0].s = "asd" val.simple.SimpleClass[1].i = 12 val.simple.SimpleClass[1].s = "qwe" val.other = self.client.get_type("{%s}OtherClass" % self.ns)() val.other.dt = datetime.now() val.other.d = 123.456 val.other.b = True ret = self.client.service.echo_nested_class(val) self.assertEquals(ret.i, val.i) self.assertEqual(ret.ai.integer, val.ai.integer) self.assertEqual(ret.ai.integer[0], val.ai.integer[0]) self.assertEquals(ret.simple.SimpleClass[0].s, val.simple.SimpleClass[0].s) self.assertEqual(ret.other.dt, val.other.dt) def test_huge_number(self): self.assertEquals(self.client.service.huge_number(), 2 ** int(1e5)) def test_long_string(self): self.assertEquals(self.client.service.long_string(), ('0123456789abcdef' * 16384)) def test_empty(self): self.client.service.test_empty() def test_echo_extension_class(self): val = self.client.get_type("{bar}ExtensionClass")() val.i = 45 val.s = "asd" val.f = 12.34 val.simple = self.client.get_type("{%s}SimpleClassArray" % self.ns)() val.simple.SimpleClass.append(self.client.get_type("{%s}SimpleClass" % self.ns)()) val.simple.SimpleClass.append(self.client.get_type("{%s}SimpleClass" % self.ns)()) val.simple.SimpleClass[0].i = 45 val.simple.SimpleClass[0].s = "asd" val.simple.SimpleClass[1].i = 12 val.simple.SimpleClass[1].s = "qwe" val.other = self.client.get_type("{%s}OtherClass" % self.ns)() val.other.dt = datetime.now() val.other.d = 123.456 val.other.b = True val.p = self.client.get_type("{hunk.sunk}NonNillableClass")() val.p.dt = datetime(2010, 6, 2) val.p.i = 123 val.p.s = "punk" val.l = datetime(2010, 7, 2) val.q = 5 ret = self.client.service.echo_extension_class(val) print(ret) self.assertEquals(ret.i, val.i) self.assertEquals(ret.s, val.s) self.assertEquals(ret.f, val.f) self.assertEquals(ret.simple.SimpleClass[0].i, val.simple.SimpleClass[0].i) self.assertEquals(ret.other.dt, val.other.dt) self.assertEquals(ret.p.s, val.p.s) def test_python_exception(self): try: self.client.service.python_exception() raise Exception("must fail") except ZeepError as e: pass def test_soap_exception(self): try: self.client.service.soap_exception() raise Exception("must fail") except ZeepError as e: pass def test_complex_return(self): ret = self.client.service.complex_return() self.assertEquals(ret.resultCode, 1) self.assertEquals(ret.resultDescription, "Test") self.assertEquals(ret.transactionId, 123) self.assertEquals(ret.roles.RoleEnum[0], "MEMBER") def test_return_invalid_data(self): try: self.client.service.return_invalid_data() raise Exception("must fail") except: pass def test_custom_messages(self): ret = self.client.service.custom_messages("test") assert ret == 'test' def test_echo_simple_bare(self): ret = self.client.service.echo_simple_bare("test") assert ret == 'test' def test_echo_complex_bare(self): val = ['abc','def'] ret = self.client.service.echo_complex_bare(val) assert ret == val
from zeep import Client c = Client('http://localhost:8000?wsdl') def get_header(): return c.get_type('ns0:Header')(Message_Type='mt', Company_ID='ci', Version='v', Source='s', Destination='d', Action_Type='read', Sequence_Number='1', Batch_ID='bi', Reference_ID='ri', Msg_Locale='ml', Msg_Time_Zone='mtz', Internal_Date_Time_Stamp='idts') def send_receive_item_bar_code(): message = c.get_type('ns0:Message')( ItemBarCodeList=c.get_type('ns0:ItemBarCodeList')(ItemBarCode=[ c.get_type('ns0:ItemBarCode')( IsPrimary='ip', ItemCode='ic', Barcode='b', Quantity='q', ActionType='at', BarcodeType='bt', Extensions=[
# CERT = 'changeme.pem' # session.verify = CERT session.auth = HTTPBasicAuth(os.getenv('USERNAME'), os.getenv('PASSWORD')) transport = Transport(session=session, timeout=10) # strict=False is not always necessary, but it allows Zeep to parse imperfect XML settings = Settings(strict=False, xml_huge_tree=True) # If debug output is requested, add the MyLoggingPlugin callback plugin = [MyLoggingPlugin()] if DEBUG else [] # Create the Zeep client with the specified settings client = Client(WSDL_FILE, settings=settings, transport=transport, plugins=plugin) # Create the Zeep service binding to AXL at the specified CUCM service = client.create_service( '{http://www.cisco.com/AXLAPIService/}AXLAPIBinding', f'https://{os.getenv("CUCM_ADDRESS")}:8443/axl/') # Create a simple phone # Of note, this appears to be the minimum set of elements required # by the schema/Zeep phone = { 'name': 'CSFTESTPHONE', 'product': 'Cisco Unified Client Services Framework', 'model': 'Cisco Unified Client Services Framework', 'class': 'Phone',
import os os.system('cls' if os.name == 'nt' else 'clear') #client = Client(wsdl='http://localhost:44383/WebService1.asmx?wsdl') #client = Client(wsdl='http://localhost:44383/WebService1.asmx') print('\n') print(' _ __ ______ ___ ____ ____ ') print(' | | / / | ___ \ | \/ | | \ \ \ ') print(' | |/ / __ _| |_/ /_ _| . . | | \ \ \ ') print(' | \ / _` | ___ \ | | | |\/| | | > > > ') print(' | |\ \ (_| | |_/ / |_| | | | |_| / / / ') print(' \_| \_/\__,_\____/ \__,_\_| |_(_) /_/_/ ') print('--------------------------------------------') print('| Cliente |') print('--------------------------------------------') client = Client(wsdl='http://localhost:44383/WebService1.asmx?wsdl') minhasComprar = [] indexCompra = 0 while True: print('\n') print('1) Listar Produtos') print('2) Comprar Produtos') print('3) Buscar Produtos') print('4) Meus Produtos') print('0) Sair') print('\n') op = input('> ') #------------------------------Listar Produtos ------------------------------------- if op == '1': x = [client.service.ObterProdutoPorMarca('todas')]
class AxirosACS(object): """ACS connection class used to perform TR069 operations on stations/board """ model = "axiros_acs_soap" def __init__(self, *args, **kwargs): """This method intializes the varible that are used in establishing connection to the ACS. The method intializes an HTTP SOAP client which will authenticate with the ACS server. :param *args: the arguments to be used if any :type *args: tuple :param **kwargs: extra args to be used if any (mainly contains username, password, ipadress and port) :type **kwargs: dict """ self.args = args self.kwargs = kwargs self.username = self.kwargs['username'] self.password = self.kwargs['password'] self.ipaddr = self.kwargs['ipaddr'] self.port = self.kwargs.get('port', None) if self.port is not None: target = self.ipaddr + ":" + self.port else: target = self.ipaddr self.wsdl = "http://" + target + "/live/CPEManager/DMInterfaces/soap/getWSDL" session = Session() session.auth = HTTPBasicAuth(self.username, self.password) self.client = Client(wsdl=self.wsdl, transport=Transport(session=session), wsse=UsernameToken(self.username, self.password)) name = "acs_server" def __str__(self): """The method is used to format the string representation of self object (instance). :returns: :class:`Response <Response>` string representation of self object. :rtype: string """ return "AxirosACS" def close(self): """Method to be implemented to close ACS connection """ pass def get_ticketId(self, cpeid, param): """ACS server maintains a ticket ID for all TR069 RPC calls. This method will contruct a TR069 GPV query, execute it and return the ticket id associated with it. :param cpeid: the serial number of the modem through which ACS communication happens. :type cpeid: string :param param: parameter to used :type param: string :raises: NA :returns: ticketid :rtype: string """ GetParameterValuesParametersClassArray_type = self.client.get_type( 'ns0:GetParameterValuesParametersClassArray') GetParameterValuesParametersClassArray_data = GetParameterValuesParametersClassArray_type( [param]) CommandOptionsTypeStruct_type = self.client.get_type( 'ns0:CommandOptionsTypeStruct') CommandOptionsTypeStruct_data = CommandOptionsTypeStruct_type() CPEIdentifierClassStruct_type = self.client.get_type( 'ns0:CPEIdentifierClassStruct') CPEIdentifierClassStruct_data = CPEIdentifierClassStruct_type( cpeid=cpeid) # get raw soap response (parsing error with zeep) with self.client.settings(raw_response=True): response = self.client.service.GetParameterValues( GetParameterValuesParametersClassArray_data, CommandOptionsTypeStruct_data, CPEIdentifierClassStruct_data) ticketid = None root = ElementTree.fromstring(response.content) for value in root.iter('ticketid'): ticketid = value.text break return ticketid def get(self, cpeid, param, wait=8): """This method is used to perform a remote procedure call (GetParameterValue) The method will query the ACS server for value against ticket_id generated during the GPV RPC call. Example usage : acs_server.get(self.cpeid, 'Device.DeviceInfo.SoftwareVersion') :param cpeid: the serial number of the modem through which ACS communication happens. :type cpeid: string :param param: parameter to be used in get :type param: string :param wait: the number of tries to be done if we are not getting proper ACS response, defaults to 8 :type wait: int :raises: NA :returns: first value of ACS reponse for the parameter. :rtype: string """ ticketid = self.get_ticketId(cpeid, param) if ticketid is None: return None return self.Axiros_GetTicketValue(ticketid, wait=wait) def getcurrent(self, cpeid, param, wait=8): """This method is used to get the key, value of the response for the given parameter from board. Example usage : acs_server.getcurrent(self.cpeid, 'Device.IP.Interface.') :param cpeid: the serial number of the modem through which ACS communication happens. :type cpeid: string :param param: parameter to be used in get :type param: string :param wait: the number of tries to be done if we are not getting proper ACS response, defaults to 8 :type wait: int :raises: NA :returns: dictionary with the key, value of the response for the given parameter. :rtype: dict """ ticketid = self.get_ticketId(cpeid, param) for i in range(wait): time.sleep(1) with self.client.settings(raw_response=True): ticket_resp = self.client.service.get_generic_sb_result( ticketid) root = ElementTree.fromstring(ticket_resp.content) for value in root.iter('code'): break if (value.text != '200'): continue dict_key_value = {} for key, value in zip(root.iter('key'), root.iter('value')): dict_key_value[key.text] = value.text return dict_key_value def set(self, cpeid, attr, value): """This method is used to set a parameter in board via TR069 RPC call (SetParameterValue). This method constructs a SPV query and sends it to ACS server ACS server will generate a ticket_id and perform the RPC call. The method will then return the value associated with the ticket_id Example usage : acs_server.set(self.cpeid, 'Device.WiFi.AccessPoint.1.AC.1.Alias', "TestSSID") :param cpeid: the serial number of the modem through which ACS communication happens. :type cpeid: string :param attr: attribute to be used to set :type attr: string :param values: the value to be set to the attr :type values: string :raises: NA :returns: ticketId for set. :rtype: string """ SetParameterValuesParametersClassArray_type = self.client.get_type( 'ns0:SetParameterValuesParametersClassArray') SetParameterValuesParametersClassArray_data = SetParameterValuesParametersClassArray_type( [{ 'key': attr, 'value': value }]) CommandOptionsTypeStruct_type = self.client.get_type( 'ns0:CommandOptionsTypeStruct') CommandOptionsTypeStruct_data = CommandOptionsTypeStruct_type() CPEIdentifierClassStruct_type = self.client.get_type( 'ns0:CPEIdentifierClassStruct') CPEIdentifierClassStruct_data = CPEIdentifierClassStruct_type( cpeid=cpeid) # get raw soap response (parsing error with zeep) with self.client.settings(raw_response=True): response = self.client.service.SetParameterValues( SetParameterValuesParametersClassArray_data, CommandOptionsTypeStruct_data, CPEIdentifierClassStruct_data) ticketid = None root = ElementTree.fromstring(response.content) for value in root.iter('ticketid'): ticketid = value.text break if ticketid is None: return None return self.Axiros_GetTicketValue(ticketid) def Axiros_GetListOfCPEs(self): """This method is used to get the list of all devices registered on the ACS server. :raises: NA :returns: ACS response containing the list of CPE. :rtype: string """ CPESearchOptionsClassStruct_type = self.client.get_type( 'ns0:CPESearchOptionsClassStruct') CPESearchOptionsClassStruct_data = CPESearchOptionsClassStruct_type() CommandOptionsForCPESearchStruct_type = self.client.get_type( 'ns0:CommandOptionsForCPESearchStruct') CommandOptionsForCPESearchStruct_data = CommandOptionsForCPESearchStruct_type( ) response = self.client.service.GetListOfCPEs( CPESearchOptionsClassStruct_data, CommandOptionsForCPESearchStruct_data) if response['code'] != 200: return None return response def Axiros_DeleteCPEs(self, cpeid): """This method is used to delete a CPE on the ACS server. :raises: NA :returns: True if successful :rtype: True/False """ CPESearchOptionsClassStruct_type = self.client.get_type( 'ns0:CPESearchOptionsClassStruct') CPESearchOptionsClassStruct_data = CPESearchOptionsClassStruct_type( cpeid=cpeid) CommandOptionsForCPESearchStruct_type = self.client.get_type( 'ns0:CommandOptionsForCPESearchStruct') CommandOptionsForCPESearchStruct_data = CommandOptionsForCPESearchStruct_type( ) response = self.client.service.DeleteCPEs( CPESearchOptionsClassStruct_data, CommandOptionsForCPESearchStruct_data) print(response) if response['code'] != 200: return False return True delete_cpe = Axiros_DeleteCPEs def Axiros_GetTicketResponse(self, ticketid): """This is helper method used to get the ticket response on ACS. :param ticketid: the ticketid to be used to get the ACS response. :type ticketid: string :raises: NA :returns: ACS response. :rtype: string """ response = self.client.service.get_generic_sb_result(ticketid) if response['code'] != 200: return None return response['code'] def Axiros_GetTicketValue(self, ticketid, wait=8): """This is helper method used to get the text of ticket response on ACS. :param ticketid: the ticketid to be used to get the ACS response. :type ticketid: string :param wait: the number of tries to be done if we are not getting proper ACS response, defaults to 8 :type wait: int :raises: NA :returns: ACS response text / None. :rtype: string/None """ for i in range(wait): time.sleep(1) with self.client.settings(raw_response=True): ticket_resp = self.client.service.get_generic_sb_result( ticketid) root = ElementTree.fromstring(ticket_resp.content) for value in root.iter('code'): break if (value.text != '200'): continue for value in root.iter('value'): return value.text return None def rpc_GetParameterAttributes(self, cpeid, param): """This method is used to get parameter attribute on ACS of the parameter specified i.e a remote procedure call (GetParameterAttribute). Example usage : acs_server.rpc_GetParameterAttributes('DEAP815610DA', 'Device.WiFi.SSID.1.SSID') :param cpeid: the serial number of the modem through which ACS communication happens. :type cpeid: string :param param: parameter to be used in get :type param: string :raises: NA :returns: dictionary with keys Name, Notification (0/1), AccessList indicating the GPA :rtype: dict """ GetParameterAttrParametersClassArray_type = self.client.get_type( 'ns0:GetParameterAttributesParametersClassArray') GetParameterAttrParametersClassArray_data = GetParameterAttrParametersClassArray_type( [param]) CommandOptionsTypeStruct_type = self.client.get_type( 'ns0:CommandOptionsTypeStruct') CommandOptionsTypeStruct_data = CommandOptionsTypeStruct_type() CPEIdentifierClassStruct_type = self.client.get_type( 'ns0:CPEIdentifierClassStruct') CPEIdentifierClassStruct_data = CPEIdentifierClassStruct_type( cpeid=cpeid) # get raw soap response (parsing error with zeep) with self.client.settings(raw_response=True): response = self.client.service.GetParameterAttributes( GetParameterAttrParametersClassArray_data, CommandOptionsTypeStruct_data, CPEIdentifierClassStruct_data) ticketid = None root = ElementTree.fromstring(response.content) for value in root.iter('ticketid'): ticketid = value.text break if ticketid is None: return None for i in range(8): time.sleep(1) with self.client.settings(raw_response=True): ticket_resp = self.client.service.get_generic_sb_result( ticketid) root = ElementTree.fromstring(ticket_resp.content) for value in root.iter('code'): break if (value.text != '200'): continue dict_value = {'Name': param} for iter_value in ['Notification', 'item']: for value in root.iter(iter_value): dict_value[iter_value] = value.text dict_value['AccessList'] = dict_value.pop('item') return dict_value assert False, "rpc_GetParameterAttributes failed to lookup %s" % param def rpc_SetParameterAttributes(self, cpeid, attr, value): """This method is used to set parameter attribute on ACS of the parameter specified i.e a remote procedure call (SetParameterAttribute). :param cpeid: the serial number of the modem through which ACS communication happens. :type cpeid: string :param attr: attribute to be used to set :type attr: string :param values: the value to be set to the attr :type values: string :raises: NA :returns: ticket response on ACS. :rtype: string """ SetParameterAttrParametersClassArray_type = self.client.get_type( 'ns0:SetParameterAttributesParametersClassArray') SetParameterAttrParametersClassArray_data = SetParameterAttrParametersClassArray_type( [{ 'Name': attr, 'Notification': value, 'AccessListChange': '0', 'AccessList': { 'item': 'Subscriber' }, 'NotificationChange': '1' }]) CommandOptionsTypeStruct_type = self.client.get_type( 'ns0:CommandOptionsTypeStruct') CommandOptionsTypeStruct_data = CommandOptionsTypeStruct_type() CPEIdentifierClassStruct_type = self.client.get_type( 'ns0:CPEIdentifierClassStruct') CPEIdentifierClassStruct_data = CPEIdentifierClassStruct_type( cpeid=cpeid) # get raw soap response (parsing error with zeep) with self.client.settings(raw_response=True): response = self.client.service.SetParameterAttributes( SetParameterAttrParametersClassArray_data, CommandOptionsTypeStruct_data, CPEIdentifierClassStruct_data) ticketid = None root = ElementTree.fromstring(response.content) for value in root.iter('ticketid'): ticketid = value.text break if ticketid is None: return None return self.Axiros_GetTicketValue(ticketid) def rpc_AddObject(self, cpeid, param, wait=8): """This method is used to add object ACS of the parameter specified i.e a remote procedure call (AddObject). :param cpeid: the serial number of the modem through which ACS communication happens. :type cpeid: string :param param: parameter to be used to add :type param: string :param wait: the number of tries to be done if we are not getting proper ACS response, defaults to 8 :type wait: integer, optional :raises assertion: rpc_AddObject failed to lookup for the param :returns: ticket response on ACS :rtype: dictionary """ AddObjectClassArray_type = self.client.get_type( 'ns0:AddDelObjectArgumentsStruct') AddObjectClassArray_data = AddObjectClassArray_type(param, '') CommandOptionsTypeStruct_type = self.client.get_type( 'ns0:CommandOptionsTypeStruct') CommandOptionsTypeStruct_data = CommandOptionsTypeStruct_type() CPEIdentifierClassStruct_type = self.client.get_type( 'ns0:CPEIdentifierClassStruct') CPEIdentifierClassStruct_data = CPEIdentifierClassStruct_type( cpeid=cpeid) # get raw soap response (parsing error with zeep) with self.client.settings(raw_response=True): response = self.client.service.AddObject(AddObjectClassArray_data, \ CommandOptionsTypeStruct_data, CPEIdentifierClassStruct_data) ticketid = None root = ElementTree.fromstring(response.content) for value in root.iter('ticketid'): ticketid = value.text break if ticketid is None: return None for i in range(wait): time.sleep(1) with self.client.settings(raw_response=True): ticket_resp = self.client.service.get_generic_sb_result( ticketid) root = ElementTree.fromstring(ticket_resp.content) for value in root.iter('code'): break if (value.text != '200'): continue dict_value = {} for key, value in zip(root.iter('key'), root.iter('value')): dict_value[key.text] = value.text return dict_value assert False, "rpc_AddObject failed to lookup %s" % param def rpc_DelObject(self, cpeid, param): """This method is used to delete object ACS of the parameter specified i.e a remote procedure call (DeleteObject). :param cpeid: the serial number of the modem through which ACS communication happens. :type cpeid: string :param param: parameter to be used to delete :type param: string :returns: ticket response on ACS ('0' is returned) :rtype: string """ DelObjectClassArray_type = self.client.get_type( 'ns0:AddDelObjectArgumentsStruct') DelObjectClassArray_data = DelObjectClassArray_type(param, '') CommandOptionsTypeStruct_type = self.client.get_type( 'ns0:CommandOptionsTypeStruct') CommandOptionsTypeStruct_data = CommandOptionsTypeStruct_type() CPEIdentifierClassStruct_type = self.client.get_type( 'ns0:CPEIdentifierClassStruct') CPEIdentifierClassStruct_data = CPEIdentifierClassStruct_type( cpeid=cpeid) # get raw soap response (parsing error with zeep) with self.client.settings(raw_response=True): response = self.client.service.DeleteObject(DelObjectClassArray_data, \ CommandOptionsTypeStruct_data, CPEIdentifierClassStruct_data) ticketid = None root = ElementTree.fromstring(response.content) for value in root.iter('ticketid'): ticketid = value.text break if ticketid is None: return None return self.Axiros_GetTicketValue(ticketid) def Read_Log_Message(self, cpeid, wait=8): """This method is used to read ACS log messages :param cpeid: the serial number of the modem through which ACS communication happens. :type cpeid: string :param wait: the number of tries to be done if we are not getting proper ACS response, defaults to 8 :type wait: integer, optional :returns: ticket response on ACS(Log message) :rtype: dictionary """ CommandOptionsTypeStruct_type = self.client.get_type( 'ns0:CommandOptionsForCPELogStruct') CommandOptionsTypeStruct_data = CommandOptionsTypeStruct_type() CPEIdentifierClassStruct_type = self.client.get_type( 'ns0:CPEIdentifierClassStruct') CPEIdentifierClassStruct_data = CPEIdentifierClassStruct_type( cpeid=cpeid) # get raw soap response (parsing error with zeep) with self.client.settings(raw_response=True): response = self.client.service.GetLogMessagesOfCPE( CommandOptionsTypeStruct_data, CPEIdentifierClassStruct_data) for i in range(wait): time.sleep(1) root = ElementTree.fromstring(response.content) for value in root.iter('code'): break if (value.text != '200'): continue dict_value1 = {} num = 1 for key, value in zip(root.iter('ts'), root.iter('message')): dict_value = {} dict_value['time'] = key.text dict_value['msg'] = value.text dict_value1['log_msg' + str(num)] = dict_value num += 1 return dict_value1 return None def Del_Log_Message(self, cpeid, wait=8): """This method is used to delete ACS log messages :param cpeid: the serial number of the modem through which ACS communication happens. :type cpeid: string :param wait: the number of tries to be done if we are not getting proper ACS response, defaults to 8 :type wait: integer, optional :returns: True or None :rtype: Boolean """ CPEIdentifierClassStruct_type = self.client.get_type( 'ns0:CPEIdentifierClassStruct') CPEIdentifierClassStruct_data = CPEIdentifierClassStruct_type( cpeid=cpeid) # get raw soap response (parsing error with zeep) with self.client.settings(raw_response=True): response = self.client.service.DeleteLogMessagesOfCPE( CPEIdentifierClassStruct_data) for i in range(wait): time.sleep(1) root = ElementTree.fromstring(response.content) for value in root.iter('code'): break if (value.text == '200'): return True else: continue return None
def __init__(self, keyword: str = 'Session', verbose: bool = False): self.client = Client(_make_client_url(keyword=keyword)) self.verbose = verbose