def fetchServicesData():
        try:
            while True:
                global serviceDictionary,lock
                global webServerUrls,loadBalancerServerURL
                lock.acquire()
                serviceDictionary = {}
                urlArray = webServerUrls
                for url in urlArray:
                    try:
                        client = Client(url,cache = NoCache(),timeout=30)
                        key = url.split('?')[0]
                        serviceDictionary.update({key:[]})
                        for method in client.wsdl.services[0].ports[0].methods.values():    
                            serviceDictionary[key].append(method.name)
                    except Exception as e:
                        if hasattr(e,'reason') and e.reason.message == 'timed out':
                            webServerUrls.remove(url)
                        elif hasattr(e,'reason') and (e.reason.errno == 111 or e.reason.errno == 10061):
                            webServerUrls.remove(url)
                        continue

                for loadurl in loadBalancerServerURL:
                    try:
                        client = Client(loadurl,cache = NoCache(),timeout=30)
                    except Exception as e:
                        if hasattr(e,'reason') and e.reason.message == 'timed out':
                            loadBalancerServerURL.remove(loadurl)
                        elif hasattr(e,'reason') and (e.reason.errno == 111 or e.reason.errno == 10061):
                            loadBalancerServerURL.remove(loadurl)
                        continue
                lock.release()
                time.sleep(5)
        except Exception as identifier:
            pass
예제 #2
0
    def __init__(self,
                 xaddr,
                 user,
                 passwd,
                 url,
                 cache_location='/tmp/suds',
                 cache_duration=None,
                 encrypt=True,
                 daemon=False,
                 ws_client=None,
                 no_cache=False,
                 portType=None,
                 dt_diff=None):

        if not os.path.isfile(url):
            raise ONVIFError('%s doesn`t exist!' % url)

        if no_cache:
            cache = NoCache()
        else:
            # Create cache object
            # NOTE: if cache_location is specified,
            # onvif must has the permission to access it.
            cache = ObjectCache(location=cache_location)
            # cache_duration: cache will expire in `cache_duration` days
            if cache_duration is not None:
                cache.setduration(days=cache_duration)

        # Convert pathname to url
        self.url = urlparse.urljoin('file:', urllib.pathname2url(url))
        self.xaddr = xaddr
        # Create soap client
        if not ws_client:
            self.ws_client = Client(
                url=self.url,
                location=self.xaddr,
                cache=cache,
                port=portType,
                headers={'Content-Type': 'application/soap+xml'})
        else:
            self.ws_client = ws_client
            self.ws_client.set_options(location=self.xaddr)

        # Set soap header for authentication
        self.user = user
        self.passwd = passwd
        # Indicate wether password digest is needed
        self.encrypt = encrypt

        self.daemon = daemon

        self.dt_diff = dt_diff

        if self.user is not None and self.passwd is not None:
            self.set_wsse()

        # Method to create type instance of service method defined in WSDL
        self.create_type = self.ws_client.factory.create
예제 #3
0
 def _get_siif(self,
               retornaXML=False,
               unverified_context=False,
               check_wsdl=False):
     """
     Establece la conexión con el WS y crea el objeto SOAP cliente de dicha conexión.
     """
     if not check_wsdl:  #Web
         self.local_wsdl = False
         # Obtener la URL de parámetros del sistema
         url_siif = self.env['ir.config_parameter'].get_param(
             'url_ws.siif', '')
         if not url_siif or url_siif == '0':
             _logger.info(
                 'Servicio Web SIIF: No se pudo conectar con el servicio.')
             return False, 'Error!\n %s' % (
                 'No se encuentra configurada la ruta del WSDL para consumir los servicios SIIF',
             )
         # Establecer la conexión
         try:
             return True, Client(url_siif,
                                 cache=NoCache(),
                                 retxml=retornaXML)
         except Exception as e:
             return False, 'Error!\n %s' % (
                 'Ha ocurrido un error en la comunicación web con SIIF', )
     else:
         self.local_wsdl = True
         try:
             sys.stdout = codecs.getwriter(locale.getpreferredencoding())(
                 sys.stdout)
             path_file = os.path.dirname(os.path.abspath(__file__))
             ultima_barra = path_file.rfind('/')
             path_new = path_file[:ultima_barra]
             if unverified_context:
                 try:
                     _create_unverified_https_context = ssl._create_unverified_context
                 except AttributeError:
                     # Legacy Python that doesn't verify HTTPS certificates by default
                     pass
                 else:
                     # Handle target environment that doesn't support HTTPS verification
                     ssl._create_default_https_context = _create_unverified_https_context
             # Construcción del objeto clente SOAP
             url = 'file://' + path_new + '/CGNSiiF.wsdl'
             return True, Client(url,
                                 plugins=[LogPlugin()],
                                 cache=NoCache(),
                                 retxml=retornaXML)
         except Exception as e:
             return False, 'Error!\n %s' % (
                 u'Ha ocurrido un error en la comunicación local con SIIF',
             )
예제 #4
0
    def __init__(self, xaddr, user, passwd, url,
                 cache_location='/tmp/suds', cache_duration=None,
                 encrypt=True, daemon=False, ws_client=None, no_cache=False, portType=None, dt_diff = None):

        if not os.path.isfile(url):
            raise ONVIFError('%s doesn`t exist!' % url)

        if no_cache:
            cache = NoCache()
        else:
            # Create cache object
            # NOTE: if cache_location is specified,
            # onvif must has the permission to access it.
            cache = ObjectCache(location=cache_location)
            # cache_duration: cache will expire in `cache_duration` days
            if cache_duration is not None:
                cache.setduration(days=cache_duration)


        # Convert pathname to url
        self.url = urlparse.urljoin('file:', urllib.pathname2url(url))
        self.xaddr = xaddr
        # Create soap client
        if not ws_client:
            self.ws_client = Client(url=self.url,
                                    location=self.xaddr,
                                    cache=cache,
                                    port=portType,
                                    headers={'Content-Type': 'application/soap+xml'})
        else:
            self.ws_client = ws_client
            self.ws_client.set_options(location=self.xaddr)

        # Set soap header for authentication
        self.user = user
        self.passwd = passwd
        # Indicate wether password digest is needed
        self.encrypt = encrypt

        self.daemon = daemon

        self.dt_diff = dt_diff

        if self.user is not None and self.passwd is not None:
            self.set_wsse()

        # Method to create type instance of service method defined in WSDL
        self.create_type = self.ws_client.factory.create
예제 #5
0
 def __init__(self, **kwargs):
     domain = __name__
     definitions = [
         Definition('cache', Cache, NoCache()),
         Definition('faults', bool, True),
         Definition('transport', suds.transport.options.Options,
                    suds.transport.options.Options()),
         Definition('service', (int, basestring), None),
         Definition('port', (int, basestring), None),
         Definition('location', basestring, None),
         Definition('soapheaders', (), ()),
         Definition('wsse', suds.wsse.options.Options,
                    suds.wsse.options.Options()),
         Definition('doctor', Doctor, None),
         Definition('wsaddr', bool, False),
         Definition('xstq', bool, True),
         Definition('prefixes', bool, True),
         Definition('retxml', bool, False),
         Definition('prettyxml', bool, False),
         Definition('autoblend', bool, False),
         Definition('cachingpolicy', int, 0),
         Definition('plugins', (list, tuple), []),
         Definition('nosend', bool, False),
         Definition('enforcepolicy', bool, True),
     ]
     Skin.__init__(self, Properties(domain, definitions, kwargs))
예제 #6
0
    def _setup(self):
        plugings = []
        cache_conf = NoCache()
        if Configuration.debug:
            if Configuration.log_file is not None:
                logging.basicConfig(filename=Configuration.log_file, level=Configuration.log_level,
                                    format=utils.get_log_format())
            else:
                logging.basicConfig(level=Configuration.log_level,
                                    format=utils.get_log_format())

            if Configuration.log_level == logging.DEBUG and Configuration.environment ==  constants.PRODUCTION_ENV:
                raise LogException

            plugings.append(LogPlugin())


        s = requests.Session()
        s.mount('file://', FileAdapter())
        if Configuration.proxy_url:
            s.proxies = utils.get_builded_proxy_url(Configuration.proxy_url, Configuration.proxy_port)
            if Configuration.proxy_user:
                s.auth= HTTPProxyAuth(Configuration.proxy_user, Configuration.proxy_pass)

        if Configuration.certificate and Configuration.c_key:
            s.cert=(Configuration.certificate, Configuration.c_key)
        else:
            s.verify = Configuration.certificate

        t = RequestsTransport(s, timeout=Configuration.timeout)

        if Configuration.cache:
            cache_conf = ObjectCache(location=Configuration.cache_location, seconds=Configuration.cache_duration)

        self._client = client.Client(Configuration.get_wsdl().strip(), plugins=plugings, transport=t, cache=cache_conf)
예제 #7
0
    def __init__(self,
                 oauth2_client,
                 application_name,
                 network_code=None,
                 https_proxy=None,
                 cache=NoCache()):
        """Initializes a DfpClient.

    For more information on these arguments, see our SOAP headers guide:
    https://developers.google.com/doubleclick-publishers/docs/soap_xml

    Args:
      oauth2_client: A googleads.oauth2.GoogleOAuth2Client used to authorize
          your requests.
      application_name: An arbitrary string which will be used to identify your
          application
      [optional]
      network_code: A string identifying the network code of the network you are
          accessing. All requests other than getAllNetworks and getCurrentUser
          calls require this header to be set.
      https_proxy: A string identifying the URL of a proxy that all HTTPS
          requests should be routed through.
      cache: A subclass of suds.cache.Cache that defaults to NoCache.
    """
        self.oauth2_client = oauth2_client
        self.application_name = application_name
        self.network_code = network_code
        self.https_proxy = https_proxy
        self.cache = cache
        self._header_handler = _DfpHeaderHandler(self)
예제 #8
0
    def getSessionId(self, client, serviceUrl):
        try:
            #proxy_settings = dict(http='http://localhost:8081')
            #clientSDK = Client(serviceUrl + "?wsdl", cache=NoCache(), timeout=1200, proxy=proxy_settings)
            clientSDK = Client(serviceUrl + "?wsdl",
                               timeout=1200,
                               cache=NoCache())

            CxLogin = clientSDK.factory.create("Credentials")
            CxLogin.User = self.USERNAME
            CxLogin.Pass = self.PASSWORD

            cxSDK = clientSDK.service.Login(CxLogin, 1033)

            if not cxSDK.IsSuccesfull:
                raise Exception("Unable to Login > %s" % cxSDK.ErrorMessage)

            if self.DEBUG:
                print "Service Object:", dir(client)
                print "Login Object:", dir(cxSDK)
                print "Session ID:", cxSDK.SessionId

            return (cxSDK.SessionId, clientSDK)
        except Exception as e:
            raise Exception("Unable to get SessionId from [%s] : %s" %
                            (serviceUrl, e.message))
예제 #9
0
    def request(self, start_date, end_date):
        imp = Import('http://theaffiliategateway.com/data/schemas')
        client = Client(self.url, doctor=ImportDoctor(imp), cache=NoCache())

        authentication = client.factory.create('AuthenticationType')
        authentication.username = self.username
        authentication.apikey = self.password

        criteria = client.factory.create('CriteriaType')

        criteria.StartDateTime = start_date.isoformat() + ' 00:00:00'
        criteria.EndDateTime = end_date.isoformat() + ' ' + '00:00:00'

        result = client.service.GetSalesData(authentication, criteria)

        data = []
        if result.Transactions:
            for transaction in result.Transactions.Transaction:
                entry = dict()
                for field in transaction:
                    entry[field[0]] = field[1]
                data.append(entry)

        output = pandas.DataFrame()
        if len(data) > 0:
            output = output.append(data, ignore_index=True)
            output = output.rename(columns=lambda x: 'ag:' + x)

        return output
예제 #10
0
 def __init__(self, **kwargs):
     domain = __name__
     definitions = [
         Definition('cache', Cache, NoCache()),
         Definition('documentStore', DocumentStore, defaultDocumentStore),
         Definition('extraArgumentErrors', bool, True),
         Definition('allowUnknownMessageParts', bool, False),
         Definition('faults', bool, True),
         Definition('transport', Transport, None, TpLinker()),
         Definition('service', (int, basestring), None),
         Definition('port', (int, basestring), None),
         Definition('location', basestring, None),
         Definition('soapheaders', (), ()),
         Definition('wsse', Security, None),
         Definition('doctor', Doctor, None),
         Definition('xstq', bool, True),
         Definition('prefixes', bool, True),
         Definition('retxml', bool, False),
         Definition('prettyxml', bool, False),
         Definition('autoblend', bool, False),
         Definition('cachingpolicy', int, 0),
         Definition('plugins', (list, tuple), []),
         Definition('nosend', bool, False),
         Definition('unwrap', bool, True),
         Definition('sortNamespaces', bool, True)
     ]
     Skin.__init__(self, domain, definitions, kwargs)
예제 #11
0
파일: options.py 프로젝트: tefra/txsuds
    def __init__(self, **kwargs):
        domain = __name__
        default_envns = ('SOAP-ENV',
                         'http://schemas.xmlsoap.org/soap/envelope/')

        definitions = [
            Definition('cache', Cache, NoCache()),
            Definition('faults', bool, True),
            Definition('transport', Transport, None, TpLinker()),
            Definition('service', (int, basestring), None),
            Definition('port', (int, basestring), None),
            Definition('location', basestring, None),
            Definition('envns', tuple, default_envns),
            Definition('soapheaders', (), ()),
            Definition('wsse', Security, None),
            Definition('doctor', Doctor, None),
            Definition('xstq', bool, True),
            Definition('prefixes', bool, True),
            Definition('retxml', bool, False),
            Definition('prettyxml', bool, False),
            Definition('autoblend', bool, False),
            Definition('cachingpolicy', int, 0),
            Definition('plugins', (list, tuple), []),
            Definition('nosend', bool, False),
        ]
        Skin.__init__(self, domain, definitions, kwargs)
예제 #12
0
    def __init__(self,
                 username,
                 oauth2_client,
                 application_name,
                 https_proxy=None,
                 cache=NoCache()):
        """Initializes a DfaClient.

    For more information on these arguments, see our SOAP headers guide:
    https://developers.google.com/doubleclick-advertisers/docs/SOAP_headers

    Args:
      username: A string representation of your DFA username. This is likely not
          the same as your Google Account name.
      oauth2_client: A googleads.oauth2.GoogleOAuth2Client used to authorize
          your requests.
      application_name: An arbitrary string which will be used to identify your
          application
      [optional]
      https_proxy: A string identifying the URL of a proxy that all HTTPS
          requests should be routed through.
      cache: A subclass of suds.cache.Cache that defaults to NoCache.
    """
        self.username = username
        self.oauth2_client = oauth2_client
        self.application_name = application_name
        self.https_proxy = https_proxy
        self.cache = cache
        self._header_handler = _DfaHeaderHandler(self)
예제 #13
0
    def setUp(self):
        self.longMessage = True

        client = Client(
            '%s/medfreq/wsdl/' % self.live_server_url,
            cache=NoCache(),
        )
        self.client = client
예제 #14
0
    def _get_wslsp_obj(self, no_cache=False):
        self.ensure_one()
        client = False
        if no_cache:
            client = Client(self.url, cache=NoCache())

        ws = self._webservice_class(self, url=self.url, client=client)
        return ws
예제 #15
0
    def _get_client(self):
        """
        contacts the webservice and gets a client with suds

        :return: client object
        """
        url = 'https://bioinfoweb.sch.nhs.uk/QPulseWeb.asmx?WSDL'
        client = Client(url, cache=NoCache())
        return client
예제 #16
0
 def cache(self):
     """
     Get the cache.
     @return: The I{cache} when I{cachingpolicy} = B{1}.
     @rtype: L{Cache}
     """
     if self.options.cachingpolicy == 1:
         return self.options.cache
     return NoCache()
예제 #17
0
 def setUp(self):
   self.network_code = '12345'
   self.application_name = 'application name'
   self.oauth2_client = 'unused'
   self.https_proxy = 'myproxy.com:443'
   self.cache = NoCache()
   self.version = sorted(googleads.dfp._SERVICE_MAP.keys())[-1]
   self.dfp_client = googleads.dfp.DfpClient(
       self.oauth2_client, self.application_name, self.network_code,
       self.https_proxy, self.cache)
 def cache(self):
     """
     Get the cache.
     @return: The I{options} when I{cachingpolicy} = B{0}.
     @rtype: L{Cache}
     """
     if self.options.cachingpolicy == 0:
         return self.options.cache
     else:
         return NoCache()
예제 #19
0
 def setUp(self):
     self.username = '******'
     self.application_name = 'application name'
     self.oauth2_client = 'unused'
     self.https_proxy = 'myproxy.com:443'
     self.cache = NoCache()
     self.dfa_client = googleads.dfa.DfaClient(self.username,
                                               self.oauth2_client,
                                               self.application_name,
                                               self.https_proxy, self.cache)
예제 #20
0
파일: common.py 프로젝트: securestep9/CxPy
def get_session_id(service_url, user_name, password, lcid=2052):
    """

    Login in Checkmarx and retrieve the Session ID

    https://checkmarx.atlassian.net/wiki/display/KC/Initiating+a+Session

    The login web service parameters are as follows:
    public CxWSResponseLoginData Login(
               Credentials applicationCredentials,
               int lcid
            );

    applicationCredentials: A Credentials object, with fields:
    User: The username for login
    Pass: The password for login

    lcid: ID# of the language for web service responses.
    The current API version supports the following values:
    1033: English
    1028: Chinese Taiwan
    1041: Japanese
    2052: Chinese

    Log in Checkmarx and retrieve the session id.
    The Checkmarx server session timeout is 24 hours.

    :param service_url:
    :param user_name:
    :param password:
    :param lcid:
    :return:
    """
    try:
        client_sdk = Client(service_url + "?wsdl",
                            cache=NoCache(),
                            prettyxml=True)

        cx_login = client_sdk.factory.create("Credentials")
        cx_login.User = user_name
        cx_login.Pass = password

        cx_sdk = client_sdk.service.Login(cx_login, lcid)

        if not cx_sdk.IsSuccesfull:
            logger.error("Unable to Login > " "{}".format(cx_sdk.ErrorMessage))
            raise Exception("Unable to Login > "
                            "{}".format(cx_sdk.ErrorMessage))

        return cx_sdk.SessionId, client_sdk
    except Exception as e:
        logger.error("Unable to get SessionId from "
                     "[{}] : {} ".format(service_url, e.message))
        raise Exception("Unable to get SessionId from "
                        "[{}] : {} ".format(service_url, e.message))
예제 #21
0
 def setUp(self):
     self.cache = NoCache()
     self.dev_token = 'developers developers developers'
     self.user_agent = 'users users user'
     self.oauth2_client = 'unused'
     self.https_proxy = 'my.proxy:443'
     self.adwords_client = googleads.adwords.AdWordsClient(
         self.dev_token,
         self.oauth2_client,
         self.user_agent,
         https_proxy=self.https_proxy,
         cache=self.cache)
예제 #22
0
 def add_replica(self, replica_uri):
     logging.info('TM: add_replica() called.')
     if len(self._replicas)==0: 
         logging.debug('TM: replica added: %s', replica_uri)
         self._replicas = []
         self._replicaURIs = []
         self._replicaURIs.append(replica_uri)
         self._replicas.append(Client(replica_uri, cache=NoCache()))
     elif replica_uri not in self._replicaURIs:
         logging.debug('TM: replica added: %s', replica_uri)
         self._replicaURIs.append(replica_uri)
         self._replicas.append(replica_uri)
예제 #23
0
def send(
    intelligenceTypeId,
    iodefTypeId,
    filepath,
    account,
    pwd,
    url,
    cert_path,
    key_path,
    toUnitIds=2,
):
    try:
        client = Client(
            url=url,
            cache=NoCache(),
            transport=HTTPSClientCertTransport(
                cert=cert_path,
                key=key_path,
            ),
        )
    except Exception as e:
        logging.exception('Exception when connecting to server.')
        raise

    try:
        with open(filepath, 'rb') as f:
            doc = base64.b64encode(f.read()).decode()
    except Exception as e:
        logging.exception('Exception when reading iodef.')
        raise

    try:
        checksum = md5sum(filepath)
    except Exception as e:
        logging.exception('Exception when calculating md5sum.')
        raise

    try:
        response = client.service.uploadIodefFile(
            account=account,
            pwd=pwd,
            toUnitIds=toUnitIds,
            intelligenceTypeId=intelligenceTypeId,
            iodefTypeId=iodefTypeId,
            doc=doc,
            checksum=checksum,
        )
    except Exception as e:
        logging.exception('Exception when sending to server.')
        raise

    return response
예제 #24
0
파일: cli.py 프로젝트: gisce/gestionatr
def request_p0(url, user, password, xml_str):
    t = HttpAuthenticated(username=user, password=password)
    base64string = base64.encodestring('%s:%s' % (user, password)).replace(
        '\n', '')
    auth_header = {"Authorization": "Basic %s" % base64string}
    try:
        client = Client(url, retxml=True, transport=t, cache=NoCache())
    except urllib2.URLError as e:
        import ssl
        ssl._create_default_https_context = ssl._create_unverified_context
        client = Client(url, retxml=True, transport=t, cache=NoCache())
    client.set_options(headers=auth_header)

    # Clean XML
    xml_str = xml_str.strip()
    xml_str = xml_str.replace("'utf-8'", "'UTF-8'")
    xml_str = xml_str.replace("<?xml version='1.0' encoding='UTF-8'?>", "")
    xml_str = Raw(xml_str)
    # Send request
    res = client.service.sync(xml_str)
    try:

        def find_child(element, child_name):
            res = None
            if child_name in element.tag:
                return element
            for child in element:
                res = find_child(child, child_name)
                if res is not None:
                    break
            return res

        aux = etree.fromstring(res)
        aux_res = find_child(aux, "MensajeEnvioInformacionPS")

        res = etree.tostring(aux_res)
    except Exception:
        pass
    return res
예제 #25
0
 def set_client(self, settings):
     for key in settings.iterkeys():
         setattr(self, key, settings.get(key))
     base64string = base64.encodestring(
         '%s:%s' % (self.username, self.password)).replace('\n', '')
     authenticationHeader = {
         "SOAPAction": "ActionName",
         "Authorization": "Basic %s" % base64string
     }
     t = HttpAuthenticated(username=self.username, password=self.password)
     self._client = Client(self.url,
                           headers=authenticationHeader,
                           transport=t,
                           cache=NoCache(),
                           timeout=500)
예제 #26
0
def soap_call(wsdl_url, methodname, method_args):
    """Calls a SOAP webmethod at a given URL with given arguments."""
    client = Client(wsdl_url, cache=NoCache())

    try:
        method = getattr(client.service, methodname)
    except MethodNotFound as error:
        return(error)

    try:
        response = method(*method_args)
    except WebFault as error:
        return(error)

    return response
예제 #27
0
    def _get_client(self):
        """
        contacts the webservice and gets a client with suds

        :return: client object
        """
        try:
            _create_unverified_https_context = ssl._create_unverified_context
        except AttributeError:
            pass
        else:
            ssl._create_default_https_context = _create_unverified_https_context

        url = 'https://bioinfoweb.sch.nhs.uk/UserAuthentication.asmx?WSDL'
        client = Client(url, cache=NoCache())
        return client
예제 #28
0
파일: yoksis.py 프로젝트: zetaops/ulakbus
    def connection():
        """
        Bu metod Zato suds proxy kullanimi icin patch yapilana kadar burada duracak.
        :return: suds client
        """

        # conn = self.outgoing.soap['YOKSIS Akademik Birim Agaci'].conn
        # cli = conn.client()

        from suds.client import Client
        from suds.cache import NoCache
        wsdl = 'http://servisler.yok.gov.tr/ws/UniversiteBirimlerv1?WSDL'
        proxy = {'http': 'services.konya.edu.tr:3128'}
        cli = Client(wsdl, cache=NoCache(), proxy=proxy)
        cli.set_options(faults=False)
        return cli
  def __init__(self, client_id, client_secret, refresh_token,
               manager_account_id, dev_token):
    """Initializes an APIHandler.

    Args:
      client_id: The client customer id retrieved from the Developers Console.
      client_secret: The client secret retrieved from the Developers Console.
      refresh_token: The refresh token retrieved with generate_refresh_token.py.
      manager_account_id: The AdWords manager account Id.
      dev_token: The AdWords Developer Token.
    """
    credentials = GoogleRefreshTokenClient(client_id, client_secret,
                                           refresh_token)
    self.client = AdWordsClient(dev_token, credentials, self._USER_AGENT,
                                client_customer_id=manager_account_id,
                                cache=NoCache())
예제 #30
0
def main(argv):

    #Command line arguments
    serverFile = None
    try:
        opts, args = getopt.getopt(argv, "hF:", ["serverFile="])
    except getopt.GetoptError:
        print './replica_config.py -F <serverFile>'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print './replica_config.py -F <serverFile>'
            sys.exit()
        elif opt in ("-F", "--serverFile="):
            serverFile = arg

    #Read server address file and append to list
    if serverFile is None:
        logging.error("serverFile is needed to add replicas.")
        sys.exit(1)
    sfile = None
    try:
        sfile = open(serverFile, 'r')
    except:
        logging.error("error while trying to open the serverFile")
        sys.exit(1)

    servers = []
    for line in sfile:
        addr = line.strip('\n').split(' ')
        uri = 'http://' + addr[0] + ':' + addr[
            1] + '/?wsdl'  #'http://localhost:7789/?wsdl'
        logging.info("replica uri: %s", uri)
        servers.append(uri)

    #Create a client & add replica to each server
    logging.info("Establishing connection with servers...")
    for server in servers:
        client = Client(uri, cache=NoCache(), timeout=120)
        client.service.set_server(server)
        # Add replicas
        for replica in servers:
            if replica.find(server) == -1:
                client.service.add_replica(replica)
    logging.info("Connections b/w servers is setup.")
    sys.exit(0)
예제 #31
0
 def setUp(self):
     oauth_header = {'Authorization': 'header'}
     self.cache = NoCache()
     self.client_customer_id = 'client customer id'
     self.dev_token = 'developers developers developers'
     self.user_agent = 'users users user'
     self.oauth2_client = mock.Mock()
     self.oauth2_client.CreateHttpHeader.return_value = dict(oauth_header)
     self.https_proxy = 'my.proxy:443'
     self.adwords_client = googleads.adwords.AdWordsClient(
         self.dev_token,
         self.oauth2_client,
         self.user_agent,
         client_customer_id=self.client_customer_id,
         https_proxy=self.https_proxy,
         cache=self.cache)
     self.header_handler = googleads.adwords._AdWordsHeaderHandler(
         self.adwords_client, CURRENT_VERSION)