Python zeep.Client() Examples

The following are 30 code examples of zeep.Client(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module zeep , or try the search function .
Example #1
Source File: SymantecDLP.py    From content with MIT License 8 votes vote down vote up
def list_custom_attributes_command(client: Client) -> Tuple[str, dict, dict]:
    raw_custom_attributes_list = client.service.listCustomAttributes()

    human_readable: str
    entry_context: dict = {}
    raw_response: dict = {}

    if raw_custom_attributes_list:
        custom_attributes_list = helpers.serialize_object(raw_custom_attributes_list)
        raw_response = custom_attributes_list
        outputs: list = [{'Custom Attribute': custom_attribute} for custom_attribute in custom_attributes_list]
        human_readable = tableToMarkdown('Symantec DLP custom attributes', outputs, removeNull=True)
    else:
        human_readable = 'No custom attributes found.'

    return human_readable, entry_context, raw_response 
Example #2
Source File: 1-deleterecord-SOAP.py    From making-apis-work-for-you with Apache License 2.0 7 votes vote down vote up
def gethostrecordwithhint(bam_url, login_user, login_password, host_record_name):
    """get the host record FQDN and return the entity details
    """
    records=""
    try:
        # api session
        client = Client(bam_url)
        # login
        client.service.login(login_user,login_password)
        # get the host record details
        records = client.service.getHostRecordsByHint(0,10,"hint="+host_record_name+"|")
        # logout of BAM
        client.service.logout()
    except zeep.exceptions.Fault as e:
        print(e.message)
        logging.exception(e)
        sys.exit(1)
    # return the records from function
    return records 
Example #3
Source File: util.py    From odoo12-x64 with GNU General Public License v3.0 6 votes vote down vote up
def get_soap_client(wsdlurl):  # pragma: no cover (not part of normal test suite)
    """Get a SOAP client for performing requests. The client is cached."""
    # this function isn't automatically tested because the functions using
    # it are not automatically tested
    if wsdlurl not in _soap_clients:
        # try zeep first
        try:
            from zeep import CachingClient
            client = CachingClient(wsdlurl).service
        except ImportError:
            # fall back to non-caching zeep client
            try:
                from zeep import Client
                client = Client(wsdlurl).service
            except ImportError:
                # other implementations require passing the proxy config
                try:
                    from urllib import getproxies
                except ImportError:
                    from urllib.request import getproxies
                # fall back to suds
                try:
                    from suds.client import Client
                    client = Client(wsdlurl, proxy=getproxies()).service
                except ImportError:
                    # use pysimplesoap as last resort
                    from pysimplesoap.client import SoapClient
                    client = SoapClient(wsdl=wsdlurl, proxy=getproxies())
        _soap_clients[wsdlurl] = client
    return _soap_clients[wsdlurl] 
Example #4
Source File: CheckmarxConnection.py    From reapsaw with Apache License 2.0 6 votes vote down vote up
def get_client(self, client_type='SDK'):
        """
        Connect to Checkmarx client
        :param client_type:
        :return:
        """
        if client_type in self.clients:
            return self.clients[client_type]
        try:
            client_url = self.get_client_url(client_type)
            client = Client(client_url + "?wsdl", transport=self.transport, strict=False)
            credentials = {'User': self.username, 'Pass': self.password}
            login = client.service.Login(credentials, 1033)
            if not login.IsSuccesfull:
                raise AssertionError(f"Unable to login in Checkmarx. \n"
                                     f"Please double check CX_PASSWORD and CX_USER.")

            if self.session_id is None:
                self.session_id = login.SessionId
            self.clients[client_type] = client
            return client
        except ConnectionError as error:
            self.logger.critical(
                "Checkmarx connection failed. Wrong or inaccessible hostname: {error}".format(error=error))
            return False, False 
Example #5
Source File: CheckmarxConnection.py    From reapsaw with Apache License 2.0 6 votes vote down vote up
def __init__(self, hostname=None, username=None, password=None):
        """
        :param hostname:
            Checkmarx hostname
        :param username:
            Checkmarx username
        :param password:
            Checkmarx password
        """
        self.logger = configure_logging(logging.getLogger(__name__))
        self.hostname = hostname
        self.username = username
        self.password = password
        self.resolver_url = "%s/cxwebinterface/cxwsresolver.asmx?wsdl" % self.hostname
        session = Session()
        session.verify = False
        self.transport = Transport(session=session)
        try:
            self._resolver_client = Client(self.resolver_url, transport=self.transport)
        except Exception as error:
            self.logger.error("Checkmarx connection failed: {error}".format(error=error))
            raise ConnectionError(f"Checkmarx connection failed. Wrong or inaccessible hostname: {hostname}") from None
        self.session_id = None
        self.clients = {} 
Example #6
Source File: api.py    From mf-platform-bse with MIT License 6 votes vote down vote up
def create_mandate_bse(client_code, amount):
	'''
	Creates mandate for user for a specific amount 
	Called before creating an SIP transaction on BSEStar because 
		every SIP transaction requires a mandate
	'''

	## initialise the zeep client for wsdl
	client = zeep.Client(wsdl=WSDL_UPLOAD_URL[settings.LIVE])
	set_soap_logging()

	## get the password
	pass_dict = soap_get_password_upload(client)
	
	## prepare the mandate record 
	bse_mandate = prepare_mandate_param(client_code, amount)

	## post the mandate creation request
	mandate_id = soap_create_mandate(client, bse_mandate, pass_dict)
	return mandate_id 
Example #7
Source File: api.py    From mf-platform-bse with MIT License 6 votes vote down vote up
def create_user_bse(client_code):
	'''
	Creates a user on BSEStar (called client in bse lingo)
	- Initializes SOAP client zeep
	- Gets one-time password from BSEStar to query its endpoints
	- Prepares fields to be sent to BSEStar user creation and fatca endpoints
	- Posts the requests
	'''

	## initialise the zeep client for order wsdl
	client = zeep.Client(wsdl=WSDL_UPLOAD_URL[settings.LIVE])
	set_soap_logging()

	## get the password 
	pass_dict = soap_get_password_upload(client)
	## prepare the user record 
	bse_user = prepare_user_param(client_code)
	## post the user creation request
	user_response = soap_create_user(client, bse_user, pass_dict)
	## TODO: Log the soap request and response post the user creation request

	pass_dict = soap_get_password_upload(client)
	bse_fatca = prepare_fatca_param(client_code)
	fatca_response = soap_create_fatca(client, bse_fatca, pass_dict)
	## TODO: Log the soap request and response post the fatca creation request 
Example #8
Source File: 1-deleterecord-SOAP.py    From making-apis-work-for-you with Apache License 2.0 6 votes vote down vote up
def deletehostrecord(bam_url, login_user, login_password, host_record):
    """Delete host record
    """
    # api session
    client = Client(bam_url)

    # login
    client.service.login(login_user,login_password)
    # get the host record details
    print("You are requesting to delete:")
    print(host_record)
    answer = input("Do you want to proceed (y (yes) or n (no))? ")
    if answer.lower() == "y":
        deletion = client.service.deleteWithOptions(host_record['id'],
                                                "deleteOrphanedIPAddresses=true|")
    elif answer.lower() == "n":
        print("You requested deletion to be stopped")
    else:
        print("Invalid Entry")
    # logout of BAM
    client.service.logout()
    # return the records from function 
Example #9
Source File: 1-deleterecord-SOAP.py    From making-apis-work-for-you with Apache License 2.0 6 votes vote down vote up
def gethostrecordwithhint(bam_url, login_user, login_password, host_record_name):
    """get the host record FQDN and return the entity details
    """
    records = ""
    try:
        # api session
        client = Client(bam_url)
        # login
        client.service.login(login_user, login_password)
        # get the host record details
        records = client.service.getHostRecordsByHint(
                                                    0,
                                                    10,
                                                    "hint="+host_record_name+"|"
                                                    )
        # logout of BAM
        client.service.logout()
    except zeep.exceptions.Fault as e:
        print(e.message)
        logging.exception(e)
        sys.exit(1)
    # return the records from function
    return records 
Example #10
Source File: SymantecDLP.py    From content with MIT License 6 votes vote down vote up
def list_incident_status_command(client: Client) -> Tuple[str, dict, dict]:
    raw_incident_status_list = client.service.listIncidentStatus()

    human_readable: str
    entry_context: dict = {}
    raw_response: dict = {}

    if raw_incident_status_list:
        incident_status_list = helpers.serialize_object(raw_incident_status_list)
        raw_response = incident_status_list
        outputs: list = [{'Incident Status': incident_status} for incident_status in incident_status_list]
        human_readable = tableToMarkdown('Symantec DLP incident status', outputs, removeNull=True)
    else:
        human_readable = 'No incident status found.'

    return human_readable, entry_context, raw_response 
Example #11
Source File: zeep_client.py    From python-tbk with MIT License 6 votes vote down vote up
def __init__(
        self,
        wsdl_url,
        key_data,
        cert_data,
        tbk_cert_data,
        password=None,
        transport_timeout=300,
    ):
        super(ZeepSoapClient, self).__init__(
            wsdl_url, key_data, cert_data, tbk_cert_data
        )
        self.wsse = ZeepWsseSignature.init_from_data(
            key_data, cert_data, tbk_cert_data, password=password
        )
        self.transport_timeout = transport_timeout
        self.transport = zeep.transports.Transport(timeout=self.transport_timeout)
        self.history = zeep.plugins.HistoryPlugin()
        self.client = zeep.Client(
            wsdl_url, wsse=self.wsse, transport=self.transport, plugins=[self.history]
        ) 
Example #12
Source File: 1-deleterecord-SOAP.py    From making-apis-work-for-you with Apache License 2.0 5 votes vote down vote up
def deletehostrecord(bam_url, login_user, login_password, host_record):
    """Delete host record
    """
    # api session
    client = Client(bam_url)

    # login
    client.service.login(login_user, login_password)
    # get the host record details
    zone = client.service.getParent(host_record['id'])
    print("You are requesting to delete:")
    print(host_record)
    answer = input("Do you want to proceed (y (yes) or n (no))? ")
    if answer.lower() == "y":
        deletion = client.service.deleteWithOptions(
                                        host_record['id'],
                                        "deleteOrphanedIPAddresses=true|")
    elif answer.lower() == "n":
        print("You requested deletion to be stopped")
    else:
        print("Invalid Entry")
    # logout of BAM
    client.service.quickDeploy(zone["id"], "services=DNS")

    client.service.logout()
    # return the records from function 
Example #13
Source File: 2-CheckAccess-SOAP.py    From making-apis-work-for-you with Apache License 2.0 5 votes vote down vote up
def getAccessRightbyuseronentity(bam_url, login_user, login_password, user_id, entity_id):
    """get the access rights for a user from getAccessRights api call
    """
    # api session
    client = Client(bam_url)

    # login
    client.service.login(login_user,login_password)
    # get the host record details
    accessrights = client.service.getAccessRight(entity_id,user_id)
    # logout of BAM
    client.service.logout()
    # return the records from function
    return accessrights 
Example #14
Source File: soap.py    From workday with ISC License 5 votes vote down vote up
def __init__(self, name, session, wsdl_url, authentication, proxy_url=None):
        """
        :param name: Name of this API
        :type  name: ``str``

        :param session: HTTP session to use for communication
        :type  session: :class:`requests.Session`

        :param wsdl_url: Path to the WSDL
        :type  wsdl_url: ``str``

        :param authentication: Authentication configuration
        :type  authentication: :class:`workday.auth.BaseAuthentication`

        :param proxy_url: (Optional) HTTP Proxy URL
        :type  proxy_url: ``str``
        """
        auth_kwargs = authentication.kwargs
        self._client = zeep.Client(
            wsdl=wsdl_url,
            transport=zeep.transports.Transport(session=session),
            **auth_kwargs
        ) 
Example #15
Source File: util.py    From odoo13-x64 with GNU General Public License v3.0 5 votes vote down vote up
def get_soap_client(wsdlurl, timeout=30):  # pragma: no cover (not part of normal test suite)
    """Get a SOAP client for performing requests. The client is cached. The
    timeout is in seconds."""
    # this function isn't automatically tested because the functions using
    # it are not automatically tested
    if (wsdlurl, timeout) not in _soap_clients:
        # try zeep first
        try:
            from zeep.transports import Transport
            transport = Transport(timeout=timeout)
            from zeep import CachingClient
            client = CachingClient(wsdlurl, transport=transport).service
        except ImportError:
            # fall back to non-caching zeep client
            try:
                from zeep import Client
                client = Client(wsdlurl, transport=transport).service
            except ImportError:
                # other implementations require passing the proxy config
                try:
                    from urllib import getproxies
                except ImportError:
                    from urllib.request import getproxies
                # fall back to suds
                try:
                    from suds.client import Client
                    client = Client(
                        wsdlurl, proxy=getproxies(), timeout=timeout).service
                except ImportError:
                    # use pysimplesoap as last resort
                    try:
                        from pysimplesoap.client import SoapClient
                        client = SoapClient(
                            wsdl=wsdlurl, proxy=getproxies(), timeout=timeout)
                    except ImportError:
                        raise ImportError(
                            'No SOAP library (such as zeep) found')
        _soap_clients[(wsdlurl, timeout)] = client
    return _soap_clients[(wsdlurl, timeout)] 
Example #16
Source File: 1-deleterecord-SOAP.py    From making-apis-work-for-you with Apache License 2.0 5 votes vote down vote up
def gethostrecordwithhint(bam_url, login_user, login_password, host_record_name):
    """get the host record FQDN and return the entity details
    """
    # api session
    client = Client(bam_url)
    # login
    client.service.login(login_user,login_password)
    # get the host record details
    records = client.service.getHostRecordsByHint(0,10,"hint="+host_record_name+"|")
    # logout of BAM
    client.service.logout()
    # return the records from function
    return records 
Example #17
Source File: types.py    From django-vies with MIT License 5 votes vote down vote up
def data(self):
        """VIES API response data."""
        client = Client(VIES_WSDL_URL)
        try:
            return client.service.checkVat(self.country_code, self.number)
        except Exception as e:
            logger.exception(e)
            raise 
Example #18
Source File: 2-CheckAccess-SOAP.py    From making-apis-work-for-you with Apache License 2.0 5 votes vote down vote up
def getuser(bam_url,login_user,login_password,user_name):
    """Get the User details
    """
    # api session
    client = Client(bam_url)
    # login
    client.service.login(login_user,login_password)
    # get User
    user = client.service.getEntityByName(0,user_name,"User")
    # logout
    client.service.logout()

    return user 
Example #19
Source File: resolve.py    From astrolibpy with GNU General Public License v3.0 5 votes vote down vote up
def resolve(objectName):
    """    R
esolve the object by name using CDS
    Example:
    >> resolve.resolve('M31')
    (10.684708329999999, 41.268749999999997)

    Requires the following modules:
        suds, lxml
    """
    url = 'http://cdsws.u-strasbg.fr/axis/services/Sesame?wsdl'
    client = Client(url)    
    xml=client.service.SesameXML(objectName)           
    tree = etree.fromstring(xml.encode('utf-8'))
    # take the first resolver
    success=True
    for i in range(4):
        pathRa = tree.xpath('/Sesame/Target/Resolver[%d]/jradeg'%i)
        pathDec = tree.xpath('/Sesame/Target/Resolver[%d]/jdedeg'%i)
        if len(pathRa)!=0:
            success=True
            break
    if not success:
        return []
    ra=float(pathRa[0].text)
    dec=float(pathDec[0].text)
    return ra,dec 
Example #20
Source File: cybersource.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def issue_credit(self, order_number, basket, reference_number, amount, currency):
        try:
            client = Client(self.soap_api_url, wsse=UsernameToken(self.merchant_id, self.transaction_key))

            credit_service = {
                'captureRequestID': reference_number,
                'run': 'true',
            }
            purchase_totals = {
                'currency': currency,
                'grandTotalAmount': six.text_type(amount),
            }

            response = client.service.runTransaction(
                merchantID=self.merchant_id,
                merchantReferenceCode=order_number,
                orderRequestToken=reference_number,
                ccCreditService=credit_service,
                purchaseTotals=purchase_totals
            )

            request_id = response.requestID
            ppr = self.record_processor_response(serialize_object(response), transaction_id=request_id,
                                                 basket=basket)
        except:
            msg = 'An error occurred while attempting to issue a credit (via CyberSource) for order [{}].'.format(
                order_number)
            logger.exception(msg)
            raise GatewayError(msg)

        if response.decision == 'ACCEPT':
            return request_id
        raise GatewayError(
            'Failed to issue CyberSource credit for order [{order_number}]. '
            'Complete response has been recorded in entry [{response_id}]'.format(
                order_number=order_number, response_id=ppr.id)) 
Example #21
Source File: binary_sensor.py    From SmartHouse with MIT License 5 votes vote down vote up
def _async_update(self):
        from zeep import Client
        from zeep.exceptions import Fault
        service = Client('https://burze.dzis.net/soap.php?WSDL').service
        try:
            self.ostrzezenia_pogodowe_output = service.ostrzezenia_pogodowe(self._y, self._x, self._api_key)
            self.szukaj_burzy_output = service.szukaj_burzy(self._y, self._x, self._radius, self._api_key)
        except Fault as fault:
            _LOGGER.error('Error setting up burze_dzis_net: {}', fault) 
Example #22
Source File: 2-CheckAccess-SOAP.py    From making-apis-work-for-you with Apache License 2.0 5 votes vote down vote up
def gethostrecordwithhint(bam_url, login_user, login_password, host_record_name):
    """get the host record FQDN and return the entity details
    """
    # api session
    client = Client(bam_url)
    # login
    client.service.login(login_user,login_password)
    # get the host record details
    records = client.service.getHostRecordsByHint(0,10,"hint="+host_record_name+"|")
    # logout of BAM
    client.service.logout()
    # return the records from function
    return records 
Example #23
Source File: client.py    From netsuite with MIT License 5 votes vote down vote up
def _generate_client(self) -> zeep.Client:
        client = zeep.Client(self.wsdl_url, transport=self.transport,)
        self._set_default_soapheaders(
            client, preferences=self.config.preferences,
        )
        return client 
Example #24
Source File: client.py    From netsuite with MIT License 5 votes vote down vote up
def _set_default_soapheaders(client: zeep.Client, preferences: dict = None) -> None:
        client.set_default_soapheaders(
            {
                # https://netsuite.custhelp.com/app/answers/detail/a_id/40934
                # (you need to be logged in to SuiteAnswers for this link to work)
                # 'preferences': {
                #     'warningAsError': True/False,
                #     'disableMandatoryCustomFieldValidation': True/False,
                #     'disableSystemNotesForCustomFields': True/False,
                #     'ignoreReadOnlyFields': True/False,
                #     'runServerSuiteScriptAndTriggerWorkflows': True/False,
                # },
            }
        ) 
Example #25
Source File: client.py    From netsuite with MIT License 5 votes vote down vote up
def client(self) -> zeep.Client:
        return self._generate_client() 
Example #26
Source File: api.py    From mf-platform-bse with MIT License 5 votes vote down vote up
def cancel_transaction_bse(transaction):
	'''
	Cancels a transaction created earlier on BSEStar
	Note that this can be done only till 3pm on day when order is sent by BSEStar to RTA
	'''

	## initialise the zeep client for order wsdl
	client = zeep.Client(wsdl=WSDL_ORDER_URL[settings.LIVE])
	set_soap_logging()

	## get the password for posting order
	pass_dict = soap_get_password_order(client)
	
	## get trans_no of the order to be cancelled
	trans_no_of_order = transaction.bse_trans_no

	## get order_id of the transaction to be cancelled 
	## trans_no is of the type 2016080110000011 
	order_type = trans_no_of_order[8]
	order_id = TransResponseBSE.objects.get(trans_no=trans_no_of_order).order_id

	## prepare cancellation order
	bse_order = prepare_order_cxl(transaction, order_id, pass_dict)

	## for lumpsum order 
	if (order_type == '1'):
		## post the order
		order_id = soap_post_order(client, bse_order)
	## for XSIP order 
	elif (order_type == '2'):
		order_id = soap_post_xsip_order(client, bse_order)

	## update internal's transaction table to have a foreign key to cancellation order
	transaction.bse_trans_no = bse_order.trans_no
	transaction.status = '1'	## status 'canceled'
	transaction.save() 
Example #27
Source File: api.py    From mf-platform-bse with MIT License 5 votes vote down vote up
def get_payment_link_bse(client_code, transaction_id):
	'''
	Gets the payment link corresponding to a client
	Called immediately after creating transaction 
	'''

	## get the payment link and store it
	client = zeep.Client(wsdl=WSDL_UPLOAD_URL[settings.LIVE])
	set_soap_logging()
	pass_dict = soap_get_password_upload(client)
	payment_url = soap_create_payment(client, str(client_code), transaction_id, pass_dict)
	PaymentLinkBSE.objects.create(
		user_id=client_code, 
		link=payment_url, 
	)
	return payment_url 
Example #28
Source File: SymantecDLP.py    From content with MIT License 5 votes vote down vote up
def test_module(client: Client, saved_report_id: int):
    """
    Performs basic get request to get item samples
    """
    helpers.serialize_object(client.service.incidentList(
        savedReportId=saved_report_id,
        incidentCreationDateLaterThan=parse_date_range('1 year')[0]
    ))
    demisto.results('ok') 
Example #29
Source File: SymantecDLP.py    From content with MIT License 5 votes vote down vote up
def get_incident_details_command(client: Client, args: dict) -> Tuple[str, dict, dict]:
    incident_id: str = args.get('incident_id', '')

    raw_incident: list = client.service.incidentDetail(
        incidentId=incident_id,
        includeHistory=True,
        includeViolations=True
    )

    human_readable: str
    entry_context: dict = {}
    raw_response: dict = {}

    if raw_incident and isinstance(raw_incident, list):
        serialized_incident = helpers.serialize_object(raw_incident[0])
        raw_response = json.loads(json.dumps(serialized_incident, default=datetime_to_iso_format))
        incident_details: dict = get_incident_details(raw_response, args)
        raw_headers = ['ID', 'CreationDate', 'DetectionDate', 'Severity', 'Status', 'MessageSourceType',
                       'MessageType', 'Policy Name']
        headers = ['ID', 'Creation Date', 'Detection Date', 'Severity', 'Status', 'DLP Module',
                   'DLP Module subtype', 'Policy Name']
        outputs: dict = {}
        for raw_header in raw_headers:
            if raw_header == 'Policy Name':
                outputs['Policy Name'] = incident_details.get('Policy', {}).get('Name')
            else:
                outputs[headers[raw_headers.index(raw_header)]] = incident_details.get(raw_header)
        human_readable = tableToMarkdown(f'Symantec DLP incident {incident_id} details', outputs, headers=headers,
                                         removeNull=True)
        entry_context = {'SymantecDLP.Incident(val.ID && val.ID === obj.ID)': incident_details}
    else:
        human_readable = 'No incident found.'

    return human_readable, entry_context, raw_response 
Example #30
Source File: SymantecDLP.py    From content with MIT License 5 votes vote down vote up
def list_incidents_command(client: Client, args: dict, saved_report_id: str) -> Tuple[str, dict, dict]:
    if not saved_report_id:
        raise ValueError('Missing saved report ID. Configure it in the integration instance settings.')

    creation_date = parse_date_range(args.get('creation_date', '1 day'))[0]

    raw_incidents = client.service.incidentList(
        savedReportId=saved_report_id,
        incidentCreationDateLaterThan=creation_date
    )

    human_readable: str
    entry_context: dict = {}
    raw_response: dict = {}

    if raw_incidents:
        serialized_incidents: dict = helpers.serialize_object(raw_incidents)
        incidents_ids_list = serialized_incidents.get('incidentId')
        if incidents_ids_list:
            raw_response = serialized_incidents
            incidents = [{'ID': str(incident_id)} for incident_id in incidents_ids_list]
            human_readable = tableToMarkdown('Symantec DLP incidents', incidents, removeNull=True)
            entry_context = {'SymantecDLP.Incident(val.ID && val.ID == obj.ID)': incidents}
        else:
            human_readable = 'No incidents found.'
    else:
        human_readable = 'No incidents found.'

    return human_readable, entry_context, raw_response