def main(api_key, mastr_number, limit, step, start, filter_type, units_file): wsdl = 'https://www.marktstammdatenregister.de/MaStRAPI/wsdl/mastr.wsdl' transport = Transport(cache=SqliteCache()) settings = Settings(strict=False, xml_huge_tree=True) client = Client(wsdl=wsdl, transport=transport, settings=settings) client_bind = client.bind('Marktstammdatenregister','Anlage') writer = csv.DictWriter(units_file, field_names) writer.writeheader() total = total_filtered = 0 logging.getLogger('zeep').setLevel(logging.CRITICAL) for current_step in range(start, math.ceil(limit/step)): try: try: c = client_bind.GetListeAlleEinheiten(apiKey=api_key, marktakteurMastrNummer=mastr_number, startAb=step*current_step, limit=step) respond = serialize_object(c) except Fault as e: print('Probably reached the end, saving file: ' + e.message) break filtered = [dict(x) for x in respond['Einheiten'] if x['Einheittyp'] == filter_type] print(f'[{current_step}] Fetched {len(respond["Einheiten"])} entries out of which {len(filtered)} was used') writer.writerows(filtered) total += len(respond["Einheiten"]) total_filtered += len(filtered) except KeyboardInterrupt: print('Aborting fetching!') break print(f'Fetched in total {total} entries which {total_filtered} was used.')
def build_from_config(cls, config, pub_cert, priv_cert): ''' Builds AEAT Controller with Plugins :param config: Preconfigured Config object :param pub_cert: Public certificate file path :param priv_cert: Private certificate file path :rtype: Controller ''' session = Session() session.cert = (pub_cert, priv_cert) transport = Transport(session=session, operation_timeout=60) raw_xml_plugin = zeep_plugins.RawXMLPlugin() if config.signed: sign_plugin = zeep_plugins.SignMessagePlugin(pub_cert, priv_cert) plugins = [raw_xml_plugin, sign_plugin] else: plugins = [raw_xml_plugin] client = Client(config.wsdl, service_name=config.service, port_name=config.port, transport=transport, strict=False, plugins=plugins) return cls(client, config, raw_xml_plugin=raw_xml_plugin)
def _getTransport(self): """ Gets the zeep transport object """ transport = Transport() transport.session.verify = not self.skip_cert_verification return transport
def create_client(self, web_service) -> Client: session = Session() session.headers = {} transport = Transport(session=session) transport.session.headers = { } # DON'T REMOVE THIS LINE.YOU BLOCK FROM SAMAN BANK IF REMOVE THIS LINE return Client(web_service, transport=transport)
def __init__(self, url, user, password, verify=True, cert=None, keyfile=None): session = Session() if cert: session.verify = verify session.cert = (cert, keyfile) else: session.auth = HTTPBasicAuth(user, password) wsdl_url = "{0}/?wsdl".format(url) self.client = Client(wsdl_url, transport=Transport(session=session, timeout=10)) address = "/".join(wsdl_url.split("/")[:-2]) # ServiceProxy for same host location from config as the host location can be different in WSDL response # As an Example - # # Case 1.) Type - SAPHostControl # # URL = http://192.168.0.1:1128 - in case of http # URL = https://192.168.0.1:1129 - in case of https # # SOAP Address location in WSDL response is "http://18.92.32.0:1128/SAPHostControl.cgi" # then creating a ServiceProxy with the given URL config, it will become # "http://192.168.0.1:1128/SAPHostControl.cgi" and same goes for https self.service = self.client.create_service( "{urn:SAPHostControl}SAPHostControl", address + "/SAPHostControl.cgi")
def get_SOAP_client(url, verify=True): # http://docs.python-zeep.org/en/master/transport.html#ssl-verification # Disable SSL cert verification meanwhile a better way is found session = requests.Session() session.verify = verify transport = Transport(cache=InMemoryCache(), session=session) return Client(url, transport=transport)
def paymentDetails(wsdlUrl, requestXML): session = Session() session.verify = False transport = Transport(session=session) client = Client(wsdlUrl, transport=transport) print(client) responseXML = client.service.paymentDetails(requestXML) return responseXML
def submitEOD(wsdlUrl, requestXML, fiCode): session = Session() session.verify = False transport = Transport(session=session) client = Client(wsdlUrl, transport=transport) print(client) responseXML = client.service.submitEOD(requestXML, fiCode) return responseXML
def __init__(self, wsdl, cert=None, verify=True, timeout=8, **kwargs): session = Session() session.cert = cert session.verify = verify session.timeout = timeout session.headers.update({'Content-Type': 'text/xml;charset=UTF-8'}) transport = Transport(operation_timeout=timeout, session=session) super().__init__(wsdl=wsdl, transport=transport, **kwargs)
def __init__(self, api_key: Optional[str] = None): wsdl = WSDL if api_key else WSDL_SANDBOX self.endpoint = ENDPOINT if api_key else ENDPOINT_SANDBOX self.api_key = api_key or APIKEY_SANDBOX transport = Transport(session=Session()) transport.session.headers = self.headers self.client = ZeepClient(wsdl, transport=transport) self.service = None
def __init__(self, logger): self._logger = logger self._parser = BanxicoParser() try: self._session = requests.Session() self._client = Client(WSDL, transport=Transport(session=self._session)) except Exception as ex: self._session = None self._client = None self._logger.error(ex)
def __init__(self, address=None, username=None, password=None): self.address = address + "?wsdl" self.username = username self.password = password self.protocol = "OCI" self.session = Session() self.client = _Client(self.address, transport=Transport(session=self.session)) self.jsession = None self.bw_session = None self.log = None self.login_type = None
def _get_client(self, timeout=5): transport = Transport(timeout=timeout, operation_timeout=timeout) if self._sandbox: return Client( 'https://sandbox.zarinpal.com/pg/services/WebGate/wsdl', transport=transport, ) return Client( 'https://www.zarinpal.com/pg/services/WebGate/wsdl', transport=transport, )
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 get_client(self, endpoint): if endpoint not in self.clients: wsdl = "https://{}/Panopto/PublicAPI/{}/{}.svc?singleWsdl".format( self.host, ENDPOINTS[endpoint], endpoint) transport = Transport(session=Session(), cache=SqliteCache()) settings = Settings(strict=False) self.clients[endpoint] = Client(wsdl, transport=transport, service_name=endpoint, settings=settings) return self.clients[endpoint]
def _validate_vat_id_CH(vat_id, country_code): if vat_id[:3] != 'CHE': raise VATIDFinalError( _('Your VAT ID does not match the selected country.')) vat_id = re.sub('[^A-Z0-9]', '', vat_id.replace('HR', '').replace('MWST', '')) try: transport = Transport(cache=SqliteCache( os.path.join(settings.CACHE_DIR, "validate_vat_id_ch_zeep_cache.db"))) client = Client( 'https://www.uid-wse.admin.ch/V5.0/PublicServices.svc?wsdl', transport=transport) result = client.service.ValidateUID(uid=vat_id) except Fault as e: if e.message == 'Data_validation_failed': raise VATIDFinalError( _('This VAT ID is not valid. Please re-check your input.')) elif e.message == 'Request_limit_exceeded': logger.exception( 'VAT ID checking failed for country {} due to request limit'. format(country_code)) raise VATIDTemporaryError( _('Your VAT ID could not be checked, as the VAT checking service of ' 'your country returned an incorrect result. We will therefore ' 'need to charge VAT on your invoice. Please contact support to ' 'resolve this manually.')) else: logger.exception( 'VAT ID checking failed for country {}'.format(country_code)) raise VATIDTemporaryError( _('Your VAT ID could not be checked, as the VAT checking service of ' 'your country returned an incorrect result. We will therefore ' 'need to charge VAT on your invoice. Please contact support to ' 'resolve this manually.')) except: logger.exception( 'VAT ID checking failed for country {}'.format(country_code)) raise VATIDTemporaryError( _('Your VAT ID could not be checked, as the VAT checking service of ' 'your country is currently not available. We will therefore ' 'need to charge VAT on your invoice. You can get the tax amount ' 'back via the VAT reimbursement process.')) else: if not result: raise VATIDFinalError( _('This VAT ID is not valid. Please re-check your input.')) return vat_id
def create(cls, wsdl_path: str, cert: Tuple[str, str]): """ :param wsdl_path: :param cert: :return: """ session = Session() session.cert = cert session.verify = True transport = Transport(session=session) client = Client(wsdl_path, service_name=cls.service_name, port_name=cls.port_name, transport=transport) return cls(client)
def track_package(cls, data=None): if type(data) is not dict: raise EstafetaWrongData("Data have to be a dictionary") wsdl = cls.__valid_track__(data=data) instance = EstafetaClient() transport = Transport() transport.session.verify = False client = Client(instance.url_tracking, transport=transport) wsdl['suscriberId'] = instance.id wsdl['login'] = instance.user wsdl['password'] = instance.password response = client.service.ExecuteQuery(**wsdl) client.transport.session.close() return response
def set_cookie(auth_cookie): """ Login to Panopto by setting .ASPXAUTH cookie This *should* work regardless of whichever Panopto subdomain you"re using Returns True if login is successful, and False otherwise """ s.cookies = requests.utils.cookiejar_from_dict({".ASPXAUTH": auth_cookie}) am = Client( "{}/Panopto/PublicAPI/4.6/AccessManagement.svc?singleWsdl".format( PANOPTO_BASE), transport=Transport(session=s)) # TODO: Find a better way to check for successful login instead of relying on the SOAP API throwing an error try: am.service.GetSelfUserAccessDetails() except: return False return True
def quote(cls, data=None): if type(data) is not dict: raise EstafetaWrongData("Data have to be a dictionary") wsdl = cls.__valid_quote__(data=data) instance = EstafetaClient() transport = Transport() transport.session.verify = False client = Client(instance.url_quote, transport=transport) wsdl['idusuario'] = instance.id wsdl['usuario'] = instance.user wsdl['contra'] = instance.password response = client.service.FrecuenciaCotizador(**wsdl) client.transport.session.close() return response[0]
def __init__(self): """ Initiate client and cucm AXL API service """ transport = Transport(timeout=10) auth = HTTPBasicAuth(config.ucm_username, config.ucm_password) self.client = Client(config.wsdl, transport=transport) self.client.transport.session.auth = auth # ignore invalid certificates, required when using self signed certs self.client.transport.session.verify = False self.service = self.client.create_service( binding_name="{http://www.cisco.com/AXLAPIService/}AXLAPIBinding", address=config.ucm_url, )
def __init__(self, timeout: int = 30, **kwargs) -> None: session = Session() session.verify = False session.timeout = timeout session.headers.update({"Content-Type": "text/xml;charset=UTF-8"}) self.history = HistoryPlugin() cache = SqliteCache(path='/tmp/correios-api-cache.db', timeout=60) transport = Transport(operation_timeout=timeout, session=session, cache=cache) kwargs.update({'plugins': [self.history]}) super(WebService, self).__init__(wsdl=self.base_uri, transport=transport, **kwargs)
def __init__(self, url, username, password, library_workitem_query): self.url = url self.username = username self.password = password self.library_workitem_query = library_workitem_query self.history = HistoryPlugin() tmp_session = Session() tmp_adapter = SslContextHttpAdapter() tmp_session.mount("https://librarymanagement.swisslog.com/", tmp_adapter) tmp_transport = Transport(session=tmp_session) self.session = Client(wsdl=self.url + '/ws/services/SessionWebService?wsdl', plugins=[self.history], transport=tmp_transport) self.session.service.logIn(self.username, self.password) tree = self.history.last_received['envelope'].getroottree() self.session_header_element = tree.find( './/{http://ws.polarion.com/session}sessionID') self.__tracker = Client(wsdl=self.url + '/ws/services/TrackerWebService?wsdl', plugins=[self.history], transport=tmp_transport) self.__tracker.set_default_soapheaders([self.session_header_element]) self.__tracker.wsdl.messages[ '{http://ws.polarion.com/TrackerWebService}getModuleWorkItemsRequest'].parts[ 'parameters'].element.type._element[1].nillable = True self.__tracker.service.getModuleWorkItemUris._proxy._binding.get( 'getModuleWorkItemUris' ).input.body.type._element[1].nillable = True self.__tracker.service.getModuleWorkItemUris._proxy._binding.get( 'getModuleWorkItems').input.body.type._element[1].nillable = True self.__project_service = Client(wsdl=self.url + '/ws/services/ProjectWebService?wsdl', plugins=[self.history], transport=tmp_transport) self.__project_service.set_default_soapheaders( [self.session_header_element])
def __valid_quote__(cls, data=None): error = '' for name in [ 'esFrecuencia', 'esLista', 'esPaquete', 'datosOrigen', 'datosDestino' ]: if name not in data: error += name + ', ' if error is not '': raise EstafetaWrongData('Fields \"{}\" are mandatory'.format( error[:-2])) if data['esPaquete']: for name in ['alto', 'largo', 'ancho', 'peso']: if name not in data: error += name + ', ' if error is not '': raise EstafetaWrongData( 'When \'esPaquete\' is True, fields \"{}\" ara mandatory'. format(error[:-2])) else: for name in ['alto', 'largo', 'ancho', 'peso']: data[name] = 0 instance = EstafetaClient() transport = Transport() transport.session.verify = False client = Client(instance.url_quote, transport=transport) data['tipoEnvio'] = client.get_type("ns0:TipoEnvio")( EsPaquete=data.pop('esPaquete'), Largo=data.pop('largo'), Alto=data.pop('alto'), Ancho=data.pop('ancho'), Peso=data.pop('peso'), ) return data
def __init__(self, address=None, username=None, password=None, jsession=None, bwsession=None, isRelease22=False): self.address = address + "?wsdl" self.username = username self.password = password self.protocol = "OCI" self.jsession = jsession self.bw_session = bwsession self.session = Session() if jsession: self.session.cookies['JSESSIONID'] = jsession self.client = _Client(self.address, transport=Transport(session=self.session)) self.log = None self.login_type = None self.isRelease22 = isRelease22
def soap_api(): wsdl = "http://cbs.zong.com.pk/ReachCWSv2/CorporateSMS.svc?wsdl" # session = Session() # session.auth = HTTPBasicAuth('923120825064', 'Zong@123') client = Client(wsdl, transport=Transport(cache=SqliteCache())) # , session = session request_data = { 'loginId': '923120825064', 'loginPassword': '******', 'Destination': '923322184147', 'Message': 'Hello Paelu', 'Mask': 'MyApt', 'UniCode': 0, 'ShortCodePrefered': 'n' } response = client.service.QuickSMS(request_data) if response.find('Submitted Successfully'): pass print response
def process(self,method,url, timeout, data=None, headers=None, auth=None): from zeep import Client,Transport try: logger.debug( "Api name: " + self.name + " url: " + str(url) + " headers:" + str(headers), extra=log_json(self.halo_context)) now = datetime.datetime.now() transport = Transport(session=self.session, timeout=timeout, operation_timeout=timeout) self.client = Client(url,transport=transport) soap_response = self.do_request(method,timeout, data, headers, auth) total = datetime.datetime.now() - now logger.info(LOGChoice.performance_data.value, extra=log_json(self.halo_context, {LOGChoice.type.value: SYSTEMChoice.api.value, LOGChoice.milliseconds.value: int( total.total_seconds() * 1000), LOGChoice.url.value: str(url)})) logger.debug("ret: " + str(soap_response), extra=log_json(self.halo_context)) return soap_response except ApiException as e: msg = str(e) logger.debug("error: " + msg, extra=log_json(self.halo_context)) raise e
def webService(codes): data = { "ClientCode": "1454", "Codes": "369360;", "ShowOff": "1", "ShowNumber": "5000", "Sort": "0", "Letter": "", "ShowOrderGoods": "", "Only_GAZ_Products": "0", } host = 'https://status-m.com.ua/ws/ProductSearch_new.1cws?wsdl' user = '******' password = '******' session = Session() settings = Settings(strict=False, xml_huge_tree=True) transport = Transport(session=session, timeout=10, cache=None) session.auth = HTTPBasicAuth(user, password) # session.headers = {"Content-Type": "text/xml; charset=utf-8"} try: client = Client(host, transport=transport, settings=settings) # with client.settings(raw_response=True): result = client.service.SearchByCodes( ClientCode='1454', Codes=codes, ShowOff="1", ShowNumber="5000", Sort="0", Letter="", ShowOrderGoods="", Only_GAZ_Products="0", ) except: result = [] return result
def __call__(self, request): """Makes a SoftLayer API call against the SOAP endpoint. :param request request: Request object """ zeep_settings = Settings(strict=False, xml_huge_tree=True) zeep_transport = Transport(cache=SqliteCache(timeout=86400)) client = Client(f"{self.endpoint_url}/{request.service}?wsdl", settings=zeep_settings, transport=zeep_transport, plugins=[self.history]) # print(client.wsdl.dump()) # print("=============== WSDL ==============") # Must define headers like this because otherwise the objectMask header doesn't work # because it isn't sent in with a namespace. xsd_userauth = xsd.Element( f"{{{self.soapns}}}authenticate", xsd.ComplexType([ xsd.Element(f'{{{self.soapns}}}username', xsd.String()), xsd.Element(f'{{{self.soapns}}}apiKey', xsd.String()) ])) # factory = client.type_factory(f"{self.soapns}") the_mask = client.get_type(f"{{{self.soapns}}}SoftLayer_ObjectMask") xsd_mask = xsd.Element(f"{{{self.soapns}}}SoftLayer_ObjectMask", the_mask) # Object Filter filter_type = client.get_type( f"{{{self.soapns}}}{request.service}ObjectFilter") xsd_filter = xsd.Element( f"{{{self.soapns}}}{request.service}ObjectFilter", filter_type) # Result Limit xsd_resultlimit = xsd.Element( f"{{{self.soapns}}}resultLimit", xsd.ComplexType([ xsd.Element('limit', xsd.String()), xsd.Element('offset', xsd.String()), ])) # Might one day want to support unauthenticated requests, but for now assume user auth. headers = [ xsd_userauth(username=request.transport_user, apiKey=request.transport_password), ] if request.limit: headers.append( xsd_resultlimit(limit=request.limit, offset=request.offset)) if request.mask: headers.append(xsd_mask(mask=request.mask)) if request.filter: # The ** here forces python to treat this dict as properties headers.append(xsd_filter(**request.filter)) if request.identifier: init_param = f"{request.service}InitParameters" init_paramtype = client.get_type(f"{{{self.soapns}}}{init_param}") xsdinit_param = xsd.Element(f"{{{self.soapns}}}{init_param}", init_paramtype) # Might want to check if its an id or globalIdentifier at some point, for now only id. headers.append(xsdinit_param(id=request.identifier)) # NEXT Add params... maybe try: method = getattr(client.service, request.method) except AttributeError as ex: message = f"{request.service}::{request.method}() does not exist in {self.soapns}{request.service}?wsdl" raise exceptions.TransportError(404, message) from ex result = method(_soapheaders=headers) # NEXT GET A WAY TO FIND TOTAL ITEMS try: method_return = f"{request.method}Return" serialize = serialize_object(result) if serialize.get('body'): return serialize['body'][method_return] else: # Some responses (like SoftLayer_Account::getObject) don't have a body? return serialize except KeyError as ex: message = f"Error serializeing response\n{result}\n{ex}" raise exceptions.TransportError(500, message)
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) load_dotenv() # Load Environmental Variable wsdl = os.getenv("WSDL_FILE") username = os.getenv("UCM_USERNAME") password = os.getenv("UCM_PASSWORD") ucm_pub_url = f'https://{os.getenv("UCM_PUB_ADDRESS")}:8443/axl/' session = Session() session.verify = False session.auth = HTTPBasicAuth(username, password) transport = Transport(session=session, timeout=10) history = HistoryPlugin() client = Client(wsdl=wsdl, transport=transport, plugins=[history]) service = client.create_service( binding_name="{http://www.cisco.com/AXLAPIService/}AXLAPIBinding", address=ucm_pub_url, ) css_name = "dp-test-css" get_css_resp = service.getCss(name=css_name) print("ORIGINAL CSS MEMBERS:") print(get_css_resp["return"]["css"]["members"])