def ValidateStatement(statement): """Validate Statement object. Args: statement: dict Statement object. """ SanityCheck.ValidateTypes(((statement, dict), )) for key in statement: if statement[key] == 'None': continue if key in ('params', ): SanityCheck.ValidateTypes(((statement[key], list), )) if len(statement[key]) > 1: msg = ( 'Map \'params\' must contain a single element in the list.' ) raise ValidationError(msg) for param in statement[key]: ValidateString_ParamMapEntry(param) elif key in ('values', ): SanityCheck.ValidateTypes(((statement[key], list), )) if len(statement[key]) > 1: msg = ( 'Map \'values\' must contain a single element in the list.' ) raise ValidationError(msg) for value in statement[key]: ValidateString_ValueMapEntry(value) else: SanityCheck.ValidateTypes(((statement[key], (str, unicode)), )) return statement
def ValidateString_ValueMapEntry(value, web_services): """Validate String_ValueMapEntry object. Args: value: dict Value object. web_services: module Web services. Returns: String_ValueMapEntry instance. """ if ZsiSanityCheck.IsPyClass(value): return value SanityCheck.ValidateTypes(((value, dict), )) new_value = ZsiSanityCheck.GetPyClass('String_ValueMapEntry', web_services) for key in value: if key in ('value', ): SanityCheck.ValidateTypes(((value[key], dict), )) if 'xsi_type' in value[key]: value_obj = ZsiSanityCheck.GetPyClass(value[key]['xsi_type'], web_services) else: msg = ('The \'xsi_type\' of the value is missing.') raise ValidationError(msg) for sub_key in value[key]: value_obj.__dict__.__setitem__('_%s' % sub_key, value[key][sub_key]) data = value_obj else: SanityCheck.ValidateTypes(((value[key], (str, unicode)), )) data = value[key] new_value.__dict__.__setitem__('_%s' % key, data) return new_value
def ValidateString_ParamMapEntry(param, web_services): """Validate String_ParamMapEntry object. Args: param: dict Param object. web_services: module Web services. Returns: String_ParamMapEntry instance. """ if ZsiSanityCheck.IsPyClass(param): return param SanityCheck.ValidateTypes(((param, dict), )) new_param = ZsiSanityCheck.GetPyClass('String_ParamMapEntry', web_services) for key in param: SanityCheck.ValidateTypes(((param[key], (str, unicode)), )) if key in ('value', ): if 'xsi_type' in param: value = ZsiSanityCheck.GetPyClass(param['xsi_type'], web_services) elif 'type' in param: value = ZsiSanityCheck.GetPyClass(param['type'], web_services) else: msg = ('The type of the param is missing.') raise ValidationError(msg) value.__dict__.__setitem__('_%s' % key, param[key]) data = value else: data = param[key] new_param.__dict__.__setitem__('_%s' % key, data) return new_param
def ValidateDefinedReportJobV13(job, name_space): """Validate DefinedReportJob object. Args: job: dict report job object. name_space: str namespace to use for this ReportJob. Returns: instance Untyped instance of the defined report job. """ items = [] for key in job: if (key == 'adWordsType' or key == 'crossClient' or key == 'endDay' or key == 'includeZeroImpression' or key == 'keywordType' or key == 'name' or key == 'selectedReportType' or key == 'startDay'): SanityCheck.ValidateTypes(((job[key], (str, unicode)), )) items.append('<%s>%s</%s>' % (key, job[key], key)) else: SanityCheck.ValidateTypes(((job[key], list), )) for item in job[key]: SanityCheck.ValidateTypes(((item, (str, unicode)), )) items.append('<%s>%s</%s>' % (key, item, key)) # Explicitly set job's namespace and type. job = SoappySanityCheck.UnType(''.join(items)) job._setAttr('xmlns:impl', name_space) job._setAttr('xsi3:type', 'impl:DefinedReportJob') return job
def Mutate(self, ops): """Add, update, or remove ad group ads. Args: ops: list Unique operations. Returns: tuple Mutated ad group ads. """ method_name = 'mutateAdGroupAd' SanityCheck.ValidateTypes(((ops, list),)) for op in ops: SanityCheck.NewSanityCheck(self._wsdl_types_map, op, 'AdGroupAdOperation') if self._config['soap_lib'] == SOAPPY: new_ops = [] for op in ops: new_ops.append(self._message_handler.PackVarAsXml( op, 'operations', self._wsdl_types_map, False, 'AdGroupAdOperation')) return self.__service.CallMethod( method_name.split(self.__class__.__name__.split('Service')[0])[0], (''.join(new_ops))) elif self._config['soap_lib'] == ZSI: new_ops = [] for op in ops: new_ops.append(self._transformation.MakeZsiCompatible( op, 'AdGroupAdOperation', self._wsdl_types_map, self._web_services)) request = eval('self._web_services.%sRequest()' % method_name) return self.__service.CallMethod(method_name, (({'operations': new_ops},)), 'AdGroupAd', self._loc, request)
def ValidateCustomCriteriaSet(criteria_set): """Validate CustomCriteriaSet object. Args: criteria_set: dict CustomCriteriaSet object. Returns: CustomCriteriaSet instance. """ SanityCheck.ValidateTypes(((criteria_set, dict), )) for key in criteria_set: if key in ('children', ): SanityCheck.ValidateTypes(((criteria_set[key], list), )) children = [] for item in criteria_set[key]: if 'xsi_type' in item: if item['xsi_type'] in ('FreeFormCustomCriteria', 'PredefinedCustomCriteria'): children.append(ValidateCustomCriteria(item)) else: children.append(ValidateCustomCriteriaSet(item)) else: msg = 'The \'xsi_type\' of node is missing.' raise ValidationError(msg) else: SanityCheck.ValidateTypes(((criteria_set[key], (str, unicode)), ))
def ValidateLineItem(line_item, web_services): """Validate LineItem object. Args: line_item: dict LineItem object. web_services: module Web services. """ SanityCheck.ValidateTypes(((line_item, dict), )) for key in line_item: if line_item[key] == 'None': continue if key in ('creativeSizes', ): SanityCheck.ValidateTypes(((line_item[key], list), )) for item in line_item[key]: ValidateSize(item) elif key in ('startDateTime', 'endDateTime'): ValidateDateTime(line_item[key]) elif key in ('costPerUnit', 'valueCostPerUnit', 'budget'): ValidateMoney(line_item[key]) elif key in ('frequencyCaps', ): SanityCheck.ValidateTypes(((line_item[key], list), )) for item in line_item[key]: ValidateFrequencyCap(item) elif key in ('targeting', ): ValidateTargeting(line_item[key], web_services) else: SanityCheck.ValidateTypes(((line_item[key], (str, unicode)), ))
def ValidateAction(action, web_services): """Validate Action object. Args: action: dict Action to perform. web_services: module Web services. Returns: Action instance. """ if ZsiSanityCheck.IsPyClass(action): return action SanityCheck.ValidateTypes(((action, dict), )) if 'xsi_type' in action: new_action = ZsiSanityCheck.GetPyClass(action['xsi_type'], web_services) elif 'type' in action: new_action = ZsiSanityCheck.GetPyClass(action['type'], web_services) else: msg = 'The type of the action is missing.' raise ValidationError(msg) for key in action: SanityCheck.ValidateTypes(((action[key], (str, unicode)), )) new_action.__dict__.__setitem__('_%s' % key, action[key]) return new_action
def ValidateKeywordTrafficRequestV13(request): """Validate KeywordTrafficRequest object. Args: request: dict KeywordTrafficRequest object. """ SanityCheck.ValidateTypes(((request, dict), )) for key in request: SanityCheck.ValidateTypes(((request[key], (str, unicode)), ))
def ValidateAction(action): """Validate Action object. Args: action: dict Action to perform. """ SanityCheck.ValidateTypes(((action, dict), )) if 'type' not in action: msg = 'The \'type\' of the action is missing.' raise ValidationError(msg) for key in action: SanityCheck.ValidateTypes(((action[key], (str, unicode)), ))
def ValidateDayPart(part): """Validate DayPart object. Args: part: dict DayPart object. """ SanityCheck.ValidateTypes(((part, dict), )) for key in part: if key in ('startTime', 'endTime'): ValidateDate(part[key]) else: SanityCheck.ValidateTypes(((part[key], (str, unicode)), ))
def ValidateReportJob(report_job): """Validate ReportJob object. Args: report_job: dict ReportJob object. """ SanityCheck.ValidateTypes(((report_job, dict), )) for key in report_job: if key in ('reportQuery', ): ValidateReportQuery(report_job[key]) else: SanityCheck.ValidateTypes(((report_job[key], (str, unicode)), ))
def testAllowedArrayTypeValuesSucceed(self): """Test that Sanity Check does not fail on allowed array type values.""" SanityCheck.NewSanityCheck(self.__class__.TYPES_MAP, ['1', '2'], 'ArrayOf_xsd_string') predicate = { 'field': 'string', 'type': 'ENABLED', 'values': ['strings', '10', 'True'] } SanityCheck.NewSanityCheck(self.__class__.TYPES_MAP, [predicate], 'ArrayOf_Predicate')
def ValidateSize_StringMapEntry(map_entry): """Validate Size_StringMapEntry object. Args: map_entry: dict Size_StringMapEntry object. """ SanityCheck.ValidateTypes(((map_entry, dict), )) for key in map_entry: if map_entry[key] == 'None': continue if key in ('key', ): ValidateSize(map_entry[key]) else: SanityCheck.ValidateTypes(((map_entry[key], (str, unicode)), ))
def ValidateDateTime(date_time): """Validate DateTime object. Args: date_time: dict DateTime object. """ SanityCheck.ValidateTypes(((date_time, dict), )) for key in date_time: if date_time[key] == 'None': continue if key in ('date', ): ValidateDate(date_time[key]) else: SanityCheck.ValidateTypes(((date_time[key], (str, unicode)), ))
def ValidateString_ParamMapEntry(param): """Validate String_ParamMapEntry object. Args: param: dict Param object. """ SanityCheck.ValidateTypes(((param, dict), )) for key in param: if param[key] == 'None': continue SanityCheck.ValidateTypes(((param[key], (str, unicode)), )) if key in ('value', ): if 'type' not in param: msg = ('The \'type\' of the param is missing.') raise ValidationError(msg)
def ValidateAdGroupRequestV13(request): """Validate AdGroupRequest object. Args: request: dict AdGroupRequest object. """ SanityCheck.ValidateTypes(((request, dict), )) for key in request: if key in ('keywordRequests', ): SanityCheck.ValidateTypes(((request[key], list), )) for item in request[key]: ValidateKeywordRequestV13(item) else: SanityCheck.ValidateTypes(((request[key], (str, unicode)), ))
def ValidateLanguageTargetV13(language_target): """Validate LanguageTarget object. Args: language_target: list Languages targeted by this entity. Returns: str Languages targeted converted into str type. """ SanityCheck.ValidateTypes(((language_target, list), )) items = [] for item in language_target: SanityCheck.ValidateTypes(((item, (str, unicode)), )) items.append('<languages>%s</languages>' % item) return ''.join(items)
def ValidateAdSenseSettings(settings): """Validate AdSenseSettings object. Args: settings: dict AdSenseSettings object. """ SanityCheck.ValidateTypes(((settings, dict), )) for key in settings: if settings[key] == 'None': continue if key in ('afcFormats', ): SanityCheck.ValidateTypes(((settings[key], list), )) for item in settings[key]: ValidateSize_StringMapEntry(item) else: SanityCheck.ValidateTypes(((settings[key], (str, unicode)), ))
def ValidateNetworkTargetV13(network_target): """Validate NetworkTarget object. Args: network_target: list Advertising networks targeted by this entity. Returns: str Adertising networks converted into str type. """ SanityCheck.ValidateTypes(((network_target, list), )) items = [] for item in network_target: SanityCheck.ValidateTypes(((item, (str, unicode)), )) items.append('<networkTypes>%s</networkTypes>' % item) return ''.join(items)
def ValidatePlacement(placement): """Validate Placement object. Args: placement: dict Placement object. """ SanityCheck.ValidateTypes(((placement, dict), )) for key in placement: if placement[key] == 'None': continue if key in ('targetedAdUnitIds', ): SanityCheck.ValidateTypes(((placement[key], list), )) for item in placement[key]: SanityCheck.ValidateTypes(((item, (str, unicode)), )) else: SanityCheck.ValidateTypes(((placement[key], (str, unicode)), ))
def ValidateKeywordRequestV13(request): """Validate KeywordRequest object. Args: request: dict keyword request. Returns: str keyword request converted into str type. """ SanityCheck.ValidateTypes(((request, dict), )) items = [] for key in request: SanityCheck.ValidateTypes(((request[key], (str, unicode)), )) items.append('<%s>%s</%s>' % (key, request[key], key)) return ''.join(items)
def ValidateNetworkTargetV13(targets): """Validate NetworkTarget object. Args: targets: list NetworkTarget objects. Returns: list Updated NetworkTarget objects. """ SanityCheck.ValidateTypes(((targets, list), )) networks = [] for item in targets: SanityCheck.ValidateTypes(((item, (str, unicode)), )) networks.append({'networkTypes': item}) return networks
def ValidateOrder(order): """Validate Order object. Args: order: dict Order object. """ SanityCheck.ValidateTypes(((order, dict), )) for key in order: if order[key] == 'None': continue if key in ('startDateTime', 'endDateTime'): ValidateDateTime(order[key]) elif key in ('totalBudget', ): ValidateMoney(order[key]) else: SanityCheck.ValidateTypes(((order[key], (str, unicode)), ))
def ValidateLanguageTargetV13(targets): """Validate LanguageTarget object. Args: targets: list LanguageTarget objects. Returns: list Updated LanguageTarget objects. """ SanityCheck.ValidateTypes(((targets, list), )) languages = [] for item in targets: SanityCheck.ValidateTypes(((item, (str, unicode)), )) languages.append({'languages': item}) return languages
def DownloadReportToFile(report_job_id, export_format, service, outfile): """Download report data and write to a file. Args: report_job_id: str ID of the report job. export_format: str Export format for the report file. service: GenericDfpService A service pointing to the ReportService. outfile: file the file object to write to. If no file handle is passed in, a temporary file will be created. """ SanityCheck.ValidateTypes(((report_job_id, (str, unicode)),)) # Wait for report to complete. status = service.GetReportJob(report_job_id)[0]['reportJobStatus'] while status != 'COMPLETED' and status != 'FAILED': if Utils.BoolTypeConvert(service._config['debug']): print 'Report job status: %s' % status time.sleep(30) status = service.GetReportJob(report_job_id)[0]['reportJobStatus'] if status == 'FAILED': if Utils.BoolTypeConvert(service._config['debug']): print 'Report process failed' return '' else: if Utils.BoolTypeConvert(service._config['debug']): print 'Report has completed successfully' # Get report download URL. report_url = service.GetReportDownloadURL(report_job_id, export_format)[0] response = urllib2.urlopen(report_url) while True: chunk = response.read(_CHUNK_SIZE) if not chunk: break outfile.write(chunk)
def Get(self, selector): """Return a list of campaign targets. List of campaign targets specified by the selector from the customer's account. Args: selector: dict Filter to run campaign targets through. Returns: tuple List of campaign targets meeting all the criteria of the selector. """ method_name = 'getCampaignTarget' SanityCheck.NewSanityCheck(self._wsdl_types_map, selector, 'CampaignTargetSelector') if self._config['soap_lib'] == SOAPPY: selector = self._message_handler.PackVarAsXml( selector, 'selector', self._wsdl_types_map, False, 'CampaignTargetSelector') return self.__service.CallMethod( method_name.split( self.__class__.__name__.split('Service')[0])[0], (selector)) elif self._config['soap_lib'] == ZSI: selector = self._transformation.MakeZsiCompatible( selector, 'CampaignTargetSelector', self._wsdl_types_map, self._web_services) request = eval('self._web_services.%sRequest()' % method_name) return self.__service.CallMethod(method_name, (({ 'selector': selector }, )), 'CampaignTarget', 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 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 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)