def CallRawMethod(self, soap_message, url, server, http_proxy):
    """Call API method directly, using raw SOAP message.

    For API calls performed with this method, outgoing data is not run through
    library's validation logic.

    Args:
      soap_message: str SOAP XML message.
      url: str URL of the API service for the method to call.
      server: str API server to access for this API call.
      http_proxy: str HTTP proxy to use for this API call.

    Returns:
      tuple Response from the API method (SOAP XML response message).
    """
    headers = self._headers

    # Load additional configuration data.
    op_config = {
      'http_proxy': http_proxy,
      'server': server
    }

    service = DfpWebService(headers, self._config, op_config, url, self.__lock,
                            self.__logger)
    return service.CallRawMethod(soap_message)
    def testCallMethodDirect(self):
        """Test whether we can call an API method directly."""
        headers = client.GetAuthCredentials()
        config = client.GetConfigValues()
        url = '/'.join([
            DfpWebServiceTestV201004.SERVER, 'apis/ads/publisher/v201004',
            'UserService'
        ])
        op_config = {
            'server': self.__class__.SERVER,
            'version': self.__class__.VERSION,
            'http_proxy': HTTP_PROXY
        }

        lock = thread.allocate_lock()
        service = DfpWebService(headers, config, op_config, url, lock)
        method_name = 'getAllRoles'
        if config['soap_lib'] == SOAPPY:
            self.assert_(
                isinstance(service.CallMethod(method_name, (), 'UserService'),
                           tuple))
        elif config['soap_lib'] == ZSI:
            web_services = __import__(
                'adspygoogle.dfp.zsi.v201004.UserService_services', globals(),
                locals(), [''])
            loc = web_services.UserServiceLocator()
            request = eval('web_services.%sRequest()' % method_name)
            self.assert_(
                isinstance(
                    service.CallMethod(method_name, (({
                        'filterStatement': {
                            'query': 'ORDER BY name LIMIT 500'
                        }
                    }, )), 'User', loc, request), tuple))
class PublisherQueryLanguageService(ApiService):
    """Wrapper for PublisherQueryLanguageService.

  The PublisherQueryLanguage Service provides operations for executing a PQL
  statement to retrieve information from the system.
  """
    def __init__(self, headers, config, op_config, lock, logger):
        """Inits PublisherQueryLanguageService.

    Args:
      headers: dict Dictionary object with populated authentication
               credentials.
      config: dict Dictionary object with populated configuration values.
      op_config: dict Dictionary object with additional configuration values for
                 this operation.
      lock: thread.lock Thread lock
      logger: Logger Instance of Logger
    """
        url = [
            op_config['server'], 'apis/ads/publisher', op_config['version'],
            self.__class__.__name__
        ]
        self.__service = DfpWebService(headers, config, op_config,
                                       '/'.join(url), lock, logger)
        super(PublisherQueryLanguageService,
              self).__init__(headers, config, op_config, url,
                             'adspygoogle.dfp', lock, logger)

    def Select(self, select_statement):
        """Return rows of data for a given statement.

    Args:
      select_statement: dict Publisher Query Language statement used to specify
                        what data to return.

    Returns:
      tuple Response from the API method.
    """
        method_name = 'select'
        if self._config['soap_lib'] == SOAPPY:
            from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
            select_statement = self._message_handler.PackDictAsXml(
                self._sanity_check.ValidateStatement(select_statement),
                'selectStatement', OBJ_KEY_ORDER_MAP)
            return self.__service.CallMethod(method_name, (select_statement))
        elif self._config['soap_lib'] == ZSI:
            select_statement = self._sanity_check.ValidateStatement(
                select_statement, self._web_services)
            request = eval('self._web_services.%sRequest()' % method_name)
            return self.__service.CallMethod(
                method_name, (({
                    'selectStatement': select_statement
                }, )), 'PublisherQueryLanguage', self._loc, request)
Exemple #4
0
  def __init__(self, headers, config, op_config, lock, logger):
    """Inits InventoryService.

    Args:
      headers: dict Dictionary object with populated authentication
               credentials.
      config: dict Dictionary object with populated configuration values.
      op_config: dict Dictionary object with additional configuration values for
                 this operation.
      lock: thread.lock Thread lock
      logger: Logger Instance of Logger
    """
    url = [op_config['server'], 'apis/ads/publisher', op_config['version'],
           self.__class__.__name__]
    self.__service = DfpWebService(headers, config, op_config, '/'.join(url),
                                   lock, logger)
    super(InventoryService, self).__init__(
        headers, config, op_config, url, 'adspygoogle.dfp', lock, logger)
class ForecastService(ApiService):
    """Wrapper for ForecastService.

  The Forecast Service provides operations for estimating traffic
  (clicks/impressions) for line items.
  """
    def __init__(self, headers, config, op_config, lock, logger):
        """Inits ForecastService.

    Args:
      headers: dict Dictionary object with populated authentication
               credentials.
      config: dict Dictionary object with populated configuration values.
      op_config: dict Dictionary object with additional configuration values for
                 this operation.
      lock: thread.lock Thread lock
      logger: Logger Instance of Logger
    """
        url = [
            op_config['server'], 'apis/ads/publisher', op_config['version'],
            self.__class__.__name__
        ]
        self.__service = DfpWebService(headers, config, op_config,
                                       '/'.join(url), lock, logger)
        super(ForecastService, self).__init__(headers, config, op_config, url,
                                              'adspygoogle.dfp', lock, logger)

    def GetForecast(self, line_item):
        """Return a forecast on a hypothetical line item.

    Args:
      lint_item: dict Target of the forecast.

    Returns:
      tuple Response from the API method.
    """
        method_name = 'getForecast'
        if self._config['soap_lib'] == SOAPPY:
            from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
            self._sanity_check.ValidateLineItem(line_item)
            line_item = self._message_handler.PackDictAsXml(
                line_item, 'lineItem', OBJ_KEY_ORDER_MAP)
            return self.__service.CallMethod(method_name, (line_item))
        elif self._config['soap_lib'] == ZSI:
            self._sanity_check.ValidateLineItem(line_item, self._web_services)
            request = eval('self._web_services.%sRequest()' % method_name)
            return self.__service.CallMethod(method_name,
                                             (({
                                                 'lineItem': line_item
                                             }, )), 'Forecast', self._loc,
                                             request)

    def GetForecastById(self, line_item_id):
        """Return a forecast for an existing line item.

    Args:
      line_item_id: str ID of the line item to run the forecast on.

    Returns:
      tuple Response from the API method.
    """
        SanityCheck.ValidateTypes(((line_item_id, (str, unicode)), ))

        method_name = 'getForecastById'
        if self._config['soap_lib'] == SOAPPY:
            from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
            line_item_id = self._message_handler.PackDictAsXml(
                line_item_id, 'lineItemId', OBJ_KEY_ORDER_MAP)
            return self.__service.CallMethod(method_name, (line_item_id))
        elif self._config['soap_lib'] == ZSI:
            request = eval('self._web_services.%sRequest()' % method_name)
            return self.__service.CallMethod(method_name,
                                             (({
                                                 'lineItemId': line_item_id
                                             }, )), 'Forecast', self._loc,
                                             request)
class NetworkService(ApiService):
    """Wrapper for NetworkService.

  The Network Service provides operations for retrieving information related to
  the publisher's network.
  """
    def __init__(self, headers, config, op_config, lock, logger):
        """Inits NetworkService.

    Args:
      headers: dict Dictionary object with populated authentication
               credentials.
      config: dict Dictionary object with populated configuration values.
      op_config: dict Dictionary object with additional configuration values for
                 this operation.
      lock: thread.lock Thread lock
      logger: Logger Instance of Logger
    """
        url = [
            op_config['server'], 'apis/ads/publisher', op_config['version'],
            self.__class__.__name__
        ]
        self.__service = DfpWebService(headers, config, op_config,
                                       '/'.join(url), lock, logger)
        super(NetworkService, self).__init__(headers, config, op_config, url,
                                             'adspygoogle.dfp', lock, logger)

    def GetAllNetworks(self):
        """Return a list of network objects.

    Returns:
      tuple Response from the API method.
    """
        method_name = 'getAllNetworks'
        if self._config['soap_lib'] == SOAPPY:
            return self.__service.CallMethod(method_name, ())
        elif self._config['soap_lib'] == ZSI:
            request = eval('self._web_services.%sRequest()' % method_name)
            return self.__service.CallMethod(method_name, (), 'Network',
                                             self._loc, request)

    def GetCurrentNetwork(self):
        """Return the current network.

    Returns:
      tuple Response from the API method.
    """
        method_name = 'getCurrentNetwork'
        if self._config['soap_lib'] == SOAPPY:
            return self.__service.CallMethod(method_name, ())
        elif self._config['soap_lib'] == ZSI:
            request = eval('self._web_services.%sRequest()' % method_name)
            return self.__service.CallMethod(method_name, (), 'Network',
                                             self._loc, request)

    def UpdateNetwork(self, network):
        """Update the specified network.

    Args:
      network: dict Network to update.

    Returns:
      tuple Response from the API method.
    """
        self._sanity_check.ValidateNetwork(network)

        method_name = 'updateNetwork'
        if self._config['soap_lib'] == SOAPPY:
            from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
            line_item = self._message_handler.PackDictAsXml(
                network, 'network', OBJ_KEY_ORDER_MAP)
            return self.__service.CallMethod(method_name, (line_item))
        elif self._config['soap_lib'] == ZSI:
            request = eval('self._web_services.%sRequest()' % method_name)
            return self.__service.CallMethod(method_name, (({
                'network': network
            }, )), 'Network', self._loc, request)
Exemple #7
0
class InventoryService(ApiService):

  """Wrapper for InventoryService.

  The Inventory Service provides operations for creating, updating and
  retrieving ad units.
  """

  def __init__(self, headers, config, op_config, lock, logger):
    """Inits InventoryService.

    Args:
      headers: dict Dictionary object with populated authentication
               credentials.
      config: dict Dictionary object with populated configuration values.
      op_config: dict Dictionary object with additional configuration values for
                 this operation.
      lock: thread.lock Thread lock
      logger: Logger Instance of Logger
    """
    url = [op_config['server'], 'apis/ads/publisher', op_config['version'],
           self.__class__.__name__]
    self.__service = DfpWebService(headers, config, op_config, '/'.join(url),
                                   lock, logger)
    super(InventoryService, self).__init__(
        headers, config, op_config, url, 'adspygoogle.dfp', lock, logger)

  def CreateAdUnit(self, ad_unit):
    """Create a new ad unit.

    Args:
      ad_unit: dict Ad unit to create.

    Returns:
      tuple Response from the API method.
    """
    self._sanity_check.ValidateAdUnit(ad_unit)

    method_name = 'createAdUnit'
    if self._config['soap_lib'] == SOAPPY:
      from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
      ad_unit = self._message_handler.PackDictAsXml(ad_unit, 'adUnit',
          OBJ_KEY_ORDER_MAP)
      return self.__service.CallMethod(method_name, (ad_unit))
    elif self._config['soap_lib'] == ZSI:
      request = eval('self._web_services.%sRequest()' % method_name)
      return self.__service.CallMethod(method_name, (({'adUnit': ad_unit},)),
                                       'Inventory', self._loc, request)

  def CreateAdUnits(self, ad_units):
    """Create a list of new ad units.

    Args:
      ad_units: list Ad units to create.

    Returns:
      tuple Response from the API method.
    """
    SanityCheck.ValidateTypes(((ad_units, list),))
    for item in ad_units:
      self._sanity_check.ValidateAdUnit(item)

    method_name = 'createAdUnits'
    if self._config['soap_lib'] == SOAPPY:
      from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
      new_ad_units = []
      for ad_unit in ad_units:
        new_ad_units.append(self._message_handler.PackDictAsXml(
            ad_unit, 'adUnits', OBJ_KEY_ORDER_MAP))
      return self.__service.CallMethod(method_name, (''.join(new_ad_units)))
    elif self._config['soap_lib'] == ZSI:
      request = eval('self._web_services.%sRequest()' % method_name)
      return self.__service.CallMethod(method_name,
                                       (({'adUnits': ad_units},)),
                                       'Inventory', self._loc, request)

  def GetAdUnit(self, ad_unit_id):
    """Return the ad unit uniquely identified by the given id.

    Args:
      ad_unit_id: str ID of the ad unit, which must already exist.

    Returns:
      tuple Response from the API method.
    """
    SanityCheck.ValidateTypes(((ad_unit_id, (str, unicode)),))

    method_name = 'getAdUnit'
    if self._config['soap_lib'] == SOAPPY:
      from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
      ad_unit_id = self._message_handler.PackDictAsXml(
          ad_unit_id, 'adUnitId', OBJ_KEY_ORDER_MAP)
      return self.__service.CallMethod(method_name, (ad_unit_id))
    elif self._config['soap_lib'] == ZSI:
      request = eval('self._web_services.%sRequest()' % method_name)
      return self.__service.CallMethod(method_name,
                                       (({'adUnitId': ad_unit_id},)),
                                       'Inventory', self._loc, request)

  def GetAdUnitsByStatement(self, filter_statement):
    """Return the ad units that match the given statement.

    Args:
      filter_statement: dict Publisher Query Language statement used to filter a
                        set of ad units.

    Returns:
      tuple Response from the API method.
    """
    method_name = 'getAdUnitsByStatement'
    if self._config['soap_lib'] == SOAPPY:
      from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
      filter_statement = self._message_handler.PackDictAsXml(
          self._sanity_check.ValidateStatement(filter_statement),
          'filterStatement', OBJ_KEY_ORDER_MAP)
      return self.__service.CallMethod(method_name, (filter_statement))
    elif self._config['soap_lib'] == ZSI:
      filter_statement = self._sanity_check.ValidateStatement(
          filter_statement, self._web_services)
      request = eval('self._web_services.%sRequest()' % method_name)
      return self.__service.CallMethod(method_name,
          (({'filterStatement': filter_statement},)), 'Inventory', self._loc,
          request)

  def PerformAdUnitAction(self, action, filter_statement):
    """Perform action on ad units that match the given statement.

    Args:
      action: dict Action to perform.
      filter_statement: dict Publisher Query Language statement.

    Returns:
      tuple Response from the API method.
    """
    method_name = 'performAdUnitAction'
    if self._config['soap_lib'] == SOAPPY:
      from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
      self._sanity_check.ValidateAction(action)
      action = self._message_handler.PackDictAsXml(action, 'adUnitAction',
          OBJ_KEY_ORDER_MAP)
      filter_statement = self._message_handler.PackDictAsXml(
          self._sanity_check.ValidateStatement(filter_statement),
          'filterStatement', OBJ_KEY_ORDER_MAP)
      return self.__service.CallMethod(method_name,
                                       (''.join([action, filter_statement])))
    elif self._config['soap_lib'] == ZSI:
      action = self._sanity_check.ValidateAction(action, self._web_services)
      filter_statement = self._sanity_check.ValidateStatement(
          filter_statement, self._web_services)
      request = eval('self._web_services.%sRequest()' % method_name)
      return self.__service.CallMethod(method_name,
          (({'adUnitAction': action}, {'filterStatement': filter_statement})),
          'Inventory', self._loc, request)

  def UpdateAdUnit(self, ad_unit):
    """Update the specified ad unit.

    Args:
      ad_unit: dict Ad unit to update.

    Returns:
      tuple Response from the API method.
    """
    self._sanity_check.ValidateAdUnit(ad_unit)

    method_name = 'updateAdUnit'
    if self._config['soap_lib'] == SOAPPY:
      from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
      ad_unit = self._message_handler.PackDictAsXml(ad_unit, 'adUnit',
          OBJ_KEY_ORDER_MAP)
      return self.__service.CallMethod(method_name, (ad_unit))
    elif self._config['soap_lib'] == ZSI:
      request = eval('self._web_services.%sRequest()' % method_name)
      return self.__service.CallMethod(method_name, (({'adUnit': ad_unit},)),
                                       'Inventory', self._loc, request)

  def UpdateAdUnits(self, ad_units):
    """Update a list of specified ad units.

    Args:
      ad_units: list Ad units to update.

    Returns:
      tuple Response from the API method.
    """
    SanityCheck.ValidateTypes(((ad_units, list),))
    for item in ad_units:
      self._sanity_check.ValidateAdUnit(item)

    method_name = 'updateAdUnits'
    if self._config['soap_lib'] == SOAPPY:
      from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
      new_ad_units = []
      for ad_unit in ad_units:
        new_ad_units.append(self._message_handler.PackDictAsXml(
            ad_unit, 'adUnits', OBJ_KEY_ORDER_MAP))
      return self.__service.CallMethod(method_name, (''.join(new_ad_units)))
    elif self._config['soap_lib'] == ZSI:
      request = eval('self._web_services.%sRequest()' % method_name)
      return self.__service.CallMethod(method_name, (({'adUnits': ad_units},)),
                                       'Inventory', self._loc, request)
Exemple #8
0
class CustomTargetingService(ApiService):
    """Wrapper for CustomTargetingService.

  The CustomTargeting Service provides methods for creating, updating and
  retrieving custom targeting keys and values.
  """
    def __init__(self, headers, config, op_config, lock, logger):
        """Inits CustomTargetingService.

    Args:
      headers: dict Dictionary object with populated authentication
               credentials.
      config: dict Dictionary object with populated configuration values.
      op_config: Dict dictionary object with additional configuration values for
                 this operation.
      lock: thread.lock Thread lock
      logger: Logger Instance of Logger
    """
        url = [
            op_config['server'], 'apis/ads/publisher', op_config['version'],
            self.__class__.__name__
        ]
        self.__service = DfpWebService(headers, config, op_config,
                                       '/'.join(url), lock, logger)
        super(CustomTargetingService,
              self).__init__(headers, config, op_config, url,
                             'adspygoogle.dfp', lock, logger)

    def CreateCustomTargetingKeys(self, keys):
        """Create a list of new custom targeting keys.

    Args:
      keys: list Custom targeting keys to create.

    Returns:
      tuple Response from the API method.
    """
        SanityCheck.ValidateTypes(((keys, list), ))
        for item in keys:
            self._sanity_check.ValidateCustomTargetingKey(item)

        method_name = 'createCustomTargetingKeys'
        if self._config['soap_lib'] == SOAPPY:
            from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
            new_keys = []
            for key in keys:
                new_keys.append(
                    self._message_handler.PackDictAsXml(
                        key, 'keys', OBJ_KEY_ORDER_MAP))
            return self.__service.CallMethod(method_name, (''.join(new_keys)))
        elif self._config['soap_lib'] == ZSI:
            request = eval('self._web_services.%sRequest()' % method_name)
            return self.__service.CallMethod(method_name, (({
                'keys': keys
            }, )), 'CustomTargeting', self._loc, request)

    def CreateCustomTargetingValues(self, values):
        """Create a list of new custom targeting values.

    Args:
      values: list Custom targeting values to create.

    Returns:
      tuple Response from the API method.
    """
        SanityCheck.ValidateTypes(((values, list), ))
        for item in values:
            self._sanity_check.ValidateCustomTargetingValue(item)

        method_name = 'createCustomTargetingValues'
        if self._config['soap_lib'] == SOAPPY:
            from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
            new_values = []
            for value in values:
                new_values.append(
                    self._message_handler.PackDictAsXml(
                        value, 'values', OBJ_KEY_ORDER_MAP))
            return self.__service.CallMethod(method_name,
                                             (''.join(new_values)))
        elif self._config['soap_lib'] == ZSI:
            request = eval('self._web_services.%sRequest()' % method_name)
            return self.__service.CallMethod(method_name, (({
                'values': values
            }, )), 'CustomTargeting', self._loc, request)

    def GetCustomTargetingKeysByStatement(self, filter_statement):
        """Return the custom targeting keys that match the given statement.

    Args:
      filter_statement: dict Publisher Query Language statement used to filter a
                        set of custom targeting keys.

    Returns:
      tuple Response from the API method.
    """
        method_name = 'getCustomTargetingKeysByStatement'
        if self._config['soap_lib'] == SOAPPY:
            from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
            filter_statement = self._message_handler.PackDictAsXml(
                self._sanity_check.ValidateStatement(filter_statement),
                'filterStatement', OBJ_KEY_ORDER_MAP)
            return self.__service.CallMethod(method_name, (filter_statement))
        elif self._config['soap_lib'] == ZSI:
            filter_statement = self._sanity_check.ValidateStatement(
                filter_statement, self._web_services)
            request = eval('self._web_services.%sRequest()' % method_name)
            return self.__service.CallMethod(
                method_name, (({
                    'filterStatement': filter_statement
                }, )), 'CustomTargeting', self._loc, request)

    def GetCustomTargetingValuesByStatement(self, filter_statement):
        """Return the custom targeting values that match the given statement.

    Args:
      filter_statement: dict Publisher Query Language statement used to filter a
                        set of custom targeting values.

    Returns:
      tuple Response from the API method.
    """
        method_name = 'getCustomTargetingValuesByStatement'
        if self._config['soap_lib'] == SOAPPY:
            from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
            filter_statement = self._message_handler.PackDictAsXml(
                self._sanity_check.ValidateStatement(filter_statement),
                'filterStatement', OBJ_KEY_ORDER_MAP)
            return self.__service.CallMethod(method_name, (filter_statement))
        elif self._config['soap_lib'] == ZSI:
            filter_statement = self._sanity_check.ValidateStatement(
                filter_statement, self._web_services)
            request = eval('self._web_services.%sRequest()' % method_name)
            return self.__service.CallMethod(
                method_name, (({
                    'filterStatement': filter_statement
                }, )), 'CustomTargeting', self._loc, request)

    def PerformCustomTargetingKeyAction(self, action, filter_statement):
        """Perform action on custom targeting keys that match the given statement.

    Args:
      action: str Action to perform.
      filter_statement: dict Publisher Query Language statement.

    Returns:
      tuple Response from the API method.
    """
        method_name = 'performCustomTargetingKeyAction'
        if self._config['soap_lib'] == SOAPPY:
            from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
            self._sanity_check.ValidateAction(action)
            action = self._message_handler.PackDictAsXml(
                action, 'customTargetingKeyAction', OBJ_KEY_ORDER_MAP)
            filter_statement = self._message_handler.PackDictAsXml(
                self._sanity_check.ValidateStatement(filter_statement),
                'filterStatement', OBJ_KEY_ORDER_MAP)
            return self.__service.CallMethod(
                method_name, (''.join([action, filter_statement])))
        elif self._config['soap_lib'] == ZSI:
            action = self._sanity_check.ValidateAction(action,
                                                       self._web_services)
            filter_statement = self._sanity_check.ValidateStatement(
                filter_statement, self._web_services)
            request = eval('self._web_services.%sRequest()' % method_name)
            return self.__service.CallMethod(
                method_name, (({
                    'customTargetingKeyAction': action
                }, {
                    'filterStatement': filter_statement
                })), 'CustomTargeting', self._loc, request)

    def PerformCustomTargetingValueAction(self, action, filter_statement):
        """Perform action on custom targeting values that match the given statement.

    Args:
      action: str Action to perform.
      filter_statement: dict Publisher Query Language statement.

    Returns:
      tuple Response from the API method.
    """
        method_name = 'performCustomTargetingValueAction'
        if self._config['soap_lib'] == SOAPPY:
            from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
            self._sanity_check.ValidateAction(action)
            action = self._message_handler.PackDictAsXml(
                action, 'customTargetingValueAction', OBJ_KEY_ORDER_MAP)
            filter_statement = self._message_handler.PackDictAsXml(
                self._sanity_check.ValidateStatement(filter_statement),
                'filterStatement', OBJ_KEY_ORDER_MAP)
            return self.__service.CallMethod(
                method_name, (''.join([action, filter_statement])))
        elif self._config['soap_lib'] == ZSI:
            action = self._sanity_check.ValidateAction(action,
                                                       self._web_services)
            filter_statement = self._sanity_check.ValidateStatement(
                filter_statement, self._web_services)
            request = eval('self._web_services.%sRequest()' % method_name)
            return self.__service.CallMethod(
                method_name, (({
                    'customTargetingValueAction': action
                }, {
                    'filterStatement': filter_statement
                })), 'CustomTargeting', self._loc, request)

    def UpdateCustomTargetingKeys(self, keys):
        """Update a list of specified custom targeting keys.

    Args:
      keys: list Custom targeting keys to update.

    Returns:
      tuple Response from the API method.
    """
        SanityCheck.ValidateTypes(((keys, list), ))
        for item in keys:
            self._sanity_check.ValidateCustomTargetingKey(item)

        method_name = 'updateCustomTargetingKeys'
        if self._config['soap_lib'] == SOAPPY:
            from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
            new_keys = []
            for key in keys:
                new_keys.append(
                    self._message_handler.PackDictAsXml(
                        key, 'keys', OBJ_KEY_ORDER_MAP))
            return self.__service.CallMethod(method_name, (''.join(new_keys)))
        elif self._config['soap_lib'] == ZSI:
            request = eval('self._web_services.%sRequest()' % method_name)
            return self.__service.CallMethod(method_name, (({
                'keys': keys
            }, )), 'CustomTargeting', self._loc, request)

    def UpdateCustomTargetingValues(self, values):
        """Update a list of specified custom targeting values.

    Args:
      values: list Custom targeting values to update.

    Returns:
      tuple Response from the API method.
    """
        SanityCheck.ValidateTypes(((values, list), ))
        for item in values:
            self._sanity_check.ValidateCustomTargetingKey(item)

        method_name = 'updateCustomTargetingValues'
        if self._config['soap_lib'] == SOAPPY:
            from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
            new_values = []
            for value in values:
                new_values.append(
                    self._message_handler.PackDictAsXml(
                        value, 'values', OBJ_KEY_ORDER_MAP))
            return self.__service.CallMethod(method_name,
                                             (''.join(new_values)))
        elif self._config['soap_lib'] == ZSI:
            request = eval('self._web_services.%sRequest()' % method_name)
            return self.__service.CallMethod(method_name, (({
                'values': values
            }, )), 'CustomTargeting', self._loc, request)
class ReportService(ApiService):

  """Wrapper for ReportService.

  The Report Service provides operations for executing a report job and
  retrieving performance and statistics about ad campaigns, networks, inventory
  and sales.
  """

  def __init__(self, headers, config, op_config, lock, logger):
    """Inits ReportService.

    Args:
      headers: dict Dictionary object with populated authentication
               credentials.
      config: dict Dictionary object with populated configuration values.
      op_config: dict Dictionary object with additional configuration values for
                 this operation.
      lock: thread.lock Thread lock
      logger: Logger Instance of Logger
    """
    url = [op_config['server'], 'apis/ads/publisher', op_config['version'],
           self.__class__.__name__]
    self.__service = DfpWebService(headers, config, op_config, '/'.join(url),
                                   lock, logger)
    super(ReportService, self).__init__(
        headers, config, op_config, url, 'adspygoogle.dfp', lock, logger)

  def GetReportDownloadURL(self, report_job_id, export_format):
    """Return the URL at which the report file can be downloaded.

    Args:
      report_job_id: str Id of the report job.
      export_format: str Export format for the report file.

    Returns:
      tuple Response from the API method.
    """
    SanityCheck.ValidateTypes(((report_job_id, (str, unicode)),
                               (export_format, (str, unicode))))

    method_name = 'getReportDownloadURL'
    if self._config['soap_lib'] == SOAPPY:
      from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
      report_job_id = self._message_handler.PackDictAsXml(
          report_job_id, 'reportJobId', OBJ_KEY_ORDER_MAP)
      export_format = self._message_handler.PackDictAsXml(
          export_format, 'exportFormat', OBJ_KEY_ORDER_MAP)
      return self.__service.CallMethod(
          method_name, (''.join([report_job_id, export_format])))
    elif self._config['soap_lib'] == ZSI:
      request = eval('self._web_services.%sRequest()' % method_name)
      return self.__service.CallMethod(method_name,
                                       (({'reportJobId': report_job_id},
                                         {'exportFormat': export_format})),
                                       'Report', self._loc, request)

  def GetReportJob(self, report_job_id):
    """Return report job uniquely identified by the given id.

    Args:
      report_job_id: str Id of the report job.

    Returns:
      tuple Response from the API method.
    """
    SanityCheck.ValidateTypes(((report_job_id, (str, unicode)),))

    method_name = 'getReportJob'
    if self._config['soap_lib'] == SOAPPY:
      from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
      report_job_id = self._message_handler.PackDictAsXml(
          report_job_id, 'reportJobId', OBJ_KEY_ORDER_MAP)
      return self.__service.CallMethod(method_name, (report_job_id))
    elif self._config['soap_lib'] == ZSI:
      request = eval('self._web_services.%sRequest()' % method_name)
      return self.__service.CallMethod(method_name,
                                       (({'reportJobId': report_job_id},)),
                                       'Report', self._loc, request)

  def RunReportJob(self, report_job):
    """Initiate the execution of a report query on the server.

    Args:
      report_job: dict Report job to run.

    Returns:
      tuple Response from the API method.
    """
    self._sanity_check.ValidateReportJob(report_job)

    method_name = 'runReportJob'
    if self._config['soap_lib'] == SOAPPY:
      from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
      report_job = self._message_handler.PackDictAsXml(
          report_job, 'reportJob', OBJ_KEY_ORDER_MAP)
      return self.__service.CallMethod(method_name, (report_job))
    elif self._config['soap_lib'] == ZSI:
      request = eval('self._web_services.%sRequest()' % method_name)
      return self.__service.CallMethod(method_name,
                                       (({'reportJob': report_job},)),
                                      'Report', self._loc, request)

  def DownloadReport(self, report_job_id, export_format):
    """Download and return report data.

    Args:
      report_job_id: str ID of the report job.
      export_format: str Export format for the report file.

    Returns:
      str Report data or empty string if report failed.
    """
    SanityCheck.ValidateTypes(((report_job_id, (str, unicode)),))

    # Wait for report to complete.
    status = self.GetReportJob(report_job_id)[0]['reportJobStatus']
    while status != 'COMPLETED' and status != 'FAILED':
      if Utils.BoolTypeConvert(self._config['debug']):
        print 'Report job status: %s' % status
      time.sleep(30)
      status = self.GetReportJob(report_job_id)[0]['reportJobStatus']

    if status == 'FAILED':
      if Utils.BoolTypeConvert(self._config['debug']):
        print 'Report process failed'
      return ''
    else:
      if Utils.BoolTypeConvert(self._config['debug']):
        print 'Report has completed successfully'

    # Get report download URL.
    report_url = self.GetReportDownloadURL(report_job_id, export_format)[0]

    # Download report.
    data = urllib.urlopen(report_url).read()
    data = gzip.GzipFile(fileobj=StringIO.StringIO(data)).read()
    return data
class CreativeService(ApiService):
    """Wrapper for CreativeService.

  The Creative Service provides methods for adding, updating and retrieving
  creatives.
  """
    def __init__(self, headers, config, op_config, lock, logger):
        """Inits CreativeService.

    Args:
      headers: dict Dictionary object with populated authentication
               credentials.
      config: dict Dictionary object with populated configuration values.
      op_config: dict Dictionary object with additional configuration values for
                 this operation.
      lock: thread.lock Thread lock
      logger: Logger Instance of Logger
    """
        url = [
            op_config['server'], 'apis/ads/publisher', op_config['version'],
            self.__class__.__name__
        ]
        self.__service = DfpWebService(headers, config, op_config,
                                       '/'.join(url), lock, logger)
        super(CreativeService, self).__init__(headers, config, op_config, url,
                                              'adspygoogle.dfp', lock, logger)

    def CreateCreative(self, creative):
        """Create a new creative.

    Args:
      creative: dict Creative to create.

    Returns:
      tuple Response from the API method.
    """
        method_name = 'createCreative'
        if self._config['soap_lib'] == SOAPPY:
            from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
            creative = self._message_handler.PackDictAsXml(
                self._sanity_check.ValidateCreative(creative), 'creative',
                OBJ_KEY_ORDER_MAP)
            return self.__service.CallMethod(method_name, (creative))
        elif self._config['soap_lib'] == ZSI:
            creative = self._sanity_check.ValidateCreative(
                creative, self._web_services)
            request = eval('self._web_services.%sRequest()' % method_name)
            return self.__service.CallMethod(method_name,
                                             (({
                                                 'creative': creative
                                             }, )), 'Creative', self._loc,
                                             request)

    def CreateCreatives(self, creatives):
        """Create a list of new creatives.

    Args:
      creatives: list Creatives to create.

    Returns:
      tuple response from the API method.
    """
        method_name = 'createCreatives'
        if self._config['soap_lib'] == SOAPPY:
            from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
            new_creatives = []
            for creative in creatives:
                new_creatives.append(
                    self._message_handler.PackDictAsXml(
                        self._sanity_check.ValidateCreative(creative),
                        'creatives', OBJ_KEY_ORDER_MAP))
            return self.__service.CallMethod(method_name,
                                             (''.join(new_creatives)))
        elif self._config['soap_lib'] == ZSI:
            SanityCheck.ValidateTypes(((creatives, list), ))
            new_creatives = []
            for item in creatives:
                new_creatives.append(
                    self._sanity_check.ValidateCreative(
                        item, self._web_services))
            request = eval('self._web_services.%sRequest()' % method_name)
            return self.__service.CallMethod(method_name,
                                             (({
                                                 'creatives': new_creatives
                                             }, )), 'Creative', self._loc,
                                             request)

    def GetCreative(self, creative_id):
        """Return the creative uniquely identified by the given id.

    Args:
      creative_id: str ID of the creative, which must already exist.

    Returns:
      tuple Response from the API method.
    """
        SanityCheck.ValidateTypes(((creative_id, (str, unicode)), ))

        method_name = 'getCreative'
        if self._config['soap_lib'] == SOAPPY:
            from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
            creative_id = self._message_handler.PackDictAsXml(
                creative_id, 'creativeId', OBJ_KEY_ORDER_MAP)
            return self.__service.CallMethod(method_name, (creative_id))
        elif self._config['soap_lib'] == ZSI:
            request = eval('self._web_services.%sRequest()' % method_name)
            return self.__service.CallMethod(method_name,
                                             (({
                                                 'creativeId': creative_id
                                             }, )), 'Creative', self._loc,
                                             request)

    def GetCreativesByStatement(self, filter_statement):
        """Return a page of creatives that satisfy the given statement.

    Args:
      filter_statement: dict Publisher Query Language statement used to filter a
                        set of creatives.

    Returns:
      tuple Response from the API method.
    """
        method_name = 'getCreativesByStatement'
        if self._config['soap_lib'] == SOAPPY:
            from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
            filter_statement = self._message_handler.PackDictAsXml(
                self._sanity_check.ValidateStatement(filter_statement),
                'filterStatement', OBJ_KEY_ORDER_MAP)
            return self.__service.CallMethod(method_name, (filter_statement))
        elif self._config['soap_lib'] == ZSI:
            filter_statement = self._sanity_check.ValidateStatement(
                filter_statement, self._web_services)
            request = eval('self._web_services.%sRequest()' % method_name)
            return self.__service.CallMethod(
                method_name, (({
                    'filterStatement': filter_statement
                }, )), 'Creative', self._loc, request)

    def UpdateCreative(self, creative):
        """Update the specified creative.

    Args:
      company: dict Creative to update.

    Returns:
      tuple Response from the API method.
    """
        method_name = 'updateCreative'
        if self._config['soap_lib'] == SOAPPY:
            from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
            creative = self._message_handler.PackDictAsXml(
                self._sanity_check.ValidateCreative(creative), 'creative',
                OBJ_KEY_ORDER_MAP)
            return self.__service.CallMethod(method_name, (creative))
        elif self._config['soap_lib'] == ZSI:
            creative = self._sanity_check.ValidateCreative(
                creative, self._web_services)
            request = eval('self._web_services.%sRequest()' % method_name)
            return self.__service.CallMethod(method_name,
                                             (({
                                                 'creative': creative
                                             }, )), 'Creative', self._loc,
                                             request)

    def UpdateCreatives(self, creatives):
        """Update a list of specified creatives.

    Args:
      companies: list Creatives to update.

    Returns:
      tuple Response from the API method.
    """
        method_name = 'updateCreatives'
        if self._config['soap_lib'] == SOAPPY:
            from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
            new_creatives = []
            for creative in creatives:
                new_creatives.append(
                    self._message_handler.PackDictAsXml(
                        self._sanity_check.ValidateCreative(creative),
                        'creatives', OBJ_KEY_ORDER_MAP))
            return self.__service.CallMethod(method_name,
                                             (''.join(new_creatives)))
        elif self._config['soap_lib'] == ZSI:
            SanityCheck.ValidateTypes(((creatives, list), ))
            new_creatives = []
            for item in creatives:
                new_creatives.append(
                    self._sanity_check.ValidateCreative(
                        item, self._web_services))
            request = eval('self._web_services.%sRequest()' % method_name)
            return self.__service.CallMethod(method_name,
                                             (({
                                                 'creatives': new_creatives
                                             }, )), 'Creative', self._loc,
                                             request)
class LineItemCreativeAssociationService(ApiService):
    """Wrapper for LineItemCreativeAssociationService.

  The LineItemCreativeAssociation Service provides operations for creating,
  updating and retrieving line item creative associations (LICA).
  """
    def __init__(self, headers, config, op_config, lock, logger):
        """Inits LineItemCreativeAssociationService.

    Args:
      headers: dict Dictionary object with populated authentication
               credentials.
      config: dict Dictionary object with populated configuration values.
      op_config: dict Dictionary object with additional configuration values for
                 this operation.
      lock: thread.lock Thread lock
      logger: Logger Instance of Logger
    """
        url = [
            op_config['server'], 'apis/ads/publisher', op_config['version'],
            self.__class__.__name__
        ]
        self.__service = DfpWebService(headers, config, op_config,
                                       '/'.join(url), lock, logger)
        super(LineItemCreativeAssociationService,
              self).__init__(headers, config, op_config, url,
                             'adspygoogle.dfp', lock, logger)

    def CreateLineItemCreativeAssociation(self, lica):
        """Create a new line item creative association.

    Args:
      lica: dict Line item creative association to create.

    Returns:
      tuple Response from the API method.
    """
        self._sanity_check.ValidateLica(lica)

        method_name = 'createLineItemCreativeAssociation'
        if self._config['soap_lib'] == SOAPPY:
            from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
            lica = self._message_handler.PackDictAsXml(
                lica, 'lineItemCreativeAssociation', OBJ_KEY_ORDER_MAP)
            return self.__service.CallMethod(method_name, (lica))
        elif self._config['soap_lib'] == ZSI:
            request = eval('self._web_services.%sRequest()' % method_name)
            return self.__service.CallMethod(
                method_name, (({
                    'lineItemCreativeAssociation': lica
                }, )), 'LineItemCreativeAssociation', self._loc, request)

    def CreateLineItemCreativeAssociations(self, licas):
        """Create a list of new line item creative associations.

    Args:
      licas: list Line item creative associations to create.

    Returns:
      tuple Response from the API method.
    """
        SanityCheck.ValidateTypes(((licas, list), ))
        for item in licas:
            self._sanity_check.ValidateLica(item)

        method_name = 'createLineItemCreativeAssociations'
        if self._config['soap_lib'] == SOAPPY:
            from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
            new_licas = []
            for lica in licas:
                new_licas.append(
                    self._message_handler.PackDictAsXml(
                        lica, 'lineItemCreativeAssociations',
                        OBJ_KEY_ORDER_MAP))
            return self.__service.CallMethod(method_name, (''.join(new_licas)))
        elif self._config['soap_lib'] == ZSI:
            request = eval('self._web_services.%sRequest()' % method_name)
            return self.__service.CallMethod(
                method_name, (({
                    'lineItemCreativeAssociations': licas
                }, )), 'LineItemCreativeAssociation', self._loc, request)

    def GetLineItemCreativeAssociation(self, line_item_id, creative_id):
        """Return the line item creative association uniquely identified by the
    given line item id and creative id.

    Args:
      line_item_id: str ID of the line item, which must already exist.
      creative_id: str ID of the creative, which must already exist.

    Returns:
      tuple Response from the API method.
    """
        SanityCheck.ValidateTypes(
            ((line_item_id, (str, unicode)), (creative_id, (str, unicode))))

        method_name = 'getLineItemCreativeAssociation'
        if self._config['soap_lib'] == SOAPPY:
            from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
            line_item_id = self._message_handler.PackDictAsXml(
                line_item_id, 'lineItemId', OBJ_KEY_ORDER_MAP)
            creative_id = self._message_handler.PackDictAsXml(
                creative_id, 'creativeId', OBJ_KEY_ORDER_MAP)
            return self.__service.CallMethod(
                method_name, (''.join([line_item_id, creative_id])))
        elif self._config['soap_lib'] == ZSI:
            request = eval('self._web_services.%sRequest()' % method_name)
            return self.__service.CallMethod(method_name, ((
                {
                    'lineItemId': line_item_id
                },
                {
                    'creativeId': creative_id
                },
            )), 'LineItemCreativeAssociation', self._loc, request)

    def GetLineItemCreativeAssociationsByStatement(self, filter_statement):
        """Return the line item creative associations that match the given
    statement.

    Args:
      filter_statement: dict Publisher Query Language statement used to filter a
                        set of line item creative associations

    Returns:
      tuple Response from the API method.
    """
        method_name = 'getLineItemCreativeAssociationsByStatement'
        if self._config['soap_lib'] == SOAPPY:
            from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
            filter_statement = self._message_handler.PackDictAsXml(
                self._sanity_check.ValidateStatement(filter_statement),
                'filterStatement', OBJ_KEY_ORDER_MAP)
            return self.__service.CallMethod(method_name, (filter_statement))
        elif self._config['soap_lib'] == ZSI:
            filter_statement = self._sanity_check.ValidateStatement(
                filter_statement, self._web_services)
            request = eval('self._web_services.%sRequest()' % method_name)
            return self.__service.CallMethod(
                method_name, (({
                    'filterStatement': filter_statement
                }, )), 'LineItemCreativeAssociation', self._loc, request)

    def PerformLineItemCreativeAssociationAction(self, action,
                                                 filter_statement):
        """Perform action on line item creative associations that match the given
    statement.

    Args:
      action: str Action to perform.
      filter_statement: dict Publisher Query Language statement.

    Returns:
      tuple Response from the API method.
    """
        method_name = 'performLineItemCreativeAssociationAction'
        if self._config['soap_lib'] == SOAPPY:
            from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
            self._sanity_check.ValidateAction(action)
            action = self._message_handler.PackDictAsXml(
                action, 'lineItemCreativeAssociationAction', OBJ_KEY_ORDER_MAP)
            filter_statement = self._message_handler.PackDictAsXml(
                self._sanity_check.ValidateStatement(filter_statement),
                'filterStatement', OBJ_KEY_ORDER_MAP)
            return self.__service.CallMethod(
                method_name, (''.join([action, filter_statement])))
        elif self._config['soap_lib'] == ZSI:
            action = self._sanity_check.ValidateAction(action,
                                                       self._web_services)
            filter_statement = self._sanity_check.ValidateStatement(
                filter_statement, self._web_services)
            request = eval('self._web_services.%sRequest()' % method_name)
            return self.__service.CallMethod(
                method_name, (({
                    'lineItemCreativeAssociationAction': action
                }, {
                    'filterStatement': filter_statement
                })), 'LineItemCreativeAssociation', self._loc, request)

    def UpdateLineItemCreativeAssociation(self, lica):
        """Update the specified line item creative associations.

    Args:
      lica: dict Line item creative association to update.

    Returns:
      tuple Response from the API method.
    """
        self._sanity_check.ValidateLica(lica)

        method_name = 'updateLineItemCreativeAssociation'
        if self._config['soap_lib'] == SOAPPY:
            from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
            lica = self._message_handler.PackDictAsXml(
                lica, 'lineItemCreativeAssociation', OBJ_KEY_ORDER_MAP)
            return self.__service.CallMethod(method_name, (lica))
        elif self._config['soap_lib'] == ZSI:
            request = eval('self._web_services.%sRequest()' % method_name)
            return self.__service.CallMethod(
                method_name, (({
                    'lineItemCreativeAssociation': lica
                }, )), 'LineItemCreativeAssociation', self._loc, request)

    def UpdateLineItemCreativeAssociations(self, licas):
        """Update a list of specified line item creative associations.

    Args:
      licas: list the line item creative associations to update.

    Returns:
      tuple Response from the API method.
    """
        SanityCheck.ValidateTypes(((licas, list), ))
        for item in licas:
            self._sanity_check.ValidateLica(item)

        method_name = 'updateLineItemCreativeAssociations'
        if self._config['soap_lib'] == SOAPPY:
            from adspygoogle.dfp.soappy import OBJ_KEY_ORDER_MAP
            new_licas = []
            for lica in licas:
                new_licas.append(
                    self._message_handler.PackDictAsXml(
                        lica, 'lineItemCreativeAssociations',
                        OBJ_KEY_ORDER_MAP))
            return self.__service.CallMethod(method_name, (''.join(new_licas)))
        elif self._config['soap_lib'] == ZSI:
            request = eval('self._web_services.%sRequest()' % method_name)
            return self.__service.CallMethod(
                method_name, (({
                    'lineItemCreativeAssociations': licas
                }, )), 'LineItemCreativeAssociation', self._loc, request)