Beispiel #1
0
    def putrequest(self,
                   method,
                   url,
                   skip_host=False,
                   skip_accept_encoding=False):
        """Send a line to the server consisting of the request string, the selector
    string, and the HTTP version.

    Args:
      method: str HTTP request method.
      url: str selector URL.
      [optional]
      skip_host: bool if True, disable automatic sending of Host header.
      skip_accept_encoding: bool if True, disable automatic sending of
                            Accept-Encoding header.
    """
        if self.__http_proxy != self.__host:
            scheme = Utils.GetSchemeFromUrl(url) or 'http'
            netloc = Utils.GetNetLocFromUrl(url) or self.__host
            path = Utils.GetPathFromUrl(url)
            uri = '%s://%s%s' % (scheme, netloc, path)
        else:
            uri = url
        httplib.HTTPConnection.putrequest(
            self,
            method=method,
            url=uri,
            skip_host=skip_host,
            skip_accept_encoding=skip_accept_encoding)
    def DownloadReport(self, report_definition_id, path=None):
        """Download report and either return raw data or save it into a file.

    Args:
      report_definition_id: str Id of the report definition to download.
      path: str Path of the file to save the report data into.

    Returns:
      str Report data, if path was not specified.
    """
        selector = '/api/adwords/reportdownload?__rd=%s' % report_definition_id
        clientId = {}
        if 'clientEmail' in self.__headers:
            clientId['clientEmail'] = self.__headers['clientEmail']
        elif 'clientCustomerId' in self.__headers:
            clientId['clientCustomerId'] = self.__headers['clientCustomerId']

        # Download report data.
        conn = httplib.HTTPSConnection(
            Utils.GetNetLocFromUrl(self.__op_config['server']))
        conn.connect()
        conn.putrequest('GET', selector)
        conn.putheader('Authorization',
                       'GoogleLogin auth=%s' % self.__headers['authToken'])
        conn.putheader(clientId.keys()[0], clientId[clientId.keys()[0]])
        conn.endheaders()
        data = conn.getresponse().read()

        if not path: return data

        # Write data to a file.
        fh = open(path, 'w')
        try:
            fh.write(data)
        finally:
            fh.close()
Beispiel #3
0
  def __ManageSoap(self, buf, start_time, stop_time, error={}):
    """Manage SOAP XML message.

    Args:
      buf: SoapBuffer SOAP buffer.
      start_time: str time before service call was invoked.
      stop_time: str time after service call was invoked.
      [optional]
      error: dict error, if any.
    """
    # Update the number of units and operations consumed by API call.
    if buf.GetCallUnits() and buf.GetCallOperations():
      self.__config['units'][0] += int(buf.GetCallUnits())
      self.__config['operations'][0] += int(buf.GetCallOperations())
      self.__config['last_units'][0] = int(buf.GetCallUnits())
      self.__config['last_operations'][0] = int(buf.GetCallOperations())

    # Load trace errors, if any.
    if error and 'trace' in error:
      error_msg = error['trace']
    else:
      error_msg = ''

    # Check if response was successful or not.
    if error and 'data' in error:
      is_fault = True
    else:
      is_fault = False

    # Forward SOAP XML, errors, and other debugging data to console, external
    # file, both, or ignore. Each handler supports the following elements,
    #   tag: Config value for this handler. If left empty, will never write
    #        data to file.
    #   target: Target/destination represented by this handler (i.e. FILE,
    #           CONSOLE, etc.). Initially, it should be set to Logger.NONE.
    #   name: Name of the log file to use.
    #   data: Data to write.
    handlers = [
        {'tag': 'xml_log',
         'target': Logger.NONE,
         'name': 'soap_xml',
         'data': str('StartTime: %s\n%s\n%s\n%s\n%s\nEndTime: %s'
                     % (start_time, buf.GetHeadersOut(), buf.GetSOAPOut(),
                        buf.GetHeadersIn(), buf.GetSOAPIn(), stop_time))},
        {'tag': 'request_log',
         'target': Logger.NONE,
         'name': 'request_info',
         'data': str('host=%s service=%s method=%s operator=%s responseTime=%s '
                     'operations=%s units=%s requestId=%s isFault=%s'
                     % (Utils.GetNetLocFromUrl(self.__url),
                        buf.GetServiceName(), buf.GetCallName(),
                        buf.GetOperatorName(), buf.GetCallResponseTime(),
                        buf.GetCallOperations(), buf.GetCallUnits(),
                        buf.GetCallRequestId(), is_fault))},
        {'tag': '',
         'target': Logger.NONE,
         'name': 'aw_api_lib',
         'data': 'DEBUG: %s' % error_msg}
    ]
    for handler in handlers:
      if (handler['tag'] and
          Utils.BoolTypeConvert(self.__config[handler['tag']])):
        handler['target'] = Logger.FILE
      # If debugging is On, raise handler's target two levels,
      #   NONE -> CONSOLE
      #   FILE -> FILE_AND_CONSOLE.
      if Utils.BoolTypeConvert(self.__config['debug']):
        handler['target'] += 2

      if (handler['target'] != Logger.NONE and handler['data'] and
          handler['data'] != 'None' and handler['data'] != 'DEBUG: '):
        self.__logger.Log(handler['name'], handler['data'],
                          log_level=Logger.DEBUG, log_handler=handler['target'])

    # If raw response is requested, no need to validate and throw appropriate
    # error. Up to the end user to handle successful or failed request.
    if Utils.BoolTypeConvert(self.__config['raw_response']):
      return

    # Report SOAP fault.
    if is_fault:
      try:
        fault = buf.GetFaultAsDict()
        if not fault:
          msg = error['data']
      except:
        fault = None
        # An error is not a SOAP fault, but check if some other error.
        if error_msg:
          msg = error_msg
        else:
          msg = ('Unable to parse incoming SOAP XML. Please, file '
                 'a bug at %s/issues/list.' % LIB_URL)
      # Release thread lock.
      if self.__lock.locked():
        self.__lock.release()
      if not fault and msg:
        raise Error(msg)

      # Raise a specific error, subclass of ApiError.
      if 'detail' in fault:
        if 'code' in fault['detail']:
          code = int(fault['detail']['code'])
          if code in ERRORS:
            raise ERRORS[code](fault)
        elif 'errors' in fault['detail']:
          type = fault['detail']['errors'][0]['type']
          if type in ERRORS:
            raise ERRORS[str(type)](fault)
      raise ApiError(fault)