#!/usr/bin/python # # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """Methods to access AdGroupService service.""" __author__ = 'api.sgrinberg@gmail.com (Stan Grinberg)' from aw_api import SanityCheck as glob_sanity_check from aw_api import SOAPPY from aw_api import ZSI from aw_api.Errors import ValidationError from aw_api.WebService import WebService class AdGroupService(object): """Wrapper for AdGroupService. The Ad Group Service provides operations for accessing, modifying, and creating AdGroups. """ def __init__(self, headers, config, op_config, lock, logger): """Inits AdGroupService. 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 the thread lock. logger: Logger the instance of Logger """ url = [op_config['server'], 'api/adwords', op_config['version'], self.__class__.__name__] if glob_sanity_check.IsNewApi(op_config['version']): url.insert(2, op_config['group']) if config['access']: url.insert(len(url) - 1, config['access']) self.__service = WebService(headers, config, op_config, '/'.join(url), lock, logger) self.__config = config self.__op_config = op_config if self.__config['soap_lib'] == SOAPPY: from aw_api.soappy_toolkit import MessageHandler from aw_api.soappy_toolkit import SanityCheck self.__web_services = None self.__message_handler = MessageHandler elif self.__config['soap_lib'] == ZSI: from aw_api import API_VERSIONS from aw_api.zsi_toolkit import SanityCheck if op_config['version'] in API_VERSIONS: module = '%s_services' % self.__class__.__name__ try: web_services = __import__('aw_api.zsi_toolkit.%s.%s' % (op_config['version'], module), globals(), locals(), ['']) except ImportError, e: # If one of library's required modules is missing, re raise exception. if str(e).find(module) < 0: raise ImportError(e) msg = ('The version \'%s\' is not compatible with \'%s\'.' % (op_config['version'], self.__class__.__name__)) raise ValidationError(msg) else: msg = 'Invalid API version, not one of %s.' % str(list(API_VERSIONS)) raise ValidationError(msg) self.__web_services = web_services self.__loc = eval('web_services.%sLocator()' % self.__class__.__name__) self.__sanity_check = SanityCheck def AddAdGroup(self, campaign_id, ad_group): """Create a new AdGroup. Args: campaign_id: str campaign in which this AdGroup will be created. ad_group: dict information for the new ad group. Ex: campaign_id = '1234567890' ad_group = { 'campaignId': '1234567890', 'keywordContentMaxCpc': '1000000', 'keywordMaxCpc': '1000000', 'maxCpa': '1000000', 'name': 'Test AdGroup', 'proxyKeywordMaxCpc': '1000000', 'siteMaxCpc': '1000000', 'siteMaxCpm': '1000000' } Returns: tuple response from the API method. """ glob_sanity_check.ValidateTypes(((campaign_id, (str, unicode)), (ad_group, dict))) self.__sanity_check.ValidateAdGroupV13(ad_group) method_name = 'addAdGroup' if self.__config['soap_lib'] == SOAPPY: return self.__service.CallMethod(method_name, (campaign_id, ad_group)) elif self.__config['soap_lib'] == ZSI: web_services = self.__web_services request = eval('web_services.%sRequest()' % method_name) return self.__service.CallMethod(method_name, (({'campaignID': campaign_id}, {'newData': ad_group})), 'AdGroup', self.__loc, request) def AddAdGroupList(self, campaign_id, ad_groups): """Create multiple new AdGroups. Args: campaign_id: str campaign in which this AdGroup will be created. ad_groups: list information for the new ad groups. Ex: campaign_id = '1234567890' ad_groups = [ { 'campaignId': '1234567890', 'keywordContentMaxCpc': '1000000', 'keywordMaxCpc': '1000000', 'maxCpa': '1000000', 'name': 'Test AdGroup', 'proxyKeywordMaxCpc': '1000000', 'siteMaxCpc': '1000000', 'siteMaxCpm': '1000000' } ] Returns: tuple response from the API method. """ glob_sanity_check.ValidateTypes(((campaign_id, (str, unicode)), (ad_groups, list))) for item in ad_groups: self.__sanity_check.ValidateAdGroupV13(item) method_name = 'addAdGroupList' if self.__config['soap_lib'] == SOAPPY: return self.__service.CallMethod(method_name, (campaign_id, ad_groups)) elif self.__config['soap_lib'] == ZSI: web_services = self.__web_services request = eval('web_services.%sRequest()' % method_name) return self.__service.CallMethod(method_name, (({'campaignID': campaign_id}, {'newData': ad_groups})), 'AdGroup', self.__loc, request) def GetActiveAdGroups(self, campaign_id): """Get all information about the Active AdGroups. Args: campaign_id: str ID of the Campaign whose AdGroups to retrieve. Ex: campaign_id = '1234567890' Returns: tuple response from the API method. """ glob_sanity_check.ValidateTypes(((campaign_id, (str, unicode)),)) method_name = 'getActiveAdGroups' if self.__config['soap_lib'] == SOAPPY: return self.__service.CallMethod(method_name, (campaign_id)) elif self.__config['soap_lib'] == ZSI: web_services = self.__web_services request = eval('web_services.%sRequest()' % method_name) return self.__service.CallMethod(method_name, (({'campaignID': campaign_id},)), 'AdGroup', self.__loc, request) def GetAdGroup(self, ad_group_id): """Get all information about the specified AdGroup. Args: ad_group_id: str ID of the specified AdGroup. Ex: ad_group_id = '1234567890' Returns: tuple response from the API method. """ glob_sanity_check.ValidateTypes(((ad_group_id, (str, unicode)),)) method_name = 'getAdGroup' if self.__config['soap_lib'] == SOAPPY: return self.__service.CallMethod(method_name, (ad_group_id)) elif self.__config['soap_lib'] == ZSI: web_services = self.__web_services request = eval('web_services.%sRequest()' % method_name) return self.__service.CallMethod(method_name, (({'adGroupId': ad_group_id},)), 'AdGroup', self.__loc, request) def GetAdGroupList(self, ad_group_ids): """Get all information about a set of AdGroups. Args: ad_group_ids: list IDs of the AdGroups to load. Ex: ad_group_ids = ['1234567890'] Returns: tuple response from the API method. """ glob_sanity_check.ValidateTypes(((ad_group_ids, list),)) for item in ad_group_ids: glob_sanity_check.ValidateTypes(((item, (str, unicode)),)) method_name = 'getAdGroupList' if self.__config['soap_lib'] == SOAPPY: return self.__service.CallMethod(method_name, (ad_group_ids)) elif self.__config['soap_lib'] == ZSI: web_services = self.__web_services request = eval('web_services.%sRequest()' % method_name) return self.__service.CallMethod(method_name, (({'adgroupIDs': ad_group_ids},)), 'AdGroup', self.__loc, request) def GetAdGroupStats(self, campaign_id, ad_group_ids, start_day, end_day): """Get statistics for a list of ad groups in a campaign. Args: campaign_id: str campaign in which to find the ad groups. ad_group_ids: list ad groups whose statistics are being queried. start_day: str starting day of the period for which statistics are to be collected. end_day: str ending day of the period for which statistics are to be collected, inclusive. Ex: campaign_id = '1234567890' ad_group_ids = ['1234567890'] start_day = '2008-01-01' end_day = '2008-01-31' Returns: tuple response from the API method. """ glob_sanity_check.ValidateTypes(((campaign_id, (str, unicode)), (ad_group_ids, list), (start_day, (str, unicode)), (end_day, (str, unicode)))) for item in ad_group_ids: glob_sanity_check.ValidateTypes(((item, (str, unicode)),)) method_name = 'getAdGroupStats' if self.__config['soap_lib'] == SOAPPY: return self.__service.CallMethod(method_name, (campaign_id, ad_group_ids, start_day, end_day)) elif self.__config['soap_lib'] == ZSI: web_services = self.__web_services request = eval('web_services.%sRequest()' % method_name) return self.__service.CallMethod(method_name, (({'campaignId': campaign_id}, {'adGroupIds': ad_group_ids}, {'startDay': start_day}, {'endDay': end_day})), 'AdGroup', self.__loc, request) def GetAllAdGroups(self, campaign_id): """Get all information about the adgroups associated with a campaign. Args: campaign_id: str campaign whose AdGroups will be retrieved. Ex: campaign_id = '1234567890' Returns: tuple response from the API method. """ glob_sanity_check.ValidateTypes(((campaign_id, (str, unicode)),)) method_name = 'getAllAdGroups' if self.__config['soap_lib'] == SOAPPY: return self.__service.CallMethod(method_name, (campaign_id)) elif self.__config['soap_lib'] == ZSI: web_services = self.__web_services request = eval('web_services.%sRequest()' % method_name) return self.__service.CallMethod(method_name, (({'campaignID': campaign_id},)), 'AdGroup', self.__loc, request) def UpdateAdGroup(self, ad_group): """Update the fields of an existing AdGroup. Args: ad_group: dict new contents of the AdGroup. Ex: ad_group = { 'campaignId': '1234567890', 'adGroupId': '1234567890', 'keywordContentMaxCpc': '1000000', 'keywordMaxCpc': '1000000', 'maxCpa': '1000000', 'name': 'Test AdGroup', 'proxyKeywordMaxCpc': '1000000', 'siteMaxCpc': '1000000', 'siteMaxCpm': '1000000' } """ self.__sanity_check.ValidateAdGroupV13(ad_group) method_name = 'updateAdGroup' if self.__config['soap_lib'] == SOAPPY: self.__service.CallMethod(method_name, (ad_group)) elif self.__config['soap_lib'] == ZSI: web_services = self.__web_services request = eval('web_services.%sRequest()' % method_name) self.__service.CallMethod(method_name, (({'changedData': ad_group},)), 'AdGroup', self.__loc, request) def UpdateAdGroupList(self, ad_groups): """Update the fields of multiple existing AdGroups. Args: ad_groups: list ad groups to be updates. Ex: ad_groups = [ { 'campaignId': '1234567890', 'adGroupId': '1234567890', 'keywordContentMaxCpc': '1000000', 'keywordMaxCpc': '1000000', 'maxCpa': '1000000', 'name': 'Test AdGroup', 'proxyKeywordMaxCpc': '1000000', 'siteMaxCpc': '1000000', 'siteMaxCpm': '1000000' } ] """ glob_sanity_check.ValidateTypes(((ad_groups, list),)) for item in ad_groups: self.__sanity_check.ValidateAdGroupV13(item) method_name = 'updateAdGroupList' if self.__config['soap_lib'] == SOAPPY: self.__service.CallMethod(method_name, (ad_groups)) elif self.__config['soap_lib'] == ZSI: web_services = self.__web_services request = eval('web_services.%sRequest()' % method_name) self.__service.CallMethod(method_name, (({'changedData': ad_groups},)), 'AdGroup', self.__loc, request) def Get(self, selector): """Return a list of all the ad groups. List of all the ad groups specified by the ad group selector from the target customer's account. Args: selector: dict filter to run ad groups through. Returns: tuple list of ad groups meeting all the criteria of the selector. """ method_name = 'getAdGroup' if self.__config['soap_lib'] == SOAPPY: self.__sanity_check.ValidateSelector(selector) selector = self.__message_handler.PackDictAsXml( selector, 'selector', ['campaignId', 'adGroupIds', 'statsSelector', 'paging']) return self.__service.CallMethod( method_name.split(self.__class__.__name__.split('Service')[0])[0], (selector)) elif self.__config['soap_lib'] == ZSI: web_services = self.__web_services self.__sanity_check.ValidateSelector(selector, web_services) request = eval('web_services.%sRequest()' % method_name) return self.__service.CallMethod(method_name, (({'selector': selector},)), 'AdGroup', self.__loc, request) def Mutate(self, ops): """Add, update, or remove ad groups. Args: ops: list unique operations. Returns: tuple mutated ad groups. """ method_name = 'mutateAdGroup' if self.__config['soap_lib'] == SOAPPY: glob_sanity_check.ValidateTypes(((ops, list),)) new_ops = [] for op in ops: self.__sanity_check.ValidateOperation(op) new_ops.append(self.__message_handler.PackDictAsXml( op, 'operations', ['operator', 'operand'])) ops = ''.join(new_ops) return self.__service.CallMethod( method_name.split(self.__class__.__name__.split('Service')[0])[0], (ops)) elif self.__config['soap_lib'] == ZSI: web_services = self.__web_services glob_sanity_check.ValidateTypes(((ops, list),)) for op in ops: op = self.__sanity_check.ValidateOperation(op, web_services) request = eval('web_services.%sRequest()' % method_name) return self.__service.CallMethod(method_name, (({'operations': ops},)), 'AdGroup', self.__loc, request)