Ejemplo n.º 1
0
def _setup_connection():
    # Setup SOAP/AXL/HTTPS Connection
    global service
    # Change to true to enable output of request/response headers and XML
    DEBUG = False

    # The WSDL is a local file in the working directory, see README
    WSDL_FILE = 'schema/AXLAPI.wsdl'

    # This class lets you view the incoming and outgoing http headers and XML

    class MyLoggingPlugin(Plugin):

        def egress(self, envelope, http_headers, operation, binding_options):

            # Format the request body as pretty printed XML
            xml = etree.tostring(envelope, pretty_print=True, encoding='unicode')

            print(f'\nRequest\n-------\nHeaders:\n{http_headers}\n\nBody:\n{xml}')

        def ingress(self, envelope, http_headers, operation):

            # Format the response body as pretty printed XML
            xml = etree.tostring(envelope, pretty_print=True, encoding='unicode')

            print(f'\nResponse\n-------\nHeaders:\n{http_headers}\n\nBody:\n{xml}')


    # The first step is to create a SOAP client session
    session = Session()

    # We avoid certificate verification by default
    # session.verify = False

    # To enabled SSL cert checking (recommended for production)
    # place the CUCM Tomcat cert .pem file in the root of the project
    # and uncomment the line below

    session.verify = sessionCert

    # Add Basic Auth credentials
    session.auth = HTTPBasicAuth(cucmusername, cucmpassword)

    # Create a Zeep transport and set a reasonable timeout value
    transport = Transport(session=session, timeout=10)

    # strict=False is not always necessary, but it allows zeep to parse imperfect XML
    settings = Settings(strict=False, xml_huge_tree=True)

    # If debug output is requested, add the MyLoggingPlugin callback
    plugin = [MyLoggingPlugin()] if DEBUG else [ ]

    # Create the Zeep client with the specified settings
    client = Client(WSDL_FILE, settings=settings, transport=transport,
            plugins=plugin)

    # FUTURE create CUCM chooser menu

    # Create the Zeep service binding to AXL at the specified CUCM
    service = client.create_service('{http://www.cisco.com/AXLAPIService/}AXLAPIBinding', serverUrl)
Ejemplo n.º 2
0
 def __init__(self, url, username, password):
     self.IdToPropType = dict()
     self.IdtoObjectType = dict()
     self.PropIdToDict = dict()
     self.RNEFnameToPropType = dict()
     from requests.auth import HTTPBasicAuth
     from requests import Session
     from zeep.cache import SqliteCache
     from zeep.transports import Transport
     session = Session()
     session.auth = HTTPBasicAuth(username, password)
     transport = Transport(cache=SqliteCache(), session=session)
     from zeep import Client, Settings
     settings = Settings(strict=False, xml_huge_tree=True)
     #settings = zeep.Settings(extra_http_headers={'Authorization': 'Bearer ' + token})
     self.logger = configure_logging(logging.getLogger(__name__))
     try:
         self.SOAPclient = Client(wsdl=url,
                                  transport=transport,
                                  settings=settings)
         self.__load_model()
         print('Connected to Resnet API server:\n%s as %s' %
               (url, username))
     except Exception as error:
         self.logger.error(
             "Pathway Studio server connection failed: {error}".format(
                 error=error))
         raise ConnectionError(
             f"Server connection failed. Wrong or inaccessible url: {url}"
         ) from None
Ejemplo n.º 3
0
 def consultar_cotizaciones_zeep(self, request, fdesde, fhasta, grupo,
                                 moneda):
     wsdl = "https://cotizaciones.bcu.gub.uy/wscotizaciones/servlet/awsbcucotizaciones?wsdl"
     settings = Settings(strict=False, xml_huge_tree=True)
     client2 = zeep.Client(wsdl=wsdl, settings=settings)
     request_zeep = {
         'Entrada': {
             'Moneda': {
                 'item': moneda
             },
             'FechaDesde': fdesde.isoformat(),
             'FechaHasta': fhasta.isoformat(),
             'Grupo': '0',
         }
     }
     respuesta_ws_cotiza_zeep = client2.service.Execute(**request_zeep)
     status_zeep = respuesta_ws_cotiza_zeep[
         'respuestastatus']  #Diccionario con 'status', 'codigoerror', 'mensaje'
     #Lista con Diccionarios, cada diccionario contiene: 'Fecha', 'Moneda', 'Nombre', 'CodigoISO', 'Emisor', 'TCC', 'TCV', 'ArbAct', 'FormaArbitrar'
     cotizaciones_zeep = respuesta_ws_cotiza_zeep['datoscotizaciones'][
         'datoscotizaciones.dato']
     return {
         'status_zeep': status_zeep,
         'cotizaciones_zeep': cotizaciones_zeep
     }
Ejemplo n.º 4
0
    def __init__(self, username, password, cucm, cucm_version):
        """
        :param username: ris username
        :param password: ris password
        :param cucm: UCM IP address
        :param cucm_version: UCM version

        example usage:
        >>> from ris import RIS
        >>> ucm = RIS('ris_user', 'ris_pass', '192.168.200.10', '11.5')
        """
        wsdl = 'https://' + cucm + ':8443/realtimeservice2/services/RISService70?wsdl'
        session = Session()
        session.verify = False
        session.auth = HTTPBasicAuth(username, password)
        settings = Settings(strict=False, xml_huge_tree=True)
        transport = Transport(session=session, timeout=10, cache=SqliteCache())
        ris_client = Client(wsdl, settings=settings, transport=transport)

        self.wsdl = wsdl
        self.username = username
        self.password = password
        self.cucm = cucm
        self.cucm_version = cucm_version
        self.UUID_PATTERN = re.compile(
            r'^[\da-f]{8}-([\da-f]{4}-){3}[\da-f]{12}$', re.IGNORECASE)
        self.client = ris_client.create_service(
            "{http://schemas.cisco.com/ast/soap}RisBinding",
            f"https://{cucm}:8443/realtimeservice2/services/RISService70")
    def __init__(self, username, password, cucm, cucm_version):

        cwd = os.path.dirname(os.path.abspath(__file__))
        if os.name == "posix":
            wsdl = Path(f"{cwd}/schema/{cucm_version}/AXLAPI.wsdl").as_uri()
        else:
            wsdl = str(
                Path(f"{cwd}/schema/{cucm_version}/AXLAPI.wsdl").absolute())
        session = Session()
        session.verify = False
        session.auth = HTTPBasicAuth(username, password)
        settings = Settings(strict=False,
                            xml_huge_tree=True,
                            xsd_ignore_sequence_order=True)
        transport = Transport(session=session, timeout=10, cache=SqliteCache())
        axl_client = Client(wsdl, settings=settings, transport=transport)

        self.wsdl = wsdl
        self.username = username
        self.password = password
        self.wsdl = wsdl
        self.cucm = cucm
        self.cucm_version = cucm_version
        self.UUID_PATTERN = re.compile(
            r"^[\da-f]{8}-([\da-f]{4}-){3}[\da-f]{12}$", re.IGNORECASE)
        self.client = axl_client.create_service(
            "{http://www.cisco.com/AXLAPIService/}AXLAPIBinding",
            f"https://{cucm}:8443/axl/",
        )
Ejemplo n.º 6
0
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.')
Ejemplo n.º 7
0
def get_soap_client_number():
    """Возвращает справочник контактов клиентов из SOAP-сервиса"""
    wsdl = auth.wsdl
    user = auth.user_soap
    password = auth.password_soap

    settings = Settings(
        strict=True
        # raw_response=True  # ответ без обработки lxml-модулем
        # force_https=False
        # xml_huge_tree=True  # ограничение глубины xml-дерева
        # forbid_dtd=True
        # forbid_entities=False
        # xsd_ignore_sequence_order=True
    )

    session = Session()
    session.auth = HTTPBasicAuth(user, password)

    client = Client(wsdl=wsdl,
                    settings=settings,
                    transport=Transport(session=session))

    request = client.service.ExecProcJSON('Service', params)
    result = ast.literal_eval(
        request)  # Предобразование строки в список словарей

    return result
Ejemplo n.º 8
0
    def __init__(self, ):
        session = Session()
        session.verify = False
        transport = Transport(session=session)
        settings = Settings(strict=False, xml_huge_tree=True)

        self.client_login = Client(
            'https://tkps-http.ldz.lv/kpsws-webapp/Login?wsdl',
            settings=settings,
            transport=transport,
            plugins=[
                KpsLoginPlugin(),
            ])

        self.client_classifiers = Client(
            'https://tkps-http.ldz.lv:443/kpsws-webapp/Classifiers?wsdl',
            settings=settings,
            transport=transport,
            plugins=[
                KpsLoginPlugin(),
            ])

        self.client_cnotes = Client(
            'https://tkps-http.ldz.lv/kpsws-webapp/Cnotes?wsdl',
            settings=settings,
            transport=transport,
            plugins=[
                KpsLoginPlugin(),
            ])
Ejemplo n.º 9
0
def get_n11com_client(servicecategory):
    soapserver = "https://api.n11.com"
    strictsetting = False
    rawresponsesetting = False

    wsdl = soapserver + get_n11com_servicepath(servicecategory)
    settings = Settings(strict=strictsetting, raw_response=rawresponsesetting)
    return Client(wsdl, settings=settings)
Ejemplo n.º 10
0
def test_wsdl_dtd_entities_rules():
    wsdl_declaration = u"""<!DOCTYPE Author [
        <!ENTITY writer "Donald Duck.">
        ]>
        <wsdl:definitions
        xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        xmlns:tns="http://tests.python-zeep.org/xsd-main"
        xmlns:mine="http://tests.python-zeep.org/xsd-secondary"
        xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/"
        targetNamespace="http://tests.python-zeep.org/xsd-main">
        <wsdl:types>
          <xsd:schema
              targetNamespace="http://tests.python-zeep.org/xsd-main"
              xmlns:tns="http://tests.python-zeep.org/xsd-main">
            <xsd:element name="input" type="xsd:string"/>
          </xsd:schema>
        </wsdl:types>
        <wsdl:message name="message-1">
          <wsdl:part name="response" element="tns:input"/>
        </wsdl:message>
        <wsdl:portType name="TestPortType">
          <wsdl:operation name="TestOperation1">
            <wsdl:input message="message-1"/>
          </wsdl:operation>
        </wsdl:portType>
        </wsdl:definitions>
    """.strip()

    transport = DummyTransport()
    transport.bind('http://tests.python-zeep.org/schema-2.wsdl',
                   wsdl_declaration)

    with pytest.raises(DTDForbidden):
        wsdl.Document(StringIO(wsdl_declaration),
                      transport,
                      settings=Settings(forbid_dtd=True))

    with pytest.raises(EntitiesForbidden):
        wsdl.Document(StringIO(wsdl_declaration), transport)

    document = wsdl.Document(StringIO(wsdl_declaration),
                             transport,
                             settings=Settings(forbid_entities=False))
    document.dump()
Ejemplo n.º 11
0
def soap_request(url, params: Params):
    headerArr = {}
    settings = Settings(strict=False,
                        xml_huge_tree=True,
                        extra_http_headers=headerArr)
    client = Client(url, settings=settings)

    requestData = params.get_request_body()
    return client.service.calculate(**requestData)
def GetStopDataByRoutesCSV():
    starttime = time.time()
    settings = Settings(force_https=False, raw_response=True)
    client = Client('http://rtpi.dublinbus.ie/DublinBusRTPIService.asmx?WSDL',
                    settings=settings)

    routeList = pandas.read_csv("/dublinbus/GetRoute.csv",
                                header=0)["Route"].tolist()

    ##GetStopDataByRoutes: Each Route
    route = []
    directionList = []
    stopList = []
    addressList = []
    locationList = []
    seqnumberList = []
    seqnumberextList = []
    for routeNumber in routeList:

        print('Retriving stop information for route: ' + routeNumber)
        routeStops = client.service.GetStopDataByRoute(routeNumber)
        dom = ET.fromstring(routeStops.content)
        for stopNumber in dom.findall('.//StopNumber'):
            route.append(routeNumber)
            stopList.append(stopNumber.text)
        for Direction in dom.findall('.//Direction'):
            directionList.append(Direction.text)
        for Address in dom.findall('.//Address'):
            addressList.append(Address.text)
        for Location in dom.findall('.//Location'):
            locationList.append(Location.text)
        for SeqNumber in dom.findall('.//SeqNumber'):
            seqnumberList.append(SeqNumber.text)
        for SeqNumberExt in dom.findall('.//SeqNumberExt'):
            seqnumberextList.append(SeqNumberExt.text)

    print('There are total number of ' + str(len(stopList)) +
          ' stops retrived from ' + str(len(routeList)) + ' routes')
    #print(route)#test
    #print(stopList)#test

    d = {
        'Route': route,
        'StopID': stopList,
        'Direction': directionList,
        'Address': addressList,
        'Location': locationList,
        'SeqNumber': seqnumberList,
        'SeqNumberExt': seqnumberextList
    }
    df = pandas.DataFrame(data=d)
    df.to_csv("/dublinbus/GetStopDataByRoutes.csv", index=False, header=True)

    endtime = time.time()
    print(
        '-----------"GetStopDataByRoutes.csv" File saved on Desktop----------')
    print('----------%s seconds----------' % (endtime - starttime))
Ejemplo n.º 13
0
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
Ejemplo n.º 14
0
 def start_rating_transaction(self, wsdl_path):
     settings = Settings(strict=False)
     self.client = Client('file:///%s' % wsdl_path.lstrip('/'), plugins=[LogPlugin(self.debug_logger)], settings=settings)
     self.factory = self.client.type_factory('ns0')
     self.VersionId = self.factory.VersionId()
     self.VersionId.ServiceId = 'crs'
     self.VersionId.Major = '16'
     self.VersionId.Intermediate = '0'
     self.VersionId.Minor = '0'
Ejemplo n.º 15
0
def CUZKClient(wsdl):
    transport = Transport(cache=SqliteCache())
    settings = Settings(raw_response=False, strict=False, xml_huge_tree=True)
    settings = Settings(strict=False, xml_huge_tree=True)
    relevantWsdls = prodWsdls
    creds = None
    if TRIAL:
        relevantWsdls = trialWsdls
        creds = ["WSTESTO", "WSHESLOO"]
    if not creds[0] and not creds[1]:
        print("Nastavte creds ve funkci CUZKClient")
        sys.exit(0)

    return Client(
        relevantWsdls[wsdl],
        transport=transport,
        wsse=UsernameToken(*creds),
        settings=settings,
    )
Ejemplo n.º 16
0
    def soap_call(envData,service, data):
        settings = Settings(strict=False, xml_huge_tree=True)
        client = Client(envData["url"], settings=settings)

        with client.settings(raw_response=True):
            response = client.service.Add(**data)
            if response.status_code == 200:
                root = ET.fromstring(response.content)
                return root
            else:
                module_logger.error(f'Response Code:{response.status_code}')
Ejemplo n.º 17
0
def soapinfo(CUCM_URL, USERNAME, PASSWD, WSDL_URL):
    #Create SOAP Session
    session = Session()
    session.verify = False
    session.auth = HTTPBasicAuth(USERNAME, PASSWD)
    transport = Transport(session=session, timeout=10, cache=SqliteCache())
    settings = Settings(strict=False, xml_huge_tree=True)
    client = Client(WSDL_URL, settings=settings, transport=transport)
    service = client.create_service(
        "{http://www.cisco.com/AXLAPIService/}AXLAPIBinding", CUCM_URL)
    return service
Ejemplo n.º 18
0
 def __init__(self, start_date, project_id, dataset_id):
     self.semaphore = threading.Semaphore(3)
     self.lock = threading.Lock()
     self.client = bigquery.Client(project_id)
     self.dataset_id = dataset_id
     self.current_date = datetime.strptime(start_date, '%Y-%m-%d')
     self.current_page = 1
     self.processed = 0
     self.current_throttle = 0
     self.url = BaseConfig.API_CEIDG_URL
     settings = Settings(strict=False, xml_huge_tree=True)
     self.soap_client = Client(self.url, settings=settings)
Ejemplo n.º 19
0
 def __init__(self):
     try:
         session = Session()
         session.auth = HTTPBasicAuth(axl_client.username,axl_client.password)
         session.verify = False
         transport = Transport(session = session,timeout = 3)
         settings = Settings(strict = False,xml_huge_tree = True)
         plugin = [ MyLoggingPlugin() ] if axl_client.DEBUG else [ ]
         client = Client(wsdl=axl_client.WSDL_FILE,settings = settings,transport=transport, plugins=plugin)
         self.service = client.create_service(axl_client.axl_binding,axl_client.CallManager)
     except Exception as e:
         logger._write("axl initialize failed %s" % e, debugtype="DEBUG")
Ejemplo n.º 20
0
 def connect(self):
     """
     """
     session = Session()
     settings = Settings(strict=False, xml_huge_tree=True)
     session.auth = HTTPBasicAuth(self.username, self.password)
     transport = Transport(session=session)
     self.client = Client(self.wsdl_url,
                          transport=transport,
                          settings=settings)
     self.service = self.client.bind('Titulus4Service', 'Titulus4')
     return self.client
Ejemplo n.º 21
0
    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)
Ejemplo n.º 22
0
    def _login_soap(self,
                    username=None,
                    password=None,
                    security_token=None,
                    url=None,
                    wsdl=None,
                    metadata=False):
        """Login via SOAP (Simple Object Access Protocol)

        Args:
            username (str): The Salesforce user username
            password (str): The Salesforce user password
            security_token (str): The Salesforce user Security Token
            url (str): The Salesforce SOAP API URL used for login
            wsdl (str): The path to the WSDL (Web Services Description Language) file
            metadata (bool): Whether or not to get the metadata server URL

        Returns:
            A tuple containing the session ID and (metadata) server URL
        """

        # Create client with setting of disable strict mode, use recovery mode
        setting = Settings(strict=False)
        client = Client(wsdl, settings=setting)

        try:
            # Attempt to make the request for the response
            r = client.service.login(username, password + security_token)
        except exceptions.Fault:
            # Return None for now if exception
            return None

        # Check to see if the client service succeeded
        if r is not None:
            # Get the sessionId
            session_id = r['sessionId']

            if metadata:
                # Get the `metadataServerUrl` if requested
                metadata_server_url = r['metadataServerUrl']

                # Return a tuple of the session ID and metadata server URL
                return (session_id, metadata_server_url)
            else:
                # Get the `serverUrl`
                server_url = r['serverUrl']

                # Return a tuple of the session ID and server URL
                return (session_id, server_url)

        # Return None for now if error
        return None
Ejemplo n.º 23
0
    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]
Ejemplo n.º 24
0
    def setClient(self, wsdl):
        """
        set soap client using a wsdl URL

        Parameters
        ----------
        wsdl: str
            provide a URL string to a fewsPi wsdl service
            (eg. 'http://www.oms-waddenzee.nl:8081/FewsPiService/fewspiservice?wsdl' or
            'http://localhost:8101/FewsPiService?wsdl')
        """
        settings = Settings(xml_huge_tree=True)
        self.client = Client(wsdl=wsdl, settings=settings)
Ejemplo n.º 25
0
    def __init__(self, login: str, password: str):
        """
        Инициализация API клиента сервиса отслеживания посылок.

        :param login: Логин от системы трекинга
        :param password: Пароль от системы трекинга
        """
        self._login = login
        self._password = password

        self._client = CachingClient(
            'https://tracking.russianpost.ru/rtm34?wsdl',
            settings=Settings(strict=False),
        )
Ejemplo n.º 26
0
class EconomicSOAPApi:
    wsdl = 'https://api.e-conomic.com/secure/api1/EconomicWebService.asmx?wsdl'
    settings = Settings()
    session = Session()
    transport = Transport(session=session)
    client = zeep.Client(wsdl=wsdl, settings=settings, transport=transport)

    def __init__(self) -> None:
        self.login()
        super().__init__()

    def login(self):
        self.client.service.ConnectWithToken(token=X_AGREEMENT_GRANT_TOKEN,
                                             appToken=X_APP_SECRET_TOKEN)
Ejemplo n.º 27
0
def get_client(
    wsdl: str = CHARITY_COMMISSION_WSDL,
    raw_response: bool = False,
    api_key_name: str = CHARITY_COMMISSION_API_KEY_NAME,
    api_key_value: Optional[CharityAPIKeyType] = CHARITY_COMMISSION_API_KEY,
    plugins: List[Plugin] = None,
    **kwargs,
) -> Client:
    """Generate a Client for querying Charities Commision API."""
    settings: Settings = Settings(strict=False,
                                  xml_huge_tree=True,
                                  raw_response=raw_response)
    plugins = ([CharitiesAuthPlugin(api_key_name, api_key_value)]
               if not plugins else plugins)
    return Client(wsdl=wsdl, settings=settings, plugins=plugins, **kwargs)
Ejemplo n.º 28
0
    def __init__(self,
                 server="",
                 provider="",
                 username="",
                 password="",
                 version=""):

        # TODO: add checks
        # for key, value in locals().items():
        #     if value is "":
        #         raise ValueError('Argument %s required', key)

        super(BaseProvisioningService, self).__init__()

        self.server = server
        self._add_scheme_to_server()

        self.provider = provider
        self.username = username
        self.password = password
        self.version = version

        self.endpoint = self._build_endpoint_from_server()
        self.wsdl = self._build_wsdl_url_from_endpoint()
        self.userpath = self._build_full_username()

        # plugin for fixing the arrays
        arrayfixer = ArrayFixer()
        booleanfixer = BooleanFixer()

        # initialize our client using basic auth and with the wsdl file
        session = Session()
        session.auth = HTTPBasicAuth(self.userpath, self.password)
        settings = Settings(
            strict=False,  # ePages wsdl files are full of errors...
        )
        client = Client(wsdl=self.wsdl,
                        settings=settings,
                        transport=Transport(session=session),
                        plugins=[arrayfixer, booleanfixer])
        self.client = client

        # get the binding name, there is only one so this should be ok
        qname = next(iter(client.wsdl.bindings))

        # and create new service with the name pointing to our endpoint
        self.service2 = client.create_service(qname, self.endpoint)
        logger.debug('Initialized new client: %s', self.client)
Ejemplo n.º 29
0
def GetRouteCSV():
    starttime = time.time()

    settings = Settings(force_https=False, raw_response=True)
    client = Client('http://rtpi.dublinbus.ie/DublinBusRTPIService.asmx?WSDL',
                    settings=settings)

    ##GetRoutes
    routes = client.service.GetRoutes(0)
    dom = ET.fromstring(routes.content)
    routeList = []
    SeqNumberList = []
    FromList = []
    TowardsList = []
    IsStagedList = []
    IsXpressoList = []
    IsNitelinkList = []
    IsMinimumFareList = []

    for number in dom.findall('.//{http://dublinbus.ie/}Number'):
        routeList.append(number.text)
    for SeqNumber in dom.findall('.//{http://dublinbus.ie/}SeqNumber'):
        SeqNumberList.append(SeqNumber.text)
    for From in dom.findall('.//{http://dublinbus.ie/}From'):
        FromList.append(From.text)
    for Towards in dom.findall('.//{http://dublinbus.ie/}Towards'):
        TowardsList.append(Towards.text)
    for IsStaged in dom.findall('.//{http://dublinbus.ie/}IsStaged'):
        IsStagedList.append(IsStaged.text)
    for IsXpresso in dom.findall('.//{http://dublinbus.ie/}IsXpresso'):
        IsXpressoList.append(IsXpresso.text)
    for IsNitelink in dom.findall('.//{http://dublinbus.ie/}IsNitelink'):
        IsNitelinkList.append(IsNitelink.text)
    for IsMinimumFare in dom.findall('.//{http://dublinbus.ie/}IsMinimumFare'):
        IsMinimumFareList.append(IsMinimumFare.text)

#     d = {'Route': routeList, 'SeqNumber': SeqNumberList, 'From': FromList, 'Towards': TowardsList,
#          'IsStaged': IsStagedList, 'IsXpresso': IsXpressoList, 'IsNitelink': IsNitelinkList,
#          'IsMinimumFare': IsMinimumFareList}
#     df = pandas.DataFrame(data=d)
# #print(df)#test
#     df.to_csv("/dublinbus/GetRoute.csv", index=False, header=True)

    endtime = time.time()
    dur = endtime - starttime

    print('----------"GetRoute.csv" File saved on Desktop----------')
    print('----------%s seconds-----------' % dur)
Ejemplo n.º 30
0
def connect_to_cucm(username=None, password=None, cucm_ip=None):
    WSDL_FILE = str(Path('schema') / 'AXLAPI.wsdl')

    DEBUG = False
    SUPRESS_INSECURE_CONNECTION_WARNINGS = True

    if SUPRESS_INSECURE_CONNECTION_WARNINGS:
        import urllib3
        urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

    # This class lets you view the incoming and outgoing http headers and/or XML
    class MyLoggingPlugin(Plugin):
        def egress(self, envelope, http_headers, operation, binding_options):
            xml = etree.tostring(envelope,
                                 pretty_print=True,
                                 encoding='unicode')
            print(
                f'\nRequest\n-------\nHeaders:\n{http_headers}\n\nBody:\n{xml}'
            )

        def ingress(self, envelope, http_headers, operation):
            xml = etree.tostring(envelope,
                                 pretty_print=True,
                                 encoding='unicode')
            print(
                f'\nResponse\n-------\nHeaders:\n{http_headers}\n\nBody:\n{xml}'
            )

    sess = Session()

    sess.verify = False
    sess.auth = HTTPBasicAuth(username, password)

    transport = Transport(session=sess, timeout=10)
    settings = Settings(strict=False, xml_huge_tree=True)

    plugin = [MyLoggingPlugin()] if DEBUG else []

    client = Client(WSDL_FILE,
                    settings=settings,
                    transport=transport,
                    plugins=plugin)

    service = client.create_service(
        '{http://www.cisco.com/AXLAPIService/}AXLAPIBinding',
        'https://{cucm}:8443/axl/'.format(cucm=cucm_ip))

    return service