def __init__( self, username, password, find_items_basepoint='Beginning', wsdl='Services.wsdl', timeout=120, max_folder_items_per_find_item_query=1000, max_items_per_get_item_query=1000, logger=None, ): self.username = username self.password = password self.find_items_basepoint = find_items_basepoint self.wsdl = wsdl self.timeout = timeout self.max_folder_items_per_find_item_query = max_folder_items_per_find_item_query self.max_items_per_get_item_query = max_items_per_get_item_query self.session = Session() self.session.auth = HttpNtlmAuth(self.username, self.password) self.history = HistoryPlugin() self.client = Client(self.wsdl, transport=Transport(session=self.session), plugins=[self.history]) self.client.options(timeout=120) # if logger is provided if (bool(logger)): # set logger to what was provided EWS_Client.logger = logger
def _createSession(self): """ Starts a session with the specified user/password """ if 'Session' in self.services: self.history = HistoryPlugin() self.services['Session']['client'] = Client( self.services['Session']['url'] + '?wsdl', plugins=[self.history], transport=self._getTransport()) try: self.sessionHeaderElement = None self.services['Session']['client'].service.logIn( self.user, self.password) tree = self.history.last_received['envelope'].getroottree() self.sessionHeaderElement = tree.find( './/{http://ws.polarion.com/session}sessionID') except Exception: raise Exception( f'Could not log in to Polarion for user {self.user}') if self.sessionHeaderElement is not None: self._updateServices() else: raise Exception( 'Cannot login because WSDL has no SessionWebService')
def seur_soap_send(self, service, method, data): def trace(title, data): _logger.debug('%s %s: %s' % (method, title, etree.tostring(data['envelope']))) def create_rewrite_plugin(data): key = [k for k, v in data.items() if isinstance(v, dict)] if not key: return RewritePlugin('//no-dict', '') key = key[0] if 'total_bultos' not in data[key]: return RewritePlugin('//missing-key', '') xml_root = etree.Element('root') xml_exp = etree.SubElement(xml_root, 'exp') for _index in range(int(data[key].get('total_bultos') or 1)): package = etree.SubElement(xml_exp, 'bulto') for k, v in data[key].items(): etree.SubElement(package, k).text = str(v or '') xml = etree.tostring(xml_root, encoding='utf8', method='xml') data[key] = '-RewritePlugin-' return RewritePlugin('//*[text()="-RewritePlugin-"]', xml) history = HistoryPlugin() client = Client( wsdl=self.seur_wsdl_get(service), transport=Transport(), plugins=[history, create_rewrite_plugin(data)], ) cli = client.bind(service) response = cli[method](**data) trace('Request', history.last_sent) trace('Response', history.last_received) return helpers.serialize_object(response, dict)
def __init__( self, config: Union[Config, Dict], *, version: str = None, wsdl_url: str = None, cache: zeep.cache.Base = None, session: requests.Session = None, sandbox: bool = None, max_history_length: int = 10, ) -> None: if sandbox is not None: warnings.warn( 'The `sandbox` flag has been deprecated and no longer has ' 'any effect. Please locate the correct account ID for your ' 'sandbox instead (usually `_SB1`)', DeprecationWarning, ) if version is not None: assert re.match(r'\d+\.\d+\.\d+', version) self.version = version self.__config = self._make_config(config) self.__wsdl_url = wsdl_url self.__cache = cache self.__session = session self.history = HistoryPlugin(maxlen=max_history_length)
def _call_submission(settings: CzNiaAppSettings, transport: Transport, assertion, message: NiaMessage) -> bytes: """Call Submission service and return the body.""" plugins = [] history = None if settings.DEBUG: history = HistoryPlugin() plugins.append(history) client = Client(settings.PUBLIC_WSDL, wsse=SAMLTokenSignature(assertion), settings=SETTINGS, transport=transport, plugins=plugins) # Prepare the Body bodies_type = client.get_type( QName(NiaNamespaces.SUBMISSION.value, 'ArrayOfBodyPart')) body_part_type = client.get_type( QName(NiaNamespaces.SUBMISSION.value, 'BodyPart')) # Call the service service = client.bind('Public', 'Token') try: response = service.Submit( message.action, bodies_type(body_part_type(Body={'_value_1': message.pack()})), '') except (Error, XmlsecError, RequestException) as err: _log_history(history, settings, 'Submission', success=False) raise NiaException(err) _log_history(history, settings, 'Submission') return b64decode(response.BodyBase64XML)
def _call_federation(settings: CzNiaAppSettings, transport: Transport, assertion: Element) -> Element: """Call FPSTS (Federation provider) service and return the assertion.""" plugins = [] history = None if settings.DEBUG: history = HistoryPlugin() plugins.append(history) client = Client(settings.FEDERATION_WSDL, wsse=SAMLTokenSignature(assertion), settings=SETTINGS, transport=transport, plugins=plugins) # prepare request request_type = client.get_element( QName(NiaNamespaces.WS_TRUST.value, 'RequestType')) request = AnyObject(request_type, request_type(NiaNamespaces.WS_TRUST.value + '/Issue')) # Prepare WSA header applies = _get_wsa_header(client, settings.PUBLIC_ADDRESS) # Call the service service = client.bind('SecurityTokenService', 'WS2007FederationHttpBinding_IWSTrust13Sync') try: response = service.Trust13Issue(_value_1=[applies, request]) except (Error, XmlsecError, RequestException) as err: _log_history(history, settings, 'FPSTS', success=False) raise NiaException(err) _log_history(history, settings, 'FPSTS') return response.RequestSecurityTokenResponse[0]['_value_1'][3]['_value_1']
def _connect_sii(self, wsdl): today = fields.Date.today() sii_config = self.env['l10n.es.aeat.sii'].search([ ('company_id', '=', self.company_id.id), ('public_key', '!=', False), ('private_key', '!=', False), '|', ('date_start', '=', False), ('date_start', '<=', today), '|', ('date_end', '=', False), ('date_end', '>=', today), ('state', '=', 'active') ], limit=1) if sii_config: public_crt = sii_config.public_key private_key = sii_config.private_key else: public_crt = self.env['ir.config_parameter'].get_param( 'l10n_es_aeat_sii.publicCrt', False) private_key = self.env['ir.config_parameter'].get_param( 'l10n_es_aeat_sii.privateKey', False) session = Session() session.cert = (public_crt, private_key) transport = Transport(session=session) history = HistoryPlugin() client = Client(wsdl=wsdl, transport=transport, plugins=[history]) return client
def pagar(request): if request.method == "POST": data = json.loads(request.body) total = 0 for pago in data['data']: p = Pago() empleado = Empleado.objects.get(pk=pago['empleado_pk']) p.empleado = empleado p.sueldo = empleado.salario total += p.sueldo p.save() tipos = [d['nombre'] for d in pago['tipos'] if d['use']] tipos = Tipo.objects.filter(nombre__in=tipos) for tipo in tipos: if tipo.depende_salario: monto = empleado.salario*tipo.porcentaje else: monto = tipo.monto p.transaccion_set.create(tipo=tipo, monto=monto, estado='R', tipo_trans=tipo.nombre) history = HistoryPlugin() client = zeep.Client('https://contabilidad.ngrok.io/Contabilidad/Contabilidad?wsdl', plugins=[history]) entrada = dict(cuentaContable=70, tipoMovimiento="CR", monto=total) entrada2 = dict(cuentaContable=71, tipoMovimiento="DB", monto=total) entradaCont = dict(auxiliar=2, descripcion='Nomina', entradasContables=[{'entradaContable': [entrada, entrada2]}]) ret = serialize_object(client.service.crearAsiento(entradaCont)) AsientoContable.objects.create(descripcion=ret['descripcion'], id_db=ret['idAsiento']) return JsonResponse(ret)
def idmquery(wsdlurl, begintime, endtime, pagenum, systemid, idmid, clientsrv): try: history = HistoryPlugin() client = Client(wsdl=wsdlurl, plugins=[history]) querydto_type = client.get_type('ns0:queryDto') header_type = client.get_type('ns2:Header') querydto = querydto_type(beginDate=begintime, endDate=endtime, pageNo=pagenum, pageRowNo='100', systemID=systemid) header = header_type(BIZTRANSACTIONID=idmid, COUNT='', CONSUMER='', SRVLEVEL='', ACCOUNT='idmadmin', PASSWORD='******') if clientsrv == 'idmorg': residmquery = client.service.PUBLIC_SUNAC_301_queryIdmOrgData( queryDto=querydto, _soapheaders={'parameters2': header}) if clientsrv == 'idmuser': residmquery = client.service.PUBLIC_SUNAC_300_queryIdmUserData( queryDto=querydto, _soapheaders={'parameters2': header}) debuglog_sys(history.last_sent) debuglog_sys(history.last_received) except Exception as e: errlog_sys(e) return residmquery
def getNextTrains(self, stationToCheck, LDB_TOKEN, numberNextTrains): # current WSDL version. Available from # https://lite.realtime.nationalrail.co.uk/OpenLDBWS/ WSDL = ('https://lite.realtime.nationalrail.co.uk/' 'OpenLDBWS/wsdl.aspx?ver=2017-10-01') history = HistoryPlugin() client = Client(wsdl=WSDL, plugins=[history]) header = xsd.Element( '{http://thalesgroup.com/RTTI/2013-11-28/Token/types}AccessToken', xsd.ComplexType([ xsd.Element( '{http://thalesgroup.com/' 'RTTI/2013-11-28/Token/types}TokenValue', xsd.String()), ]) ) header_value = header(TokenValue=LDB_TOKEN) # attempt connection to the API, return the API response on success, # otherwise return an error message and exit program with error status try: res = (client.service.GetDepBoardWithDetails( numRows=numberNextTrains, crs=stationToCheck, _soapheaders=[header_value])) except: print("Error fetching train times! Check your token is correct!") sys.exit(1) return res
def setupserviceconnection(self, ip): #print (threading.currentThread().getName()) ## setup Session session = Session() session.verify = False session.auth = HTTPBasicAuth(self.axluser, self.axlpass) transport = CustomTransport(cache=SqliteCache(), session=session, timeout=60) history = HistoryPlugin() # import required WSDL's servicewsdl = 'file://' + os.getcwd() + '//Files//ServiceWSDL.wsdl' SERVICE_BINDING_NAME = "{http://cisco.com/ccm/serviceability/soap/ControlCenterServices/}ControlCenterServicesBinding" SERVICE_ADDR = "https://" + ip + ":8443/controlcenterservice/services/ControlCenterServicesPort" try: print("Fetching Services Status from " + ip) client = Client(wsdl=servicewsdl, transport=transport, plugins=[history]) Servicexl = client.create_service(SERVICE_BINDING_NAME, SERVICE_ADDR) result = Servicexl.soapGetServiceStatus(['']) return result except (Fault, Exception) as error: print(error) return None
def __init__(self, login, password, preprod=False, header_message={}, config=""): self.preprod = preprod if self.preprod: domain = "preprod-cdiscount.com" else: domain = "cdiscount.com" self.wsdl = "https://wsvc.{0}/MarketplaceAPIService.svc?wsdl".format( domain) self.auth_url = ( "https://sts.{0}/users/httpIssue.svc/" "?realm=https://wsvc.{0}/MarketplaceAPIService.svc".format(domain)) self.login = login self.password = password self.history = HistoryPlugin() self.client = Client(self.wsdl, plugins=[self.history]) self.factory = self.client.type_factory("http://www.cdiscount.com") if self.login is None or self.password is None: raise CdiscountApiConnectionError( "Please provide valid login and password") self.token = self.get_token() if header_message != {} and config != "": raise CdiscountApiConnectionError( "You should provide header_message or config. Not both.") if header_message: self.header = self.create_header_message(header_message) elif config: config_path = Path(config) if config_path.exists(): conf = yaml.load(config_path.read_text(), Loader=yaml.FullLoader) self.header = self.create_header_message(conf) else: raise CdiscountApiConnectionError( "Can't find the configuration file {}".format(config)) else: raise CdiscountApiConnectionError( "You must provide header_message or config.") # Instanciated sections. self.seller = Seller(self) self.offers = Offers(self) self.products = Products(self) self.orders = Orders(self) self.fulfillment = Fulfillment(self) self.relays = Relays(self) self.discussions = Discussions(self) self.webmail = WebMail(self)
def test_client(requests_mock, maxlen: int = 20): """A mock test client using the 19/12/2019 Charties Commission API.""" history: HistoryPlugin = HistoryPlugin(maxlen=maxlen) auth: CharityAPIKeyType = CharitiesAuthPlugin(api_key_value=TEST_API_KEY) with open("tests/charities_api.wsdl", "r") as charities_api: requests_mock.get(CHARITY_COMMISSION_WSDL, text=charities_api.read()) client: Client = get_client(plugins=[history, auth]) assert hasattr(client.service, "GetCharitiesByName") return client
def client_soap(config_file): logger.debug('Ha entrado en la funcion client_soap()') csp_cmserver = cspconfigfile['CUCM']['server'] csp_username = cspconfigfile['CUCM']['user'] csp_password = cspconfigfile['CUCM']['pass'] csp_version = cspconfigfile['CUCM']['version'] if platform.system() == 'Windows': logger.debug('El sistema operativo es: %s' % (platform.system())) wsdl = 'file://' + os.getcwd().replace ("\\","//") + '//Schema//CUCM//' + csp_version + '//AXLAPI.wsdl' else: logger.debug('El sistema operativo es: %s' % (platform.system())) wsdl = 'file://' + os.getcwd() + '/Schema/CUCM/' + csp_version + '/AXLAPI.wsdl' csp_location = 'https://' + csp_cmserver + '/axl/' logger.debug('El valor de csp_cmserver es: %s' % (csp_cmserver)) logger.debug('El valor de csp_username es: %s' % (csp_username)) logger.debug('El valor de csp_version es: %s' % (csp_version)) logger.debug('El valor de csp_location es: %s' % (csp_location)) logger.debug('El valor de wsdl es: %s' % (wsdl)) # history shows http_headers global history history = HistoryPlugin() # The first step is to create a SOAP client session session = Session() # We avoid certificate verification by default, but you can uncomment and set # your certificate here, and comment out the False setting #session.verify = CERT session.verify = False session.auth = HTTPBasicAuth(csp_username, csp_password) transport = Transport(session=session, timeout=10, cache=SqliteCache()) # strict=False is not always necessary, but it allows zeep to parse imperfect XML settings = Settings(strict=False, xml_huge_tree=True) try: csp_soap_client = Client(wsdl, settings=settings, transport=transport, plugins=[MyLoggingPlugin(),history], ) service = csp_soap_client.create_service("{http://www.cisco.com/AXLAPIService/}AXLAPIBinding", csp_location) except: logger.error('Se ha producido un error al crear el cliente soap') logger.debug(sys.exc_info()) logger.error(sys.exc_info()[1]) sys.exit() else: logger.info('Se ha creado el cliente SOAP.') return service
def getAuthenticationWithServer(username, password, wsdl): disable_warnings(InsecureRequestWarning) session = Session() session.verify = False session.auth = HTTPBasicAuth(username, password) transport = Transport(cache=SqliteCache(), session=session, timeout=20) history = HistoryPlugin() ssl._create_default_https_context = ssl._create_unverified_context return (Client(wsdl=wsdl, transport=transport, plugins=[history]))
def __init__(self, username, password, hostname, tls_verify=True, timeout=10): self.last_exception = None wsdl = f'https://{hostname}/perfmonservice/services/PerfmonPort?wsdl' session = Session() session.verify = tls_verify session.auth = HTTPBasicAuth(username, password) cache = SqliteCache() transport = Transport(cache=cache, session=session, timeout=timeout, operation_timeout=timeout) history = HistoryPlugin() self.client = Client(wsdl=wsdl, transport=transport, plugins=[history])
def connectToWebService(self, wsdl): session = Session() session.verify = False transport = Transport(session=session) client = Client(wsdl, plugins=[HistoryPlugin()], transport=transport, strict=False, wsse=UsernameToken("testuser", "testuser")) return client
def get_client(api): history = HistoryPlugin() session = Session() session.auth = HTTPBasicAuth('MedML', '12345') try: parserApi = ParserAPI.objects.get(id=api.id) except: parserApi = None client = Client(parserApi.link if parserApi else settings.PARSER_API, transport=Transport(session=session)) return client
def _get_client(wsdl, public_crt, private_key, test=False): session = Session() session.cert = (public_crt, private_key) transport = Transport(session=session) plugins = [HistoryPlugin()] # TODO: manually handle sessionId? Not mandatory yet recommended... # http://www.agenciatributaria.es/AEAT.internet/Inicio/Ayuda/Modelos__Procedimientos_y_Servicios/Ayuda_P_G417____IVA__Llevanza_de_libros_registro__SII_/Ayuda_tecnica/Informacion_tecnica_SII/Preguntas_tecnicas_frecuentes/1__Cuestiones_Generales/16___Como_se_debe_utilizar_el_dato_sesionId__.shtml if test: plugins.append(LoggingPlugin()) client = Client(wsdl=wsdl, transport=transport, plugins=plugins) return client
def __init__(self, account=None, caching=True, caching_timeout=2592000): """ Initialize the Zeep SOAP client, parse the xsd specifications of Netsuite and store the complex types as attributes of this instance. :param str account_id: Account ID to connect to :param str caching: If caching = 'sqlite', setup Sqlite caching :param int caching_timeout: Timeout in seconds for caching. If None, defaults to 30 days """ 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: path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'cache.db') timeout = caching_timeout cache = SqliteCache(path=path, timeout=timeout) session = Session() transport = Transport(cache=cache, session=session) else: transport = None # Initialize History Logging self._history = HistoryPlugin() # Initialize the Zeep Client self._client = Client(self._wsdl_url, transport=transport, plugins=[self._history]) # 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 send_action(action): if request.method == 'GET': history = HistoryPlugin() client = zeep.Client('https://contabilidad.ngrok.io/Contabilidad/Contabilidad?wsdl', plugins=[history]) try: oper = client.service[action] return jsonify(serialize_object(oper())) except AttributeError as err: return jsonify({'error': f"No existe la accion {action}"}) except: return jsonify({'error': 'Hubo un error haciendo su request.'}) elif request.method == 'POST': history = HistoryPlugin() client = zeep.Client('https://contabilidad.ngrok.io/Contabilidad/Contabilidad?wsdl', plugins=[history]) try: oper = client.service[action] return jsonify(serialize_object(oper(request.json()))) except AttributeError as err: return jsonify({'error': f"No existe la accion {action}"}) except: return jsonify({'error': "Hubo un error haciendo su request."})
def cucm_rt_phones(model = 255, name = '', num = '', ip = '', max = 1000, Print = True): StateInfo = '' if name != '': SelectBy = 'Name' SelectItems = {'item': name} elif num != '': SelectBy = 'DirNumber' SelectItems = {'item': num} elif ip != '': SelectBy = 'IPV4Address' SelectItems = {'item': ip} else: SelectBy = 'Name' SelectItems = {} CmSelectionCriteria = { 'MaxReturnedDevices': max, 'DeviceClass': 'Phone', 'Model': '255', 'Status': 'Registered', 'SelectBy': SelectBy, 'SelectItems': SelectItems } session = Session() session.verify = False session.auth = HTTPBasicAuth(axluser, axlpassword) transport = Transport(cache=SqliteCache(), session=session, timeout=5) history = HistoryPlugin() client = Client(wsdl=riswsdl, transport=transport, plugins=[history]) def show_history(): for item in [history.last_sent, history.last_received]: print(etree.tostring(item["envelope"], encoding="unicode", pretty_print=True)) Out = [] i = 0 try: resp = client.service.selectCmDevice(CmSelectionCriteria=CmSelectionCriteria, StateInfo=StateInfo) result = resp['SelectCmDeviceResult']['CmNodes']['item'] for node in result: if node['CmDevices'] != None: for device in node['CmDevices']['item']: OutIp = device['IPAddress']['item'][0]['IP'] OutModel = device['Model'] OutDesc = device['Description'] OutNum = device['DirNumber'].replace('-Registered', '') Out.append({'ip': OutIp, 'model': OutModel, 'desc': OutDesc, 'num': OutNum}) if Print: print(str(list(Out[i].values()))) i += 1 except Fault: show_history() return [] return Out
def CustomSoapClient (self): self.Logger.debug('La direccion IP para la conexion SOAP es: %s' % (self.ipaddress)) # Comprobamos el SO sobre el que esta funcionando el servidor de Flask if platform.system() == 'Windows': self.Logger.debug('El sistema operativo es: %s' % (platform.system())) CustomWSDL = 'file://' + os.getcwd().replace ("\\","//") + '//Schema//CUCM//' + self.version + '//AXLAPI.wsdl' else: self.Logger.debug('El sistema operativo es: %s' % (platform.system())) CustomWSDL = 'file://' + os.getcwd() + '/Schema/CUCM/' + self.version + '/AXLAPI.wsdl' self.Logger.debug('El archivo WSDL es: %s' % (CustomWSDL)) # Definimos la URL de AXL self.location = 'https://' + self.ipaddress + ':' + self.port + '/axl/' # History shows http_headers global CustomHistory CustomHistory = HistoryPlugin() # The first step is to create a SOAP client session CustomSession = Session() # We avoid certificate verification by default, but you can uncomment and set # your certificate here, and comment out the False setting #session.verify = CERT CustomSession.verify = False CustomSession.auth = HTTPBasicAuth(self.username, self.password) CustomTransport = Transport(session=CustomSession, timeout=10, cache=SqliteCache()) urllib3.disable_warnings() # strict=False is not always necessary, but it allows zeep to parse imperfect XML CustomSettings = Settings(strict=False, xml_huge_tree=True) try: CustomSOAPClient = Client(CustomWSDL, settings=CustomSettings, transport=CustomTransport, plugins=[MyLoggingPlugin(),CustomHistory], ) CustomService = CustomSOAPClient.create_service("{http://www.cisco.com/AXLAPIService/}AXLAPIBinding", self.location) except: self.Logger.error('Se ha producido un error al crear el cliente SOAP') self.Logger.debug(sys.exc_info()) self.Logger.error(sys.exc_info()[1]) sys.exit() else: self.Logger.info('Se ha creado el cliente SOAP') return (CustomService)
def __init__(self, username, password, hostname, tls_verify=True, timeout=10): self.last_exception = None wsdl = f'https://{hostname}:8443/realtimeservice2/services/RISService?wsdl' session = Session() session.verify = tls_verify session.auth = HTTPBasicAuth(username, password) cache = SqliteCache() transport = Transport(cache=cache, session=session, timeout=timeout, operation_timeout=timeout) self.history = HistoryPlugin() self.client = Client(wsdl=wsdl, transport=transport, plugins=[self.history]) binding_name = '{http://schemas.cisco.com/ast/soap}RisBinding' service_addr = f'https://{hostname}:8443/realtimeservice2/services/RISService' self.service = self.client.create_service(binding_name, service_addr)
def __init__(self, username, password, hostname, tls_verify=True, timeout=10): self.last_exception = None wsdl = f'https://{hostname}:8443/logcollectionservice/services/DimeGetFileService' session = Session() session.verify = tls_verify session.auth = HTTPBasicAuth(username, password) cache = SqliteCache() transport = Transport(cache=cache, session=session, timeout=timeout, operation_timeout=timeout) self.history = HistoryPlugin() self.client = Client(wsdl=wsdl, transport=transport, plugins=[self.history]) binding_name = '{http://cisco.com/ccm/serviceability/soap/LogCollection/GetFile/}GetFileBinding' service_addr = f'https://{hostname}:8443/logcollectionservice/services/DimeGetFileService' self.service = self.client.create_service(binding_name, service_addr)
def _connect_sii(self, cr, uid, wsdl): publicCrt = self.pool.get('ir.config_parameter').get_param( cr, uid, 'l10n_es_aeat_sii.publicCrt', False) privateKey = self.pool.get('ir.config_parameter').get_param( cr, uid, 'l10n_es_aeat_sii.privateKey', False) session = Session() session.cert = (publicCrt, privateKey) transport = Transport(session=session) history = HistoryPlugin() client = Client(wsdl=wsdl, transport=transport, plugins=[history]) return client
def _request(self, method, *args, **kwargs): history = HistoryPlugin() client = ZeepClient(self.WS[0], plugins=[history]) kwargs['usuario'] = self.username kwargs['senha'] = self.password fn = getattr(client.service, method) # print envelope for debug purposes # node = client.create_message(client.service, method, **kwargs) # print etree.tostring(node, encoding='iso-8859-1'), 'NODE' result = fn(**kwargs) return result
def handle(self, *args, **options): history = HistoryPlugin() session = Session() session.auth = HTTPBasicAuth('MedML', '12345') apis = ParserAPI.objects.filter(is_active=True) for api in apis: client = Client(api.link, transport=Transport(session=session)) service2 = client.bind('WebPortal', 'WebPortalSoap12') file = client.service.Sync() self.get_handle(file, api.id)
def connect_soap(self, wsdl, model): if "company_id" in model._fields: public_crt, private_key = self.env[ "l10n.es.aeat.certificate"].get_certificates(model.company_id) else: public_crt, private_key = self.env[ "l10n.es.aeat.certificate"].get_certificates() session = Session() session.cert = (public_crt, private_key) transport = Transport(session=session) history = HistoryPlugin() client = Client(wsdl=wsdl, transport=transport, plugins=[history]) return client
def get_cybersource_client(): """ Configures and authenticates a CyberSource client Returns: (zeep.Client, zeep.plugins.HistoryPlugin): a tuple of the configured client and the history plugin instance """ wsse = UsernameToken(settings.CYBERSOURCE_MERCHANT_ID, settings.CYBERSOURCE_TRANSACTION_KEY) history = HistoryPlugin() client = Client(settings.CYBERSOURCE_WSDL_URL, wsse=wsse, plugins=[history]) return client, history