def __init__(self, headers=None, config=None, path=None):
        """Inits DfaClient.

    Args:
      [optional]
      headers: dict Object with populated authentication credentials.
      config: dict Object with client configuration values.
      path: str Relative or absolute path to home directory (i.e. location of
            pickles and logs/).

    Example:
      headers = {
        'Username': '******',
        'Password': '******',
        'AuthToken': '...'
      }
      config = {
        'home': '/path/to/home',
        'log_home': '/path/to/logs/home',
        'xml_parser': '1', # PYXML = 1, ELEMENTREE = 2
        'debug': 'n',
        'raw_debug': 'n',
        'xml_log': 'y',
        'request_log': 'y',
        'raw_response': 'n',
        'strict': 'y',
        'pretty_xml': 'y',
        'compress': 'y',
      }
      path = '/path/to/home'
    """
        super(DfaClient, self).__init__(headers, config, path)

        self.__lock = threading.RLock()
        self.__loc = None

        if path is not None:
            # Update absolute path for a given instance of DfaClient, based on
            # provided relative path.
            if os.path.isabs(path):
                DfaClient.home = path
            else:
                # NOTE(api.sgrinberg): Keep first parameter of join() as os.getcwd(),
                # do not change it to DfaClient.home. Otherwise, may break when
                # multiple instances of DfaClient exist during program run.
                DfaClient.home = os.path.join(os.getcwd(), path)

            # If pickles don't exist at given location, default to "~".
            if (not headers and not config
                    and (not os.path.exists(
                        os.path.join(DfaClient.home, DfaClient.auth_pkl_name))
                         or not os.path.exists(
                             os.path.join(DfaClient.home,
                                          DfaClient.config_pkl_name)))):
                DfaClient.home = os.path.expanduser('~')
        elif not headers:
            DfaClient.home = os.path.expanduser('~')

        # Update location for both pickles.
        DfaClient.auth_pkl = os.path.join(DfaClient.home,
                                          DfaClient.auth_pkl_name)
        DfaClient.config_pkl = os.path.join(DfaClient.home,
                                            DfaClient.config_pkl_name)

        # Only load from the pickle if config wasn't specified.
        self._config = config or self.__LoadConfigValues()
        self._config = self.__SetMissingDefaultConfigValues(self._config)
        self._config['home'] = DfaClient.home

        # Validate XML parser to use.
        SanityCheck.ValidateConfigXmlParser(self._config['xml_parser'])

        # Only load from the pickle if 'headers' wasn't specified.
        if headers is None:
            self._headers = self.__LoadAuthCredentials()
        else:
            # Pass app_name from config as appName to headers if still present
            if self._config.get('app_name', None):
                headers['appName'] = self._config['app_name']

            if Utils.BoolTypeConvert(self._config['strict']):
                SanityCheck.ValidateRequiredHeaders(headers,
                                                    REQUIRED_SOAP_HEADERS)
            self._headers = headers

        # Initialize logger.
        self.__logger = Logger(LIB_SIG, self._config['log_home'])
  def __init__(self, headers=None, config=None, path=None):
    """Inits Client.

    Args:
      [optional]
      headers: dict Object with populated authentication credentials.
      config: dict Object with client configuration values.
      path: str Relative or absolute path to home directory (i.e. location of
            pickles and logs/).

    Example:
      headers = {
        'email': '*****@*****.**',
        'password': '******',
        'authToken': '...',
        'applicationName': 'GoogleTest',
        'networkCode': 'ca-01234567',
        'oauth2credentials': 'See use_oauth2.py'
      }
      config = {
        'home': '/path/to/home',
        'log_home': '/path/to/logs/home',
        'proxy': 'http://example.com:8080',
        'xml_parser': '1', # PYXML = 1, ELEMENTREE = 2
        'debug': 'n',
        'raw_debug': 'n',
        'xml_log': 'y',
        'request_log': 'y',
        'raw_response': 'n',
        'strict': 'y',
        'pretty_xml': 'y',
        'compress': 'y',
        'access': ''
      }
      path = '/path/to/home'
    """
    super(DfpClient, self).__init__(headers, config, path)

    self.__lock = thread.allocate_lock()
    self.__loc = None

    if path is not None:
      # Update absolute path for a given instance of DfpClient, based on
      # provided relative path.
      if os.path.isabs(path):
        DfpClient.home = path
      else:
        # NOTE(api.sgrinberg): Keep first parameter of join() as os.getcwd(),
        # do not change it to DfpClient.home. Otherwise, may break when
        # multiple instances of DfpClient exist during program run.
        DfpClient.home = os.path.join(os.getcwd(), path)

      # If pickles don't exist at given location, default to "~".
      if (not headers and not config and
          (not os.path.exists(os.path.join(DfpClient.home,
                                           DfpClient.auth_pkl_name)) or
           not os.path.exists(os.path.join(DfpClient.home,
                                           DfpClient.config_pkl_name)))):
        DfpClient.home = os.path.expanduser('~')
    elif not headers:
      DfpClient.home = os.path.expanduser('~')

    # Update location for both pickles.
    DfpClient.auth_pkl = os.path.join(DfpClient.home,
                                      DfpClient.auth_pkl_name)
    DfpClient.config_pkl = os.path.join(DfpClient.home,
                                        DfpClient.config_pkl_name)

    # Only load from the pickle if config wasn't specified.
    self._config = config or self.__LoadConfigValues()
    self._config = self.__SetMissingDefaultConfigValues(self._config)
    self._config['home'] = DfpClient.home

    # Validate XML parser to use.
    SanityCheck.ValidateConfigXmlParser(self._config['xml_parser'])

    # Only load from the pickle if 'headers' wasn't specified.
    if headers is None:
      self._headers = self.__LoadAuthCredentials()
    else:
      if Utils.BoolTypeConvert(self._config['strict']):
        SanityCheck.ValidateRequiredHeaders(headers, REQUIRED_SOAP_HEADERS)
      self._headers = headers

    # Load/set authentication token.
    try:
      if headers and 'authToken' in headers and headers['authToken']:
        self._headers['authToken'] = headers['authToken']
      elif 'email' in self._headers and 'password' in self._headers:
        self._headers['authToken'] = Utils.GetAuthToken(
            self._headers['email'], self._headers['password'],
            AUTH_TOKEN_SERVICE, LIB_SIG, self._config['proxy'])
      elif (self._headers.get('oauth2credentials')):
        # If they have oauth2credentials, that's also fine.
        pass
      else:
        msg = ('Authentication data, email or/and password, OAuth2 credentials '
               'is missing.')
        raise ValidationError(msg)
      self._config['auth_token_epoch'] = time.time()
    except AuthTokenError:
      # We would end up here if non-valid Google Account's credentials were
      # specified.
      self._headers['authToken'] = None
      self._config['auth_token_epoch'] = 0

    # Initialize logger.
    self.__logger = Logger(LIB_SIG, self._config['log_home'])
Exemple #3
0
    elif source == 'config':
        # Prompt user to update configuration values.
        if header == 'soap_lib' or header == 'xml_parser':
            res = raw_input('%s: ' % prompt_msg).rstrip('\r')
            if not SanityCheck.IsConfigUserInputValid(res, ['1', '2']):
                msg = 'Possible values are \'1\' or \'2\'.'
                raise InvalidInputError(msg)
        else:
            res = raw_input('%s [y/n]: ' % prompt_msg).rstrip('\r')
            if not SanityCheck.IsConfigUserInputValid(res, ['y', 'n']):
                msg = 'Possible values are \'y\' or \'n\'.'
                raise InvalidInputError(msg)
        config[header] = res

# Raise an exception, if required headers are missing.
SanityCheck.ValidateRequiredHeaders(auth, REQUIRED_SOAP_HEADERS)
if not AdWordsSanityCheck.IsClientIdSet(auth['clientEmail'],
                                        auth['clientCustomerId']):
    msg = 'Set either clientEmail or clientCustomerId, but not both.'
    raise InvalidInputError(msg)

# Load new authentication credentials into adwords_api_auth.pkl.
try:
    fh = open(AUTH_PKL, 'w')
    try:
        pickle.dump(auth, fh)
    finally:
        fh.close()
except IOError, e:
    logger.Log(LOG_NAME, e, log_level=Logger.ERROR)