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 dep_credentials(): """ :usage: Defines the Session and the Device Enrollment Program Settings for the API calls :return: Requests Session w/ headers and DEP cert, DEP SoldTo, DEP ResellerID, and endpoint base URL """ # Begin a Requests Session for all API Calls session = Session() session.headers.update({ 'Content-Type': "application/json;charset=utf-8", # Required 'Accept-Encoding': "application/json" # Optional }) # Get ACC Connection Details from Environment Variables dep_env = environ['DEP_ENV'] # DEP Environment: UAT or PROD dep_ship_to = environ['DEP_SHIPTO'] # 10 digit Ship-To Account Number dep_reseller_id = environ['DEP_RESELLER_ID'] # DEP Reseller ID # Set the base_url of the AppleCare Connect endpoint and SSL cert # Default to Dev/Test environment base_url = "https://acc-ipt.apple.com/enroll-service/1.0" session.cert = ( environ['DEP_UAT_CERT'], # Path to DEP UAT Cert .PEM File environ['DEP_UAT_PRIVATE_KEY'] ) # Path to DEP UAT Private Key .PEM File if dep_env == 'UAT': # Joint UAT environment session.cert = ( environ['DEP_UAT_CERT'], # Path to DEP UAT Cert .PEM File environ['DEP_UAT_PRIVATE_KEY'] ) # Path to DEP UAT Private Key .PEM File if (int(dep_ship_to) % 2) == 0: base_url = "https://api-applecareconnect-ept.apple.com/enroll-service/1.0" else: base_url = "https://api-applecareconnect-ept2.apple.com/enroll-service/1.0" elif dep_env == 'PROD': # Production environment session.cert = ( environ['DEP_PROD_CERT'], # Path to DEP PROD Cert .PEM File environ['DEP_PROD_PRIVATE_KEY'] ) # Path to DEP PROD Private Key .PEM File if (int(dep_ship_to) % 2) == 0: base_url = "https://api-applecareconnect.apple.com/enroll-service/1.0" else: base_url = "https://api-applecareconnect2.apple.com/enroll-service/1.0" # Context Information for the request. Contains the Ship-To, language code and timezone. request_context = dict( shipTo=dep_ship_to, # Ship-To Account Number timeZone= "420", # Default value is Pacific Time. Users can provide a timezone, offset or canonical ID values. langCode= "en" # Default value is "en". Users can provide any of the Valid Language Codes. ) return session, dep_ship_to, dep_reseller_id, base_url, request_context
def add_certs_to_session(session: requests.Session, ca_bundle: Optional[str] = None, cert: Optional[str] = None) -> requests.Session: """Adds CA bundle and certificate to an existing session. Parameters ---------- session: requests.Session input session ca_bundle: str, optional path to CA bundle file cert: str, optional path to client certificate file in Privacy Enhanced Mail (PEM) format Returns ------- requests.Session verified session """ if ca_bundle is not None: ca_bundle = os.path.expanduser(os.path.expandvars(ca_bundle)) if not os.path.exists(ca_bundle): raise OSError( 'CA bundle file does not exist: {}'.format(ca_bundle)) logger.debug('use CA bundle file: {}'.format(ca_bundle)) session.verify = ca_bundle if cert is not None: cert = os.path.expanduser(os.path.expandvars(cert)) if not os.path.exists(cert): raise OSError('Certificate file does not exist: {}'.format(cert)) logger.debug('use certificate file: {}'.format(cert)) session.cert = cert return session
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 _send(certificado, method, **kwargs): base_url = "" if kwargs["ambiente"] == "producao": base_url = "https://wsnfsev1.natal.rn.gov.br:8444" else: base_url = "https://wsnfsev1homologacao.natal.rn.gov.br:8443/axis2/services/NfseWSServiceV1?wsdl" base_url = "https://wsnfsev1homologacao.natal.rn.gov.br:8443/axis2/services/NfseWSServiceV1?wsdl" cert, key = extract_cert_and_key_from_pfx( certificado.pfx, certificado.password) cert, key = save_cert_key(cert, key) disable_warnings() session = Session() session.cert = (cert, key) session.verify = False transport = Transport(session=session) client = Client(wsdl=base_url, transport=transport) xml_send = {} xml_send = { "nfseDadosMsg": kwargs["xml"], "nfseCabecMsg": """<?xml version="1.0"?> <cabecalho xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" versao="1" xmlns="http://www.abrasf.org.br/ABRASF/arquivos/nfse.xsd"> <versaoDados>1</versaoDados> </cabecalho>""", } response = client.service[method](**xml_send) response, obj = sanitize_response(response) return {"sent_xml": xml_send, "received_xml": response, "object": obj}
def _send(certificado, method, **kwargs): base_url = "" if kwargs["ambiente"] == "producao": base_url = "https://bhissdigital.pbh.gov.br/bhiss-ws/nfse?wsdl" else: base_url = "https://bhisshomologa.pbh.gov.br/bhiss-ws/nfse?wsdl" xml_send = kwargs["xml"].decode("utf-8") xml_cabecalho = '<?xml version="1.0" encoding="UTF-8"?>\ <cabecalho xmlns="http://www.abrasf.org.br/nfse.xsd" versao="1.00">\ <versaoDados>1.00</versaoDados></cabecalho>' 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) client = Client(base_url, transport=transport) response = client.service[method](xml_cabecalho, xml_send) response, obj = sanitize_response(response) return {"sent_xml": xml_send, "received_xml": response, "object": obj}
def __init__(self, url, max_schemas_per_subject=1000, ca_location=None, cert_location=None, key_location=None): # In order to maintain compatibility the url(conf in future versions) param has been preserved for now. conf = url if not isinstance(url, dict): conf = { 'url': url, 'ssl.ca.location': ca_location, 'ssl.certificate.location': cert_location, 'ssl.key.location': key_location } warnings.warn( "CachedSchemaRegistry constructor is being deprecated. " "Use CachedSchemaRegistryClient(dict: config) instead. " "Existing params ca_location, cert_location and key_location will be replaced with their " "librdkafka equivalents as keys in the conf dict: `ssl.ca.location`, `ssl.certificate.location` and " "`ssl.key.location` respectively", category=DeprecationWarning, stacklevel=2) """Construct a Schema Registry client""" # Ensure URL valid scheme is included; http[s] url = conf.pop('url', '') if not isinstance(url, string_type): raise TypeError("URL must be of type str") if not url.startswith('http'): raise ValueError("Invalid URL provided for Schema Registry") self.url = url.rstrip('/') # subj => { schema => id } self.subject_to_schema_ids = defaultdict(dict) # id => avro_schema self.id_to_schema = defaultdict(dict) # subj => { schema => version } self.subject_to_schema_versions = defaultdict(dict) s = Session() ca_path = conf.pop('ssl.ca.location', None) if ca_path is not None: s.verify = ca_path s.cert = self._configure_client_tls(conf) s.auth = self._configure_basic_auth(self.url, conf) self.url = utils.urldefragauth(self.url) self._session = s self.auto_register_schemas = conf.pop("auto.register.schemas", True) self.additional_headers = conf.pop("additional.headers", None) if len(conf) > 0: raise ValueError( "Unrecognized configuration properties: {}".format( conf.keys()))
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 _send(certificado, method, **kwargs): base_url = '' if kwargs['ambiente'] == 'producao': base_url = 'https://isse.maringa.pr.gov.br/ws/?wsdl' else: base_url = 'https://isseteste.maringa.pr.gov.br/ws/?wsdl' xml_send = kwargs["xml"].decode('utf-8') 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) client = Client(base_url, transport=transport) response = client.service[method](xml_send) response, obj = sanitize_response(response) return { 'sent_xml': str(xml_send), 'received_xml': str(response), 'object': obj }
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 _send(certificado, method, **kwargs): base_url = '' if kwargs['ambiente'] == 'producao': base_url = 'https://isse.maringa.gov.br/ws/?wsdl' else: base_url = 'https://isseteste.maringa.gov.br/ws/?wsdl' xml_send = kwargs["xml"].decode('utf-8') xml_cabecalho = '<?xml version="1.0" encoding="UTF-8"?>\ <cabecalho xmlns="http://www.abrasf.org.br/nfse.xsd" versao="1.00">\ <versaoDados>1.00</versaoDados></cabecalho>' 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) client = Client(base_url, transport=transport) response = client.service[method](xml_cabecalho, xml_send) response, obj = sanitize_response(response.encode('utf-8')) return { 'sent_xml': str(xml_send), 'received_xml': str(response), 'object': obj }
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/NFeDistribuicaoDFe"><cUF>AN</cUF><versaoDados>1.00</versaoDados></nfeCabecMsg>' ) client = Client(base_url, transport=transport) port = next(iter(client.wsdl.port_types)) first_operation = [ x for x in iter(client.wsdl.port_types[port].operations) if "Zip" not in x ][0] with client.settings(raw_response=True): response = client.service[first_operation](nfeDadosMsg=xml, _soapheaders=[xml_um]).text response, obj = sanitize_response(response.encode()) return { 'sent_xml': xml_send, 'received_xml': response.decode(), 'object': obj }
def _send_v310(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 __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 _send(certificado, method, **kwargs): base_url = '' if kwargs['ambiente'] == 'producao': base_url = 'https://producao.ginfes.com.br/ServiceGinfesImpl?wsdl' else: base_url = 'https://homologacao.ginfes.com.br/ServiceGinfesImpl?wsdl' cert, key = extract_cert_and_key_from_pfx(certificado.pfx, certificado.password) cert, key = save_cert_key(cert, key) header = '<ns2:cabecalho xmlns:ns2="http://www.ginfes.com.br/cabecalho_v03.xsd" versao="3"><versaoDados>3</versaoDados></ns2:cabecalho>' #noqa disable_warnings() session = Session() session.cert = (cert, key) session.verify = False transport = Transport(session=session) client = Client(base_url, transport=transport) xml_send = kwargs['xml'] response = client.service[method](header, xml_send) response, obj = sanitize_response(response) return {'sent_xml': xml_send, 'received_xml': response, 'object': obj}
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)) 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 _send(certificado, method, **kwargs): base_url = "" if kwargs["ambiente"] == "producao": base_url = "https://isse.maringa.pr.gov.br/ws/?wsdl" else: base_url = "https://isseteste.maringa.pr.gov.br/ws/?wsdl" xml_send = kwargs["xml"].decode("utf-8") 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) client = Client(base_url, transport=transport) response = client.service[method](xml_send) response, obj = sanitize_response(response) return { "sent_xml": str(xml_send), "received_xml": str(response), "object": obj }
def create_validation_service(self, partners): port_name = 'VNifPort1' type_address = '/wlpl/BURT-JDIT/ws/VNifV1SOAP' binding_name = '{http://www2.agenciatributaria.gob.es/static_files/common/internet/dep/aplicaciones/es/aeat/burt/jdit/ws/VNifV1.wsdl}VNifV1SoapBinding' service_name = 'VNifV1Service' wsdl = self.wsdl_files['ids_validator_v1'] if isinstance(partners, list): type_address = '/wlpl/BURT-JDIT/ws/VNifV2SOAP' binding_name = '{http://www2.agenciatributaria.gob.es/static_files/common/internet/dep/aplicaciones/es/aeat/burt/jdit/ws/VNifV2.wsdl}VNifV2SoapBinding' service_name = 'VNifV2Service' wsdl = self.wsdl_files['ids_validator_v2'] session = Session() session.cert = (self.certificate, self.key) session.verify = False transport = Transport(session=session) client = Client(wsdl=wsdl, port_name=port_name, transport=transport, service_name=service_name) if not self.url: return client.service address = '{0}{1}'.format(self.url, type_address) service = client.create_service(binding_name, address) return service
def _get_session(certificado): 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 return session
def __init__(self, url_ambiente, certificado, producao): verify = producao session = Session() session.cert = certificado session.verify = verify super(ClienteComunicacao, self).__init__(url_ambiente, transport=Transport(session=session))
def create_session(self, alias, headers=None, auth=None, verify="False", cert=None): session = Session() if headers: session.headers.update(headers) if auth: session.auth = tuple(auth) session.verify = self._builtin.convert_to_boolean(verify) session.cert = cert self._cache.register(session, alias)
def postQuery(self,pem,authJson,url): # Web-APIへPOST session = Session() # クライアント証明書の指定 session.cert = pem # Web-APIへPOST res = session.post(url, authJson, headers={'Content-Type': 'application/json'}) self.response(res)
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 https(): uri = 'https://localhost:8443/' + os.environ.get('TEST_TARGET', '') s = Session() s.cert = (cert_path, key_path) s.headers.update({'user': '******'}) s.verify = cacert_path r = s.get(uri) print("TARGET: {}".format(uri)) print("STATUS_CODE: {}".format(r.status_code)) print("TEXT: {}".format(r.text))
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, url, mutual_auth, cert=None, verify='true', **kwargs): self._logger = logging.getLogger("SPOT.INGEST.HDFS_client") session = Session() if verify == 'true': self._logger.info('SSL verification enabled') session.verify = True if cert is not None: self._logger.info('SSL Cert: ' + cert) if ',' in cert: session.cert = [path.strip() for path in cert.split(',')] else: session.cert = cert elif verify == 'false': session.verify = False super(SecureKerberosClient, self).__init__(url, mutual_auth, session=session, **kwargs)
def create_service_management(service_class): if credentials.getUseRequestsLibrary(): from requests import Session session = Session() session.cert = credentials.getManagementCertFile() service = service_class(credentials.getSubscriptionId(), request_session=session) else: service = service_class(credentials.getSubscriptionId(), credentials.getManagementCertFile()) set_service_options(service) return service
def cliente(self, url, verify=False, service_name=None, port_name=None): with ArquivoCertificado(self.certificado, 'w') as (key, cert): self.desativar_avisos() session = Session() session.cert = (key, cert) session.verify = verify transport = Transport(session=session, cache=self._cache) self._cliente = Client( url, transport=transport, service_name=service_name, port_name=port_name ) yield self._cliente self._cliente = False
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 __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 get_client(self) -> Iterator[Client]: session = Session() session.cert = (settings.GCSS_CERT_PATH, settings.GCSS_KEY_PATH) session.verify = False # client constructor fetches wsdl client = Client( f"https://{settings.GCSS_HOST}/gateway/services/{self.service_name}?wsdl", transport=GCSSTransport(session=session), wsse=GCSSWsseSignature(settings.GCSS_KEY_PATH, settings.GCSS_CERT_PATH), ) yield client session.close()
def __init__(self, credentials, zeep_cache=None, log_dir=None): if self.needs_ticket and self.name not in credentials.tickets: raise Exception( f'Ticket for "{self.name}" service not found in credentials object.' ) wsdl = self.wsdl_production if credentials.production else self.wsdl_testing session = Session() session.cert = (credentials.crt_path, credentials.key_path) transport = Transport(session=session, cache=zeep_cache) plugins = [TapeRecorderPlugin(self.name, log_dir) ] if log_dir is not None else [] self.credentials = credentials self.client = Client(wsdl, transport=transport, plugins=plugins)
def obtenerClienteWS(): """Retorna un objeto cliente, este sirve como un manejador que permite llamar a los metodos del IPRECORDWS""" #con el certificado adecuado se ejecutaran las subsecuentes instrucciones with sslcontext.pfx_to_pem('clientEC.pfx', 'Ea6@3H') as cert: #crea una sesión session = Session() #deshabilitar la verificación SSL session.verify = False session.cert = cert transport = Transport(session=session) #el objeto cliente que permite interactuar con el WS client = Client(url, transport=transport) return client
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 create_rest_session(self, alias, headers=None, auth=None, verify=False, cert=None): """ Creates REST session with specified alias. Arguments: | alias | session alias | | headers | custom headers for all requests | | auth | basic auth | | verify | SSL verification | | cert | path to SSL certificate file | Example usage: | ${headers} | Create Dictionary | Content-Type | application/json | | @{service_basic_auth} | Set Variable | username | password | | Create Rest Session | session_alias | headers=${headers} | auth=${service_basic_auth} | verify=False | """ session = Session() if headers: session.headers.update(headers) if auth: session.auth = tuple(auth) session.verify = self._builtin.convert_to_boolean(verify) session.cert = cert self._cache.register(session, alias)