예제 #1
0
파일: client.py 프로젝트: geelweb/affilinet
    def _get_inbox_client(self):
        self.logon(self.username, self.password, 'Publisher')

        wsdl_url = self.url + '/PublisherInbox.svc?wsdl'

        client = SudsClient(url=wsdl_url)
        return client
예제 #2
0
def runSimulator():
    url = 'http://127.0.0.1:8000/qwc?wsdl'
    print "simulator"
    client = SudsClient(url=url, cache=None)
    while True:
        returnArray = client.service.authenticate( strUserName = config['qwc']['username'], strPassword= config['qwc']['password'])
        print 'returnArray[0]',returnArray[0]
        if returnArray and (returnArray[0][1] <> "none") and (returnArray[0][1] <> "nvu"):
            ticket = str(returnArray[0][0])
            reqXML = client.service.sendRequestXML(ticket,strHCPResponse="",strCompanyFileName=returnArray[0][1],qbXMLCountry="",qbXMLMajorVers=8,qbXMLMinorVers=0)
            print reqXML
            root = etree.fromstring(str(reqXML))
            isIterator = root.xpath('boolean(//QBXMLMsgsRq/*[1]/@iterator)')
            while isIterator:
                iterator = root.xpath('//QBXMLMsgsRq/*[1]/@iterator')[0]
                requestID = int(root.xpath('//InvoiceQueryRq/@requestID')[0])
                requestID +=1                    
                if iterator == 'Start':
                    iterator = 'Continue'
                    iteratorID  =  str(uuid.uuid1())
                    iteratorRemainingCount=20
                elif iterator == 'Continue':
                    
                    iteratorRemainingCount  -= 1
                responsexml = qbxml.make_fake_invoice(requestID,iteratorID,iteratorRemainingCount,iterator)
                percentRemaining = client.service.receiveResponseXML( ticket = ticket,response=responsexml,hresult ="",message="")
                time.sleep(5)
                reqXML = client.service.sendRequestXML(ticket,strHCPResponse="",strCompanyFileName=returnArray[0][1],qbXMLCountry="",qbXMLMajorVers=8,qbXMLMinorVers=0)
                print reqXML
                root = etree.fromstring(str(reqXML))
                isIterator = root.xpath('boolean(//QBXMLMsgsRq/*[1]/@iterator)')
            break
        else:    
            time.sleep(5)
예제 #3
0
파일: client.py 프로젝트: geelweb/affilinet
    def _get_product_client(self):
        self.logon(self.username, self.password, 'Product')

        wsdl_url = self.url + '/ProductServices.svc?wsdl'

        client = SudsClient(url=wsdl_url)
        return client
예제 #4
0
    def _authenticate_by_token(self, token_id, applicationid):
        client = SudsClient(self._services['Authenticate'])
        token = client.factory.create('Token')
        token.Id = token_id
        token.ApplicationId = applicationid
        passport = client.service.AuthenticateByToken(token)

        return passport.SessionId
예제 #5
0
    def get_soap_client_service(cls):
        if None != cls.__client:
            return cls.__client

        url = 'http://www.webservicex.net/geoipservice.asmx?wsdl'
        cls.__client = SudsClient(url)

        return cls.__client.service
예제 #6
0
    def __init__(self, username, password):
        # Prepare a SUDS transport with the approperiate credentials
        transport = EnhancedDNSHttpAuthenticated(username=username,
                                                 password=password,
                                                 proxy=utils.get_proxies())

        # Prepare a SUDS client
        self.client = SudsClient(CONF['backend:akamai'].enhanceddns_wsdl,
                                 transport=transport)
예제 #7
0
    def __init__(self, service_name, login, private_key_file='decrypted_key', endpoint='api.transip.nl'):
        self.service_name = service_name
        self.login = login
        self.private_key_file = private_key_file
        self.endpoint = endpoint
        self.url = URI_TEMPLATE.format(endpoint, service_name)

        imp = Import('http://schemas.xmlsoap.org/soap/encoding/')
        doc = ImportDoctor(imp)
        self.soap_client = SudsClient(self.url, doctor=doc)
예제 #8
0
파일: client.py 프로젝트: geelweb/affilinet
    def _get_program_client(self):
        self.logon(self.username, self.password, 'Publisher')

        wsdl_url = self.url + '/PublisherProgram.svc?wsdl'

        schema_url = 'http://affilinet.framework.webservices/types/PublisherProgram'
        schema_import = Import(schema_url)
        schema_doctor = ImportDoctor(schema_import)

        client = SudsClient(url=wsdl_url, doctor=schema_doctor)
        return client
예제 #9
0
def oil_current_price():
    # Get SOAP Service via suds
    url = 'http://www.pttplc.com/webservice/pttinfo.asmx?WSDL'
    client = SudsClient(url)
    # Execute CurrentOilPrice method of SOAP
    xml = client.service.CurrentOilPrice("EN")
    # Convert XML to dict
    res_dict = xmltodict.parse(xml)
    result = {}
    result['result'] = res_dict['PTT_DS']['DataAccess']
    # Convert dict to JSON
    return jsonify(**result)
예제 #10
0
파일: client.py 프로젝트: geelweb/affilinet
    def logon(self, username, password, service_type, sandbox_publisher_id=None):
        wsdl_url = self.url + '/Logon.svc?wsdl'

        schema_url = 'http://affilinet.framework.webservices/types'
        schema_import = Import(schema_url)
        schema_doctor = ImportDoctor(schema_import)

        client = SudsClient(url=wsdl_url, doctor=schema_doctor)
        self.credential_token = client.service.Logon(
            username,
            password,
            service_type)
예제 #11
0
def _doResumeParseByFile(b64content, ext):
    try:
        soapCli = SudsClient(Conf.YGYS['soapuri'],
                             timeout=Conf.YGYS['timeout'])
    except BaseException as e:
        logger.error(u'无法连接简历解析SOAP服务,uri:<{}>,e:<{}>'.format(
            Conf.YGYS['soapuri'], e))
        return
    try:
        return soapCli.service.TransResumeByJsonStringForFileBase64(
            Conf.YGYS['username'], Conf.YGYS['password'], b64content, ext)
    except BaseException as e:
        logger.error(u'简历文件解析失败,原因:{}'.format(e))
예제 #12
0
 def _authenticate(self,
                   username,
                   password,
                   applicationid,
                   identityid=None):
     client = SudsClient(self._services['Authenticate'],
                         faults=self._faults)
     cred = client.factory.create('Credential')
     cred.Username = username
     cred.Password = password
     cred.ApplicationId = applicationid
     cred.IdentityId = identityid
     return client.service.Login(cred)
예제 #13
0
파일: client.py 프로젝트: geelweb/affilinet
    def _get_creatives_client(self):
        self.logon(self.username, self.password, 'Publisher')

        wsdl_url = self.url + '/PublisherCreative.svc?wsdl'

        schema_url = 'http://affilinet.framework.webservices/Svc'
        schema_import = Import(schema_url)
        schema_doctor = ImportDoctor(schema_import)

        schema_doctor.add(Import('http://affilinet.framework.webservices/types/PublisherCreative'))
        schema_doctor.add(Import('http://schemas.microsoft.com/2003/10/Serialization/Arrays'))

        client = SudsClient(url=wsdl_url, doctor=schema_doctor)
        return client
예제 #14
0
    def _get_client(self, name):
        """
        Return a client

        TODO change name to: get_handler ?
        get_api ?
        """
        if name in self._clients:
            return self._clients[name]

        # Create a new client
        self._clients[name] = SudsClient(self._services[name],
                                         faults=self._faults,
                                         headers=self._headers)
        logging.debug('Created new service: %s' % name)
        return self._clients[name]
예제 #15
0
    def __init__(self, **kwargs):
        super(TransIP, self).__init__(**kwargs)
        self.service_name = 'DomainService'
        self.login = kwargs['api_email']
        self.private_key_file = kwargs['api_key']
        self.endpoint = 'api.transip.nl'
        self.url = URI_TEMPLATE.format(self.endpoint, self.service_name)

        imp = Import('http://schemas.xmlsoap.org/soap/encoding/')
        doc = ImportDoctor(imp)

        suds_kwargs = dict()
        if suds_requests:
            suds_kwargs['transport'] = suds_requests.RequestsTransport()

        self.soap_client = SudsClient(self.url, doctor=doc, **suds_kwargs)
예제 #16
0
    def __init__(self, soap_endpoint, user_id, encryption_key):
        """
        Instantiate the suds client and add the SOAP types and methods to the list of attributes
        How to get the Marketo SOAP parameters: See page 4 of the Marketo SOAP Api doc.
        """
        self.soap_endpoint = soap_endpoint
        self.user_id = user_id
        self.encryption_key = encryption_key

        self.suds_client = SudsClient(Client.MARKETO_WSDL,
                                      location=soap_endpoint)
        # Make easy the access to the types and methods
        for suds_type in self.suds_client.sd[0].types:
            self.suds_types.append(suds_type[0].name)
        for suds_method in self.suds_client.sd[0].service.ports[
                0].binding.operations:
            self.suds_methods.append(suds_method)
예제 #17
0
파일: client.py 프로젝트: Navegg/ddpclient
    def _create_soap_client(self, url):
        soap_client = SudsClient(url)

        # set http headers
        http_headers = {}
        self.credentials.apply(http_headers)

        soap_client.set_options(headers=http_headers)

        # set soap headers
        soap_headers = soap_client.factory.create('SoapHeader')
        soap_headers.clientCustomerId = self.client_customer_id
        soap_headers.userAgent = USER_AGENT
        soap_client.set_options(soapheaders=soap_headers)

        # https://fedorahosted.org/suds/wiki/TipsAndTricks#TypesNamesContaining
        soap_client.factory.separator('/')

        return soap_client
예제 #18
0
    def __init__(self,
                 service_name,
                 login,
                 private_key=None,
                 private_key_file='decrypted_key',
                 endpoint='api.transip.nl'):
        self.service_name = service_name
        self.login = login
        self.private_key = private_key
        self.private_key_file = private_key_file
        self.endpoint = endpoint
        self.url = URI_TEMPLATE.format(endpoint, service_name)

        imp = Import('http://schemas.xmlsoap.org/soap/encoding/')
        doc = ImportDoctor(imp)

        suds_kwargs = dict()
        if suds_requests:
            suds_kwargs['transport'] = suds_requests.RequestsTransport()

        self.soap_client = SudsClient(self.url, doctor=doc, **suds_kwargs)
예제 #19
0
def _init_suds(wsdl):
    imp = Import('http://www.w3.org/2001/XMLSchema')
    imp.filter.add('http://thinkministry.com/')
    return SudsClient(wsdl, plugins=[ImportDoctor(imp)])
예제 #20
0
from suds.client import Client as SudsClient

url = 'http://127.0.0.1:5000/soap/someservice?wsdl'
client = SudsClient(url=url, cache=None)
r = client.service.obtenerMateriaAlumno(1234)
print r
            testklassen = []

            if ('MD_Metadata' in response):
                testklassen = [15, 16]
            #if ('service-feed' in xmlfilename.lower()): # Todo: better check
                #testklassen = [17]
            #elif ('WMT_MS_Capabilities' in response):
                #testklassen = [18, 20]

            for testklasse in testklassen:

                # Starte Tests
                credentials = {'userName': '******', 'pass': u'testtest'}

                proxies = {}
                client = SudsClient('http://testsuite.gdi-de.org/gdi/download?id=wsdl', proxy=proxies)

                #getTestClass
                parameter_get_test_class = {'testClassID': testklasse}
                parameter_get_test_class.update(credentials)
                testclass = client.service.getTestClass(**parameter_get_test_class)



                print 'Prüfe mit GDI-DE Testsuite {' + str(testclass.Name) + '} ' + url

                # setTestConfiguration
                parameter_set_test_configuration = {'name': name,
                                                    'description': url,
                                                    'notify': 'NO',
                                                    'url': url,
예제 #22
0
    def saveWaveform(self,
                     filename,
                     network,
                     station,
                     location,
                     channel,
                     starttime,
                     endtime,
                     format="MSEED"):
        """
        Writes a retrieved waveform directly into a file.

        This method ensures the storage of the unmodified waveform data
        delivered by the NERIES Web service, e.g. preserving the record based
        quality flags of MiniSEED files which would be neglected reading it
        with obspy.mseed.

        :type filename: str
        :param filename: Name of the output file.
        :type network: str
        :param network: Network code, e.g. ``'BW'``.
        :type station: str
        :param station: Station code, e.g. ``'MANZ'``.
        :type location: str
        :param location: Location code, e.g. ``'01'``. Location code may
            contain wild cards.
        :type channel: str
        :param channel: Channel code, e.g. ``'EHE'``. . Channel code may
            contain wild cards.
        :type starttime: :class:`~obspy.core.utcdatetime.UTCDateTime`
        :param starttime: Start date and time.
        :type endtime: :class:`~obspy.core.utcdatetime.UTCDateTime`
        :param endtime: End date and time.
        :type format: ``'FSEED'`` or ``'MSEED'``, optional
        :param format: Output format. Either as full SEED (``'FSEED'``) or
            Mini-SEED (``'MSEED'``) volume. Defaults to ``'MSEED'``.
        :return: None

        .. seealso:: http://www.orfeus-eu.org/wsdl/seismolink/seismolink.wsdl

        .. rubric:: Example

        >>> from obspy.neries import Client
        >>> c = Client(user='******')
        >>> dt = UTCDateTime("2009-04-01T00:00:00")
        >>> st = c.saveWaveform("outfile.fseed", "NL", "WIT", "", "BH*",
        ...                     dt, dt+30, format="FSEED")  #doctest: +SKIP
        """
        # enable logging if debug option is set
        if self.debug:
            import logging
            logging.basicConfig(level=logging.INFO)
            logging.getLogger('suds.client').setLevel(logging.DEBUG)
        # initialize client
        client = SudsClient(SEISMOLINK_WSDL)
        # set cache of 5 days
        cache = client.options.cache
        cache.setduration(days=5)
        # create user token
        usertoken = client.factory.create('UserTokenType')
        usertoken.email = self.user
        usertoken.password = self.password
        usertoken.label = self.user_agent.replace(' ', '_')
        usertoken.locale = ""
        # create station filter
        stationid = client.factory.create('StationIdentifierType')
        stationid.NetworkCode = network
        stationid.StationCode = station
        stationid.ChannelCode = channel
        stationid.LocId = location
        # adding default record length (4096) * delta to start and end time to
        # ensure right date times
        # XXX: 4096 may be overkill
        delta = guessDelta(channel) * 4096
        stationid.TimeSpan.TimePeriod.beginPosition = \
            (UTCDateTime(starttime) - delta).strftime("%Y-%m-%dT%H:%M:%S")
        stationid.TimeSpan.TimePeriod.endPosition = \
            (UTCDateTime(endtime) + delta).strftime("%Y-%m-%dT%H:%M:%S")
        # request data
        if format == 'MSEED':
            client.options.plugins = \
                [_AttributePlugin({'DataFormat': 'MSEED'})]
        # start data request
        response = client.service.dataRequest(usertoken, stationid)
        client.options.plugins = []
        # filter for request ids
        request_ids = [r._Id for r in response.RoutedRequest]
        if not request_ids:
            return
        # check status using request ids
        _loops = 0
        while True:
            response = client.service.checkStatus(usertoken, request_ids)
            status = [r.ReadyFlag for r in response.RoutedRequest]
            # if we hit MAX_REQUESTS break the loop
            if _loops > MAX_REQUESTS:
                msg = 'MAX_REQUESTS exceeded - breaking current request loop'
                warnings.warn(msg, UserWarning)
                break
            if "false" in status:
                # retry until all are set to 'true'
                _loops += 1
                continue
            break
        # keep only request ids which are fulfilled and have 'status = OK'
        request_ids = [
            r._Id for r in response.RoutedRequest
            if 'Status: OK' in r.StatusDescription and r.Fulfillment == 100
        ]
        if not request_ids:
            return
        # retrieve download URLs using request ids
        response = client.service.dataRetrieve(usertoken, request_ids)
        urls = [r.DownloadToken.DownloadURL for r in response.DataItem]
        # create file handler if a file name is given
        if isinstance(filename, basestring):
            fh = open(filename, "wb")
        elif isinstance(filename, file):
            fh = filename
        else:
            msg = "Parameter filename must be either string or file handler."
            raise TypeError(msg)
        for url in urls:
            fh.write(urllib2.urlopen(url).read())
        if isinstance(filename, basestring):
            fh.close()
        # clean up
        response = client.service.purgeData(usertoken, request_ids)
예제 #23
0
 def post(self):
     ret = {'status': 1, 'message': ''}
     try:
         # 提取post参数中name=file的文件元数据
         if self.request.files.has_key('file'):
             #
             try:
                 soapCli = SudsClient(Conf.YGYS['soapuri'],
                                      timeout=Conf.YGYS['timeout'])
             except BaseException as e:
                 logger.error(e)
                 ret['message'] = u'无法连接简历解析WebService服务'
                 return
             #
             try:
                 sitecode = self.get_argument('sitefromcode', '0')
                 maildate = self.get_argument('maildate', '')
                 filedata = self.request.files['file'][0]
                 filename = filedata['filename']
                 logger.info(u'解析简历文件<{}>'.format(filename))
                 # 文件扩展名
                 ext = os.path.splitext(filename)[-1]
                 if not ext: ext = '.text'
                 res = soapCli.service.TransResumeByJsonStringForFileBase64(
                     Conf.YGYS['username'], Conf.YGYS['password'],
                     base64.b64encode(filedata['body']), ext)
                 if res:
                     js = json.loads(res)
                     if js['Type'] == 0:
                         ret['message'] = js['Name']
                     elif not js['Name']:
                         ret['message'] = u'非完整简历'
                     else:
                         js['companyid'] = 0
                         js['jobid'] = 0
                         js['source'] = 0
                         js['apply_job_id'] = 0
                         js['siteid'] = sitecode
                         js['apply_time'] = maildate
                         js['websiteresumeid'] = js['WebSiteResumeID']
                         js['matching'] = 0
                         (res, message, new) = AssembelResumeByJson(js)
                         if res:
                             data = ResumeBase.queryAndExportByResumeCode(
                                 message)
                             ret['status'] = 0
                             ret['count'] = 1
                             ret['message'] = u'简历文件解析成功!'
                             ret['res_resume_base'] = data
                         else:
                             ret['message'] = message
                 else:
                     ret['message'] = u'解析结果空白!'
             except BaseException as e:
                 logger.error(e)
                 ret['message'] = u'简历解析内部服务错误!'
         else:
             ret['message'] = u'未上传需要解析的简历文件!'
     finally:
         if ret['status'] == 1:
             logger.error(ret['message'])
         self.write(json.dumps(ret))
예제 #24
0
    def getInventory(self,
                     network,
                     station='*',
                     location='*',
                     channel='*',
                     starttime=UTCDateTime(),
                     endtime=UTCDateTime(),
                     instruments=True,
                     min_latitude=-90,
                     max_latitude=90,
                     min_longitude=-180,
                     max_longitude=180,
                     modified_after=None,
                     format='SUDS'):
        """
        Returns information about the available networks and stations in that
        particular space/time region.

        :type network: str
        :param network: Network code, e.g. ``'BW'``.
        :type station: str
        :param station: Station code, e.g. ``'MANZ'``. Station code may contain
            wild cards.
        :type location: str
        :param location: Location code, e.g. ``'01'``. Location code may
            contain wild cards.
        :type channel: str
        :param channel: Channel code, e.g. ``'EHE'``. Channel code may contain
            wild cards.
        :type starttime: :class:`~obspy.core.utcdatetime.UTCDateTime`
        :param starttime: Start date and time.
        :type endtime: :class:`~obspy.core.utcdatetime.UTCDateTime`
        :param endtime: End date and time.
        :type instruments: boolean, optional
        :param instruments: Include instrument data. Default is ``True``.
        :type min_latitude: float, optional
        :param min_latitude: Minimum latitude, defaults to ``-90.0``
        :type max_latitude: float, optional
        :param max_latitude: Maximum latitude, defaults to ``90.0``
        :type min_longitude: float, optional
        :param min_longitude: Minimum longitude, defaults to ``-180.0``
        :type max_longitude: float, optional
        :param max_longitude: Maximum longitude, defaults to ``180.0``.
        :type modified_after: :class:`~obspy.core.utcdatetime.UTCDateTime`,
            optional
        :param modified_after: Returns only data modified after given date.
            Default is ``None``, returning all available data.
        :type format: ``'XML'`` or ``'SUDS'``, optional
        :param format: Output format. Either returns a XML document or a
            parsed SUDS object. Defaults to ``SUDS``.
        :return: XML document or a parsed SUDS object containing inventory
            information.

        .. rubric:: Example

        >>> from obspy.neries import Client
        >>> from obspy import UTCDateTime
        >>> client = Client(user='******')
        >>> dt = UTCDateTime("2011-01-01T00:00:00")
        >>> result = client.getInventory('GE', 'SNAA', '', 'BHZ', dt, dt+10,
        ...                              instruments=True)
        >>> paz = result.ArclinkInventory.inventory.responsePAZ
        >>> print(paz.poles)  # doctest: +ELLIPSIS
        (-0.037004,0.037016) (-0.037004,-0.037016) (-251.33,0.0) ...
        """
        # enable logging if debug option is set
        if self.debug:
            import logging
            logging.basicConfig(level=logging.INFO)
            logging.getLogger('suds.client').setLevel(logging.DEBUG)
        # initialize client
        client = SudsClient(SEISMOLINK_WSDL, retxml=(format == 'XML'))
        # set prefixes for easier debugging
        client.add_prefix('gml', 'http://www.opengis.net/gml')
        client.add_prefix('ogc', 'http://www.opengis.net/ogc')
        client.add_prefix('xlin', 'http://www.w3.org/1999/xlink')
        client.add_prefix('urn', 'urn:xml:seisml:orfeus:neries:org')
        # set cache of 5 days
        cache = client.options.cache
        cache.setduration(days=5)
        # create user token
        usertoken = client.factory.create('UserTokenType')
        usertoken.email = self.user
        usertoken.password = self.password
        usertoken.label = self.user_agent.replace(' ', '_')
        usertoken.locale = ""
        # create station filter
        stationid = client.factory.create('StationIdentifierType')
        stationid.NetworkCode = network
        stationid.StationCode = station
        stationid.ChannelCode = channel
        stationid.LocId = location
        stationid.TimeSpan.TimePeriod.beginPosition = \
            UTCDateTime(starttime).strftime("%Y-%m-%dT%H:%M:%S")
        stationid.TimeSpan.TimePeriod.endPosition = \
            UTCDateTime(endtime).strftime("%Y-%m-%dT%H:%M:%S")
        # create spatial filters
        spatialbounds = client.factory.create('SpatialBoundsType')
        spatialbounds.BoundingBox.PropertyName = "e gero"
        spatialbounds.BoundingBox.Envelope.lowerCorner = "%f %f" %\
            (min(min_latitude, max_latitude),
             min(min_longitude, max_longitude))
        spatialbounds.BoundingBox.Envelope.upperCorner = "%f %f" %\
            (max(min_latitude, max_latitude),
             max(min_longitude, max_longitude))
        # instruments attribute
        if instruments:
            client.options.plugins.append(
                _AttributePlugin({'Instruments': 'true'}))
        else:
            client.options.plugins.append(
                _AttributePlugin({'Instruments': 'false'}))
        # modified_after attribute
        if modified_after:
            dt = UTCDateTime(modified_after).strftime("%Y-%m-%dT%H:%M:%S")
            client.options.plugins.append(
                _AttributePlugin({'ModifiedAfter': dt}))
        # add version attribute needed for instruments
        client.options.plugins.append(_AttributePlugin({'Version': '1.0'}))
        # request data
        response = client.service.getInventory(usertoken, stationid,
                                               spatialbounds)
        if format == 'XML':
            # response is a full SOAP response
            from xml.etree.ElementTree import fromstring, tostring
            temp = fromstring(response)
            xpath = '*/*/{urn:xml:seisml:orfeus:neries:org}ArclinkInventory'
            inventory = temp.find(xpath)
            # export XML prepending a XML declaration
            XML_DECLARATION = "<?xml version='1.0' encoding='UTF-8'?>\n\n"
            return XML_DECLARATION + tostring(inventory, encoding='utf-8')
        else:
            # response is a SUDS object
            return response
예제 #25
0
    def getTravelTimes(self,
                       latitude,
                       longitude,
                       depth,
                       locations=[],
                       model='iasp91'):
        """
        Returns travel times for specified station-event geometry using
        standard velocity models such as ``iasp91``, ``ak135`` or ``qdt``.

        :type latitude: float
        :param latitude: Event latitude.
        :type longitude: float
        :param longitude: Event longitude.
        :type depth: float
        :param depth: Event depth in km.
        :type locations: list of tuples
        :param locations: Each tuple contains a pair of (latitude, longitude)
            of a station.
        :type model: ``'iasp91'``, ``'ak135'``, or ``'qdt'``, optional
        :param model: Velocity model, defaults to 'iasp91'.
        :return: List of dicts containing phase name and arrival times in ms.

        .. seealso:: http://www.orfeus-eu.org/wsdl/taup/taup.wsdl

        .. rubric:: Example

        >>> client = Client()
        >>> locations = [(48.0, 12.0), (48.1, 12.0)]
        >>> result = client.getTravelTimes(latitude=20.0, longitude=20.0,
        ...                                depth=10.0, locations=locations,
        ...                                model='iasp91')
        >>> len(result)
        2
        >>> result[0]  # doctest: +SKIP
        {'P': 356981.13561726053, 'S': 646841.5619481194}
        """
        # enable logging if debug option is set
        if self.debug:
            import logging
            logging.basicConfig(level=logging.INFO)
            logging.getLogger('suds.client').setLevel(logging.DEBUG)
        # initialize client
        client = SudsClient(TAUP_WSDL)
        # set cache of 5 days
        cache = client.options.cache
        cache.setduration(days=5)
        # create request
        request = []
        for location in locations:
            req = {
                'event-depth': float(depth),
                'event-lat': float(latitude),
                'event-lon': float(longitude),
                'model': str(model),
                'point-lat': float(location[0]),
                'point-lon': float(location[1])
            }
            request.append(req)
        data = client.service.getArrivalTimes(request)
        result = []
        for item in data:
            times = {}
            if hasattr(item, 'arrival-time'):
                for time in item['arrival-time']:
                    times[str(time._phase)] = float(time['_time-ms'])
            result.append(times)
        return result
예제 #26
0
 def __init__(self, user_id, password, wsdl_url=None):
     wsdl_url = wsdl_url or self.WSDL_URL
     self.user_id = user_id
     self.password = password
     self.soap = SudsClient(wsdl_url)
예제 #27
0
    def ws_client(self):
        if not hasattr(self, '_ws_client'):
            self._ws_client = SudsClient(WSDL_URL)

        return self._ws_client
예제 #28
0
 def __init__(self):
     self.soap = SudsClient(URL)  #immediately opens up a connection.
     self.raise_exceptions = settings.CLEVERREACH.get(
         'raise_exceptions', True)