def test_field_mask_message_diffs(): original = type_pb2.Type() modified = type_pb2.Type(source_context=source_context_pb2.SourceContext( file_name='name')) assert (protobuf_helpers.field_mask(original, modified).paths == ['source_context.file_name']) original = type_pb2.Type(source_context=source_context_pb2.SourceContext( file_name='name')) modified = type_pb2.Type() assert (protobuf_helpers.field_mask(original, modified).paths == ['source_context']) original = type_pb2.Type(source_context=source_context_pb2.SourceContext( file_name='name')) modified = type_pb2.Type(source_context=source_context_pb2.SourceContext( file_name='other_name')) assert (protobuf_helpers.field_mask(original, modified).paths == ['source_context.file_name']) original = None modified = type_pb2.Type(source_context=source_context_pb2.SourceContext( file_name='name')) assert (protobuf_helpers.field_mask(original, modified).paths == ['source_context.file_name']) original = type_pb2.Type(source_context=source_context_pb2.SourceContext( file_name='name')) modified = None assert (protobuf_helpers.field_mask(original, modified).paths == ['source_context'])
def test_field_mask_repeated_diffs(): original = struct_pb2.ListValue() modified = struct_pb2.ListValue(values=[struct_pb2.Value(number_value=1.0), struct_pb2.Value(number_value=2.0)]) assert protobuf_helpers.field_mask(original, modified).paths == ['values'] original = struct_pb2.ListValue(values=[struct_pb2.Value(number_value=1.0), struct_pb2.Value(number_value=2.0)]) modified = struct_pb2.ListValue() assert protobuf_helpers.field_mask(original, modified).paths == ['values'] original = None modified = struct_pb2.ListValue(values=[struct_pb2.Value(number_value=1.0), struct_pb2.Value(number_value=2.0)]) assert protobuf_helpers.field_mask(original, modified).paths == ['values'] original = struct_pb2.ListValue(values=[struct_pb2.Value(number_value=1.0), struct_pb2.Value(number_value=2.0)]) modified = None assert protobuf_helpers.field_mask(original, modified).paths == ['values'] original = struct_pb2.ListValue(values=[struct_pb2.Value(number_value=1.0), struct_pb2.Value(number_value=2.0)]) modified = struct_pb2.ListValue(values=[struct_pb2.Value(number_value=2.0), struct_pb2.Value(number_value=1.0)]) assert protobuf_helpers.field_mask(original, modified).paths == ['values']
def test_field_mask_message_diffs(): original = type_pb2.Type() modified = type_pb2.Type(source_context=source_context_pb2.SourceContext( file_name='name')) assert (protobuf_helpers.field_mask( original, modified).paths == ['source_context.file_name']) original = type_pb2.Type(source_context=source_context_pb2.SourceContext( file_name='name')) modified = type_pb2.Type() assert (protobuf_helpers.field_mask(original, modified).paths == ['source_context']) original = type_pb2.Type(source_context=source_context_pb2.SourceContext( file_name='name')) modified = type_pb2.Type(source_context=source_context_pb2.SourceContext( file_name='other_name')) assert (protobuf_helpers.field_mask( original, modified).paths == ['source_context.file_name']) original = None modified = type_pb2.Type(source_context=source_context_pb2.SourceContext( file_name='name')) assert (protobuf_helpers.field_mask( original, modified).paths == ['source_context.file_name']) original = type_pb2.Type(source_context=source_context_pb2.SourceContext( file_name='name')) modified = None assert (protobuf_helpers.field_mask(original, modified).paths == ['source_context'])
def test_field_mask_singular_field_diffs(): original = type_pb2.Type(name="name") modified = type_pb2.Type() assert protobuf_helpers.field_mask(original, modified).paths == ["name"] original = type_pb2.Type(name="name") modified = type_pb2.Type() assert protobuf_helpers.field_mask(original, modified).paths == ["name"] original = None modified = type_pb2.Type(name="name") assert protobuf_helpers.field_mask(original, modified).paths == ["name"] original = type_pb2.Type(name="name") modified = None assert protobuf_helpers.field_mask(original, modified).paths == ["name"]
def _update_targeting_setting(client, customer_id, ad_group_id, targeting_setting): """Updates the given TargetingSetting of an ad group. Args: client: The Google Ads client. customer_id: The Google Ads customer ID. ad_group_id: The ad group ID for which to update the audience targeting restriction. targeting_setting: The updated targeting setting. """ # Get the AdGroupService client. ad_group_service = client.get_service("AdGroupService", version="v6") # Construct an operation that will update the ad group. ad_group_operation = client.get_type("AdGroupOperation", version="v6") # Populate the ad group object with the updated targeting setting. ad_group = ad_group_operation.update ad_group.resource_name = ad_group_service.ad_group_path( customer_id, ad_group_id) ad_group.targeting_setting.target_restrictions.extend( targeting_setting.target_restrictions) # Use the field_mask utility to derive the update mask. This mask tells the # Google Ads API which attributes of the ad group you want to change. ad_group_operation.update_mask.CopyFrom( protobuf_helpers.field_mask(None, ad_group)) # Send the operation in a mutate request and print the resource name of the # updated object. mutate_ad_groups_response = ad_group_service.mutate_ad_groups( customer_id, [ad_group_operation]) print("Updated targeting setting of ad group with resource name " f"'{mutate_ad_groups_response.results[0].resource_name}'; set the " "audience target restriction to 'Observation'.")
def test_field_mask_different_level_diffs(): original = color_pb2.Color(alpha=wrappers_pb2.FloatValue(value=1.0)) modified = color_pb2.Color(alpha=wrappers_pb2.FloatValue(value=2.0), red=1.0) assert sorted(protobuf_helpers.field_mask(original, modified).paths) == [ "alpha", "red", ]
def _modify_user_access(client, customer_id, user_id, access_role): """Modifies the user access role to a specified value. Args: client: The Google Ads client. customer_id: The customer ID. user_id: ID of the user whose access role is being modified. access_role: The updated access role. """ customer_user_access_service = client.get_service( "CustomerUserAccessService") customer_user_access_op = client.get_type("CustomerUserAccessOperation") access_role_enum = client.enums.AccessRoleEnum customer_user_access = customer_user_access_op.update customer_user_access.resource_name = ( customer_user_access_service.customer_user_access_path( customer_id, user_id)) customer_user_access.access_role = getattr(access_role_enum, access_role) client.copy_from( customer_user_access_op.update_mask, protobuf_helpers.field_mask(None, customer_user_access._pb), ) response = customer_user_access_service.mutate_customer_user_access( customer_id=customer_id, operation=customer_user_access_op) print("Successfully modified customer user access with resource name: " f"{response.result.resource_name}.")
def _attach_cross_account_bidding_strategy_to_campaign( client, customer_id, campaign_id, bidding_strategy_resource_name): """Attaches the cross-account bidding strategy to the given campaign. Args: client: An initialized GoogleAdsClient instance. customer_id: A client customer ID. campaign_id: The ID of an existing campaign in the client customer's account. bidding_strategy_resource_name: The ID of a bidding strategy """ campaign_service = client.get_service("CampaignService") bidding_strategy_service = client.get_service("BiddingStrategyService") campaign_operation = client.get_type("CampaignOperation") campaign = campaign_operation.update campaign.resource_name = campaign_service.campaign_path( customer_id, campaign_id) campaign.bidding_strategy = bidding_strategy_resource_name campaign_operation.update_mask = protobuf_helpers.field_mask( None, campaign._pb) # Sends the operation in a mutate request. response = campaign_service.mutate_campaigns( customer_id=customer_id, operations=[campaign_operation]) # Prints the resource name of the updated campaign. print("Updated campaign with resource name: " f"'{response.results[0].resource_name}'")
def _create_conversion_goal_operations( client, customer_id, customer_conversion_goals, ): """Creates a list of MutateOperations that override customer conversion goals. Args: client: an initialized GoogleAdsClient instance. customer_id: a client customer ID. customer_conversion_goals: the list of customer conversion goals that will be overridden. Returns: MutateOperations that update campaign conversion goals. """ campaign_conversion_goal_service = client.get_service( "CampaignConversionGoalService") operations = [] # To override the customer conversion goals, we will change the # biddability of each of the customer conversion goals so that only # the desired conversion goal is biddable in this campaign. for customer_conversion_goal in customer_conversion_goals: mutate_operation = client.get_type("MutateOperation") campaign_conversion_goal = ( mutate_operation.campaign_conversion_goal_operation.update) campaign_conversion_goal.resource_name = ( campaign_conversion_goal_service.campaign_conversion_goal_path( customer_id, _PERFORMANCE_MAX_CAMPAIGN_TEMPORARY_ID, customer_conversion_goal["category"].name, customer_conversion_goal["origin"].name, )) # Change the biddability for the campaign conversion goal. # Set biddability to True for the desired (category, origin). # Set biddability to False for all other conversion goals. # Note: # 1- It is assumed that this Conversion Action # (category=PURCHASE, origin=WEBSITE) exists in this account. # 2- More than one goal can be biddable if desired. This example # shows only one. if (customer_conversion_goal["category"] == client.enums.ConversionActionCategoryEnum.PURCHASE and customer_conversion_goal["origin"] == client.enums.ConversionOriginEnum.WEBSITE): biddable = True else: biddable = False campaign_conversion_goal.biddable = biddable field_mask = protobuf_helpers.field_mask(None, campaign_conversion_goal._pb) client.copy_from( mutate_operation.campaign_conversion_goal_operation.update_mask, field_mask, ) operations.append(mutate_operation) return operations
def test_field_mask_singular_field_diffs(): original = type_pb2.Type(name='name') modified = type_pb2.Type() assert (protobuf_helpers.field_mask(original, modified).paths == ['name']) original = type_pb2.Type(name='name') modified = type_pb2.Type() assert (protobuf_helpers.field_mask(original, modified).paths == ['name']) original = None modified = type_pb2.Type(name='name') assert (protobuf_helpers.field_mask(original, modified).paths == ['name']) original = type_pb2.Type(name='name') modified = None assert (protobuf_helpers.field_mask(original, modified).paths == ['name'])
def main(client, customer_id, ad_id): ad_service = client.get_service("AdService", version="v5") ad_operation = client.get_type("AdOperation", version="v5") # Update ad operation. ad = ad_operation.update ad.resource_name = ad_service.ad_path(customer_id, ad_id) ad.expanded_text_ad.headline_part1 = ( f"Cruise to Pluto {str(uuid.uuid4())[:8]}") ad.expanded_text_ad.headline_part2 = "Tickets on sale now" ad.expanded_text_ad.description = "Best space cruise ever." ad.final_urls.append("http://www.example.com") ad.final_mobile_urls.append("http://www.example.com/mobile") fm = protobuf_helpers.field_mask(None, ad) ad_operation.update_mask.CopyFrom(fm) # Updates the ad. try: ad_response = ad_service.mutate_ads(customer_id, [ad_operation]) except GoogleAdsException as ex: print(f'Request with ID "{ex.request_id}" failed with status ' f'"{ex.error.code().name}" and includes the following errors:') for error in ex.failure.errors: print(f'\tError with message "{error.message}".') if error.location: for field_path_element in error.location.field_path_elements: print(f"\t\tOn field: {field_path_element.field_name}") sys.exit(1) print(f'Ad with resource name "{ad_response.results[0].resource_name}" ' "was updated.")
def main(client, customer_id, ad_group_id, criterion_id): agc_service = client.get_service('AdGroupCriterionService', version='v2') ad_group_criterion_operation = client.get_type('AdGroupCriterionOperation', version='v2') ad_group_criterion = ad_group_criterion_operation.update ad_group_criterion.resource_name = agc_service.ad_group_criteria_path( customer_id, ResourceName.format_composite(ad_group_id, criterion_id)) ad_group_criterion.status = (client.get_type('AdGroupCriterionStatusEnum', version='v2').ENABLED) final_url = ad_group_criterion.final_urls.add() final_url.value = 'https://www.example.com' fm = protobuf_helpers.field_mask(None, ad_group_criterion) ad_group_criterion_operation.update_mask.CopyFrom(fm) try: agc_response = agc_service.mutate_ad_group_criteria( customer_id, [ad_group_criterion_operation]) except google.ads.google_ads.errors.GoogleAdsException as ex: print('Request with ID "%s" failed with status "%s" and includes the ' 'following errors:' % (ex.request_id, ex.error.code().name)) for error in ex.failure.errors: print('\tError with message "%s".' % error.message) if error.location: for field_path_element in error.location.field_path_elements: print('\t\tOn field: %s' % field_path_element.field_name) sys.exit(1) print('Updated keyword %s.' % agc_response.results[0].resource_name)
def main(client, customer_id, campaign_id, criterion_id, bid_modifier_value): campaign_criterion_service = client.get_service("CampaignCriterionService") criterion_rname = campaign_criterion_service.campaign_criterion_path( customer_id, campaign_id, criterion_id ) campaign_criterion_operation = client.get_type("CampaignCriterionOperation") campaign_criterion = campaign_criterion_operation.update campaign_criterion.resource_name = criterion_rname campaign_criterion.bid_modifier = bid_modifier_value client.copy_from( campaign_criterion_operation.update_mask, protobuf_helpers.field_mask(None, campaign_criterion._pb), ) campaign_criterion_response = ( campaign_criterion_service.mutate_campaign_criteria( customer_id=customer_id, operations=[campaign_criterion_operation], ) ) print( "Campaign criterion with resource name " f'"{campaign_criterion_response.results[0].resource_name}" was ' "modified." )
def main(client, customer_id, ad_group_id, ad_id): ad_group_ad_service = client.get_service("AdGroupAdService", version="v6") ad_group_ad_operation = client.get_type("AdGroupAdOperation", version="v6") ad_group_ad = ad_group_ad_operation.update ad_group_ad.resource_name = ad_group_ad_service.ad_group_ad_path( customer_id, ad_group_id, ad_id) ad_group_ad.status = client.get_type("AdGroupStatusEnum", version="v6").PAUSED fm = protobuf_helpers.field_mask(None, ad_group_ad) ad_group_ad_operation.update_mask.CopyFrom(fm) try: ad_group_ad_response = ad_group_ad_service.mutate_ad_group_ads( customer_id, [ad_group_ad_operation]) except GoogleAdsException as ex: print('Request with ID "%s" failed with status "%s" and includes the ' "following errors:" % (ex.request_id, ex.error.code().name)) for error in ex.failure.errors: print('\tError with message "%s".' % error.message) if error.location: for field_path_element in error.location.field_path_elements: print("\t\tOn field: %s" % field_path_element.field_name) sys.exit(1) print("Paused ad group ad %s." % ad_group_ad_response.results[0].resource_name)
def main(client, customer_id, campaign_id, criterion_id, bid_modifier_value): campaign_criterion_service = client.get_service('CampaignCriterionService', version='v4') criterion_rname = campaign_criterion_service.campaign_criteria_path( customer_id, f'{campaign_id}~{criterion_id}') campaign_criterion_operation = client.get_type( 'CampaignCriterionOperation', version='v4') campaign_criterion = campaign_criterion_operation.update campaign_criterion.resource_name = criterion_rname campaign_criterion.bid_modifier.value = bid_modifier_value fm = protobuf_helpers.field_mask(None, campaign_criterion) campaign_criterion_operation.update_mask.CopyFrom(fm) try: campaign_criterion_response = ( campaign_criterion_service.mutate_campaign_criteria( customer_id, [campaign_criterion_operation])) except GoogleAdsException as ex: print(f'Request with ID "{ex.request_id}" failed with status ' f'"{ex.error.code().name}" and includes the following errors:') for error in ex.failure.errors: print(f'\tError with message "{error.message}".') if error.location: for field_path_element in error.location.field_path_elements: print(f'\t\tOn field: {field_path_element.field_name}') sys.exit(1) print('Campaign criterion with resource name ' f'"{campaign_criterion_response.results[0].resource_name}" was ' 'modified.')
def _modify_campaign_bids(client, customer_id, campaign_criterion_resource_name, bid_modifier_value): """Updates the bid modifier on a campaign criterion. Args: client: an initialized GoogleAdsClient instance. customer_id: a str client customer ID. campaign_criterion_resource_name: a str resource name for a campaign criterion. bid_modifier_value: a float value specifying a campaign criterion bid modifier. """ # Constructs an operation that will update the campaign criterion with the # specified resource name. campaign_criterion_operation = client.get_type( "CampaignCriterionOperation") campaign_criterion = campaign_criterion_operation.update campaign_criterion.resource_name = campaign_criterion_resource_name campaign_criterion.bid_modifier = bid_modifier_value # Using the FieldMasks utility to derive the update mask tells the Google # Ads API which attributes of the campaign criterion you want to change. client.copy_from( campaign_criterion_operation.update_mask, protobuf_helpers.field_mask(None, campaign_criterion._pb), ) campaign_criterion_service = client.get_service("CampaignCriterionService") response = campaign_criterion_service.mutate_campaign_criteria( customer_id=customer_id, operations=[campaign_criterion_operation]) print("Successfully updated the bid for campaign criterion with resource " f"name: '{response.results[0].resource_name}'")
def main(client, customer_id, ad_group_id, bid_micro_amount): ad_group_service = client.get_service('AdGroupService', version='v1') # Create ad group operation. ad_group_operation = client.get_type('AdGroupOperation', version='v1') ad_group = ad_group_operation.update ad_group.resource_name = ad_group_service.ad_group_path( customer_id, ad_group_id) ad_group.status = client.get_type('AdGroupStatusEnum', version='v1').PAUSED ad_group.cpc_bid_micros.value = bid_micro_amount fm = protobuf_helpers.field_mask(None, ad_group) ad_group_operation.update_mask.CopyFrom(fm) # Update the ad group. try: ad_group_response = ad_group_service.mutate_ad_groups( customer_id, [ad_group_operation]) except google.ads.google_ads.errors.GoogleAdsException as ex: print('Request with ID "%s" failed with status "%s" and includes the ' 'following errors:' % (ex.request_id, ex.error.code().name)) for error in ex.failure.errors: print('\tError with message "%s".' % error.message) if error.location: for field_path_element in error.location.field_path_elements: print('\t\tOn field: %s' % field_path_element.field_name) sys.exit(1) print('Updated ad group %s.' % ad_group_response.results[0].resource_name)
def _update_merchant_center_link_status( client, customer_id, merchant_center_link_service, merchant_center_link, status, ): """Updates the status of a Merchant Center link request. Args: client: An initialized GoogleAdsClient instance. customer_id: The client customer ID string. merchant_center_link_service: A merchant center link service instance. merchant_center_link: The merchant center link to be modified. status: The updated status to apply to the merchant center link. """ # Creates an operation. operation = client.get_type("MerchantCenterLinkOperation") link_to_update = operation.update link_to_update.resource_name = merchant_center_link.resource_name # Enables the pending link. link_to_update.status = status client.copy_from( operation.update_mask, protobuf_helpers.field_mask(None, link_to_update._pb), ) # Updates the link. mutate_response = merchant_center_link_service.mutate_merchant_center_link( customer_id=customer_id, operation=operation) # Displays the result. print("The status of Merchant Center Link with resource name " f"'{mutate_response.result.resource_name}' to Google Ads account : " f"{customer_id} was updated to {status.name}.")
def main(client, customer_id, ad_id): ad_service = client.get_service("AdService") ad_operation = client.get_type("AdOperation") # Update ad operation. ad = ad_operation.update ad.resource_name = ad_service.ad_path(customer_id, ad_id) ad.expanded_text_ad.headline_part1 = ( f"Cruise to Pluto {str(uuid.uuid4())[:8]}" ) ad.expanded_text_ad.headline_part2 = "Tickets on sale now" ad.expanded_text_ad.description = "Best space cruise ever." ad.final_urls.append("http://www.example.com") ad.final_mobile_urls.append("http://www.example.com/mobile") client.copy_from( ad_operation.update_mask, protobuf_helpers.field_mask(None, ad._pb) ) # Updates the ad. ad_response = ad_service.mutate_ads( customer_id=customer_id, operations=[ad_operation] ) print( f'Ad with resource name "{ad_response.results[0].resource_name}" ' "was updated." )
def main(client, customer_id, ad_group_id, criterion_id): agc_service = client.get_service("AdGroupCriterionService", version="v6") ad_group_criterion_operation = client.get_type("AdGroupCriterionOperation", version="v6") ad_group_criterion = ad_group_criterion_operation.update ad_group_criterion.resource_name = agc_service.ad_group_criterion_path( customer_id, ad_group_id, criterion_id) ad_group_criterion.status = client.get_type("AdGroupCriterionStatusEnum", version="v6").ENABLED al_url = ad_group_criterion.final_urls.append("https://www.example.com") fm = protobuf_helpers.field_mask(None, ad_group_criterion) ad_group_criterion_operation.update_mask.CopyFrom(fm) try: agc_response = agc_service.mutate_ad_group_criteria( customer_id, [ad_group_criterion_operation]) except google.ads.google_ads.errors.GoogleAdsException as ex: print('Request with ID "%s" failed with status "%s" and includes the ' "following errors:" % (ex.request_id, ex.error.code().name)) for error in ex.failure.errors: print('\tError with message "%s".' % error.message) if error.location: for field_path_element in error.location.field_path_elements: print("\t\tOn field: %s" % field_path_element.field_name) sys.exit(1) print("Updated keyword %s." % agc_response.results[0].resource_name)
def main(client, customer_id, feed_item_id, sitelink_text): """The main method that creates all necessary entities for the example. Args: client: an initialized GoogleAdsClient instance. customer_id: a client customer ID. feed_item_id: the ID of an extension feed item. sitelink_text: the updated sitelink text. """ extension_feed_item_service = client.get_service( "ExtensionFeedItemService") extension_feed_item_operation = client.get_type( "ExtensionFeedItemOperation") extension_feed_item = extension_feed_item_operation.update # Update the extension feed item using the specified feed item ID extension_feed_item.resource_name = extension_feed_item_service.extension_feed_item_path( customer_id, feed_item_id) extension_feed_item.sitelink_feed_item.link_text = sitelink_text # Produce a field mask enumerating the changed fields client.copy_from( extension_feed_item_operation.update_mask, protobuf_helpers.field_mask(None, extension_feed_item._pb), ) # Update the extension feed item response = extension_feed_item_service.mutate_extension_feed_items( customer_id=customer_id, operations=[extension_feed_item_operation]) print("Updated extension feed item with resource name: " f'"{response.results[0].resource_name}".')
def main(client, customer_id, feed_item_id, geo_target_constant_id): """The main method that creates all necessary entities for the example. Args: client: an initialized GoogleAdsClient instance. customer_id: a client customer ID. feed_item_id: the ID of an extension feed item. geo_target_constant_id: the geo target constant ID to add to the extension feed item. """ extension_feed_item_service = client.get_service( "ExtensionFeedItemService") extension_feed_item_operation = client.get_type( "ExtensionFeedItemOperation") extension_feed_item = extension_feed_item_operation.update # Creates an extension feed item using the specified feed item ID and # geo target constant ID for targeting. extension_feed_item.resource_name = ( extension_feed_item_service.extension_feed_item_path( customer_id, feed_item_id)) extension_feed_item.targeted_geo_target_constant = client.get_service( "GeoTargetConstantService").geo_target_constant_path( geo_target_constant_id) client.copy_from( extension_feed_item_operation.update_mask, protobuf_helpers.field_mask(None, extension_feed_item._pb), ) response = extension_feed_item_service.mutate_extension_feed_items( customer_id=customer_id, operations=[extension_feed_item_operation]) print("Updated extension feed item with resource name: " f"'{response.results[0].resource_name}'.")
def main(client, customer_id, campaign_id): campaign_service = client.get_service('CampaignService', version='v4') # Create campaign operation. campaign_operation = client.get_type('CampaignOperation', version='v4') campaign = campaign_operation.update campaign.resource_name = campaign_service.campaign_path( customer_id, campaign_id) campaign.status = client.get_type('CampaignStatusEnum', version='v4').PAUSED campaign.network_settings.target_search_network.value = False # Retrieve a FieldMask for the fields configured in the campaign. fm = protobuf_helpers.field_mask(None, campaign) campaign_operation.update_mask.CopyFrom(fm) # Update the campaign. try: campaign_response = campaign_service.mutate_campaigns( customer_id, [campaign_operation]) except google.ads.google_ads.errors.GoogleAdsException as ex: print('Request with ID "%s" failed with status "%s" and includes the ' 'following errors:' % (ex.request_id, ex.error.code().name)) for error in ex.failure.errors: print('\tError with message "%s".' % error.message) if error.location: for field_path_element in error.location.field_path_elements: print('\t\tOn field: %s' % field_path_element.field_name) sys.exit(1) print('Updated campaign %s.' % campaign_response.results[0].resource_name)
def main(client, customer_id, campaign_id): campaign_service = client.get_service("CampaignService") # Create campaign operation. campaign_operation = client.get_type("CampaignOperation") campaign = campaign_operation.update campaign.resource_name = campaign_service.campaign_path( customer_id, campaign_id ) campaign_status_enum = client.get_type( "CampaignStatusEnum" ).CampaignStatus.PAUSED campaign.network_settings.target_search_network = False # Retrieve a FieldMask for the fields configured in the campaign. client.copy_from( campaign_operation.update_mask, protobuf_helpers.field_mask(None, campaign._pb), ) campaign_response = campaign_service.mutate_campaigns( customer_id=customer_id, operations=[campaign_operation] ) print(f"Updated campaign {campaign_response.results[0].resource_name}.")
def _modify_ad_group_bids(client, customer_id, ad_group_criterion_resource_name, bid_modifier_value): """Updates the bid modifier on an ad group criterion. Args: client: an initialized GoogleAdsClient instance. customer_id: a str client customer ID. ad_group_criterion_resoure_name: a str resource name for an ad group criterion. bid_modifier_value: a float value specifying an ad group criterion bid modifier. """ # Constructs an operation that will update the ad group criterion with the # specified resource name. ad_group_criterion_operation = client.get_type("AdGroupCriterionOperation") ad_group_criterion = ad_group_criterion_operation.update # Creates the ad group criterion with a bid modifier. You may alternatively # set the bid for the ad group criterion directly. ad_group_criterion.resource_name = ad_group_criterion_resource_name ad_group_criterion.bid_modifier = bid_modifier_value # Using the FieldMasks utility to derive the update mask tells the Google # Ads API which attributes of the ad group criterion you want to change. client.copy_from( ad_group_criterion_operation.update_mask, protobuf_helpers.field_mask(None, ad_group_criterion._pb), ) ad_group_criterion_service = client.get_service("AdGroupCriterionService") response = ad_group_criterion_service.mutate_ad_group_criteria( customer_id=customer_id, operations=[ad_group_criterion_operation]) print("Updated bid for ad group criterion with resource name: " f"'{response.results[0].resource_name}'")
def main(client, customer_id, ad_group_id, cpc_bid_micro_amount): ad_group_service = client.get_service("AdGroupService", version="v6") # Create ad group operation. ad_group_operation = client.get_type("AdGroupOperation", version="v6") ad_group = ad_group_operation.update ad_group.resource_name = ad_group_service.ad_group_path( customer_id, ad_group_id) ad_group.status = client.get_type("AdGroupStatusEnum", version="v6").PAUSED ad_group.cpc_bid_micros = cpc_bid_micro_amount fm = protobuf_helpers.field_mask(None, ad_group) ad_group_operation.update_mask.CopyFrom(fm) # Update the ad group. try: ad_group_response = ad_group_service.mutate_ad_groups( customer_id, [ad_group_operation]) except GoogleAdsException as ex: print(f'Request with ID "{ex.request_id}" failed with status ' f'"{ex.error.code().name}" and includes the following errors:') for error in ex.failure.errors: print(f'\tError with message "{error.message}".') if error.location: for field_path_element in error.location.field_path_elements: print(f"\t\tOn field: {field_path_element.field_name}") sys.exit(1) print(f"Updated ad group {ad_group_response.results[0].resource_name}.")
def main(client, customer_id, feed_id, feed_item_id, flight_placeholder_field_name): """Removes a feed item attribute value of a feed item in a flights feed. Args: client: An initialized GoogleAdsClient instance. customer_id: The Google Ads customer ID. feed_id: The feed ID to which the feed item belongs. feed_item_id: The ID of the feed item to be updated. flight_placeholder_field_name: The flight placeholder field name for the attribute to be removed. """ # Get the FeedItemService client. feed_item_service = client.get_service("FeedItemService", version="v6") # Create the FeedItemOperation. feed_item_operation = client.get_type("FeedItemOperation", version="v6") feed_item = feed_item_operation.update try: # Get a map of the FlightPlaceholderFields to FeedAttributes. placeholders_to_feed_attributes_map = _get_feed( client, customer_id, feed_id) # Remove the attribute from the feed item. flight_placeholder_field = client.get_type( "FlightPlaceholderFieldEnum", version="v6").FlightPlaceholderField.Value( flight_placeholder_field_name) feed_item.CopyFrom( _remove_attribute_value_from_feed_item( client, customer_id, feed_id, feed_item_id, placeholders_to_feed_attributes_map, flight_placeholder_field, )) # Configure the operation. field_mask = protobuf_helpers.field_mask(None, feed_item) feed_item_operation.update_mask.CopyFrom(field_mask) # Update the feed item and print the results. response = feed_item_service.mutate_feed_items(customer_id, [feed_item_operation]) for result in response.results: print("Updated feed item with resource name: " f"'{result.resource_name}'.") except GoogleAdsException as ex: print(f'Request with ID "{ex.request_id}" failed with status ' f'"{ex.error.code().name}" and includes the following errors:') for error in ex.failure.errors: print(f'\tError with message "{error.message}".') if error.location: for field_path_element in error.location.field_path_elements: print(f"\t\tOn field: {field_path_element.field_name}") sys.exit(1)
def update_campaign_dsa_setting(client, customer_id, campaign_id, feed_details): """Updates the given campaign with the given feed details Args: client: an initialized GoogleAdsClient instance. customer_id: a client customer ID str. campaign_id: a campaign ID str; feed_details: a FeedDetails instance with feed attribute information. """ query = ''' SELECT campaign.id, campaign.name, campaign.dynamic_search_ads_setting.domain_name FROM campaign WHERE campaign.id = {} LIMIT 1 '''.format(campaign_id) ga_service = client.get_service('GoogleAdsService', version='v2') results = ga_service.search(customer_id, query=query) for row in results: campaign = row.campaign if not campaign: raise ValueError('Campaign with id #{} not found'.format(campaign_id)) if not campaign.dynamic_search_ads_setting.domain_name: raise ValueError( 'Campaign id #{} is not set up for Dynamic Search Ads.'.format( campaign_id)) # Retrieve a new campaign operation campaign_operation = client.get_type('CampaignOperation', version='v2') # Copy the retrieved campaign onto the new campaign operation. campaign_operation.update.CopyFrom(campaign) updated_campaign = campaign_operation.update feed = updated_campaign.dynamic_search_ads_setting.feeds.add() # Use a page feed to specify precisely which URLs to use with your Dynamic # Search ads. feed.value = feed_details.resource_name field_mask = protobuf_helpers.field_mask(campaign, updated_campaign) campaign_operation.update_mask.CopyFrom(field_mask) # Retrieve the campaign service. campaign_service = client.get_service('CampaignService', version='v2') # Submit the campaign operation and update the campaign. response = campaign_service.mutate_campaigns(customer_id, [campaign_operation]) resource_name = response.results[0].resource_name # Display the results. print('Updated campaign #{}'.format(resource_name))
def test_field_mask_equal_values(): assert protobuf_helpers.field_mask(None, None).paths == [] original = struct_pb2.Value(number_value=1.0) modified = struct_pb2.Value(number_value=1.0) assert protobuf_helpers.field_mask(original, modified).paths == [] original = color_pb2.Color(alpha=wrappers_pb2.FloatValue(value=1.0)) modified = color_pb2.Color(alpha=wrappers_pb2.FloatValue(value=1.0)) assert protobuf_helpers.field_mask(original, modified).paths == [] original = struct_pb2.ListValue(values=[struct_pb2.Value(number_value=1.0)]) modified = struct_pb2.ListValue(values=[struct_pb2.Value(number_value=1.0)]) assert protobuf_helpers.field_mask(original, modified).paths == [] original = struct_pb2.Struct(fields={"bar": struct_pb2.Value(number_value=1.0)}) modified = struct_pb2.Struct(fields={"bar": struct_pb2.Value(number_value=1.0)}) assert protobuf_helpers.field_mask(original, modified).paths == []
def get_operation(client, service, customer_id, campaign_id, is_pause): operation = client.get_type('CampaignOperation', version='v10') campaign = operation.update campaign.resource_name = service.campaign_path(customer_id, campaign_id) enum = client.get_type('CampaignStatusEnum', version='v10') campaign.status = enum.PAUSED if is_pause else enum.ENABLED operation.update_mask.CopyFrom(protobuf_helpers.field_mask(None, campaign)) return operation
def test_field_mask_wrapper_type_diffs(): original = color_pb2.Color() modified = color_pb2.Color(alpha=wrappers_pb2.FloatValue(value=1.0)) assert protobuf_helpers.field_mask(original, modified).paths == ['alpha'] original = color_pb2.Color(alpha=wrappers_pb2.FloatValue(value=1.0)) modified = color_pb2.Color() assert (protobuf_helpers.field_mask(original, modified).paths == ['alpha']) original = color_pb2.Color(alpha=wrappers_pb2.FloatValue(value=1.0)) modified = color_pb2.Color(alpha=wrappers_pb2.FloatValue(value=2.0)) assert (protobuf_helpers.field_mask(original, modified).paths == ['alpha']) original = None modified = color_pb2.Color(alpha=wrappers_pb2.FloatValue(value=2.0)) assert (protobuf_helpers.field_mask(original, modified).paths == ['alpha']) original = color_pb2.Color(alpha=wrappers_pb2.FloatValue(value=1.0)) modified = None assert (protobuf_helpers.field_mask(original, modified).paths == ['alpha'])
def test_field_mask_wrapper_type_diffs(): original = color_pb2.Color() modified = color_pb2.Color(alpha=wrappers_pb2.FloatValue(value=1.0)) assert protobuf_helpers.field_mask(original, modified).paths == ["alpha"] original = color_pb2.Color(alpha=wrappers_pb2.FloatValue(value=1.0)) modified = color_pb2.Color() assert protobuf_helpers.field_mask(original, modified).paths == ["alpha"] original = color_pb2.Color(alpha=wrappers_pb2.FloatValue(value=1.0)) modified = color_pb2.Color(alpha=wrappers_pb2.FloatValue(value=2.0)) assert protobuf_helpers.field_mask(original, modified).paths == ["alpha"] original = None modified = color_pb2.Color(alpha=wrappers_pb2.FloatValue(value=2.0)) assert protobuf_helpers.field_mask(original, modified).paths == ["alpha"] original = color_pb2.Color(alpha=wrappers_pb2.FloatValue(value=1.0)) modified = None assert protobuf_helpers.field_mask(original, modified).paths == ["alpha"]
def _create_smart_campaign_setting_operation(client, customer_id, business_location_id, business_name): """Creates a MutateOperation to create a new SmartCampaignSetting. SmartCampaignSettings are unique in that they only support UPDATE operations, which are used to update and create them. Below we will use a temporary ID in the resource name to associate it with the campaign created in the previous step. Args: client: an initialized GoogleAdsClient instance. customer_id: a client customer ID. business_location_id: the ID of a Business Profile location. business_name: the name of a Business Profile. Returns: a MutateOperation that creates a SmartCampaignSetting. """ mutate_operation = client.get_type("MutateOperation") smart_campaign_setting = ( mutate_operation.smart_campaign_setting_operation.update) # Set a temporary ID in the campaign setting's resource name to associate it # with the campaign created in the previous step. smart_campaign_setting.resource_name = client.get_service( "SmartCampaignSettingService").smart_campaign_setting_path( customer_id, _SMART_CAMPAIGN_TEMPORARY_ID) # Below we configure the SmartCampaignSetting using many of the same # details used to generate a budget suggestion. smart_campaign_setting.phone_number.country_code = _COUNTRY_CODE smart_campaign_setting.phone_number.phone_number = _PHONE_NUMBER smart_campaign_setting.final_url = _LANDING_PAGE_URL smart_campaign_setting.advertising_language_code = _LANGUAGE_CODE # Set either of the business_location_id or business_name, depending on # whichever is provided. if business_location_id: smart_campaign_setting.business_location_id = ( _convert_business_location_id(business_location_id)) else: smart_campaign_setting.business_name = business_name # Set the update mask on the operation. This is required since the smart # campaign setting is created in an UPDATE operation. Here the update # mask will be a list of all the fields that were set on the # SmartCampaignSetting. client.copy_from( mutate_operation.smart_campaign_setting_operation.update_mask, protobuf_helpers.field_mask(None, smart_campaign_setting._pb), ) return mutate_operation
def test_field_mask_invalid_args(): with pytest.raises(ValueError): protobuf_helpers.field_mask('foo', any_pb2.Any()) with pytest.raises(ValueError): protobuf_helpers.field_mask(any_pb2.Any(), 'bar') with pytest.raises(ValueError): protobuf_helpers.field_mask(any_pb2.Any(), operations_pb2.Operation())
def test_field_mask_map_diffs(): original = struct_pb2.Struct() modified = struct_pb2.Struct( fields={'foo': struct_pb2.Value(number_value=1.0)}) assert protobuf_helpers.field_mask(original, modified).paths == ['fields'] original = struct_pb2.Struct( fields={'foo': struct_pb2.Value(number_value=1.0)}) modified = struct_pb2.Struct() assert protobuf_helpers.field_mask(original, modified).paths == ['fields'] original = None modified = struct_pb2.Struct( fields={'foo': struct_pb2.Value(number_value=1.0)}) assert protobuf_helpers.field_mask(original, modified).paths == ['fields'] original = struct_pb2.Struct( fields={'foo': struct_pb2.Value(number_value=1.0)}) modified = None assert protobuf_helpers.field_mask(original, modified).paths == ['fields'] original = struct_pb2.Struct( fields={'foo': struct_pb2.Value(number_value=1.0)}) modified = struct_pb2.Struct( fields={'foo': struct_pb2.Value(number_value=2.0)}) assert protobuf_helpers.field_mask(original, modified).paths == ['fields'] original = struct_pb2.Struct( fields={'foo': struct_pb2.Value(number_value=1.0)}) modified = struct_pb2.Struct( fields={'bar': struct_pb2.Value(number_value=1.0)}) assert protobuf_helpers.field_mask(original, modified).paths == ['fields']
def test_field_mask_zero_values(): # Singular Values original = color_pb2.Color(red=0.0) modified = None assert protobuf_helpers.field_mask(original, modified).paths == [] original = None modified = color_pb2.Color(red=0.0) assert protobuf_helpers.field_mask(original, modified).paths == [] # Repeated Values original = struct_pb2.ListValue(values=[]) modified = None assert protobuf_helpers.field_mask(original, modified).paths == [] original = None modified = struct_pb2.ListValue(values=[]) assert protobuf_helpers.field_mask(original, modified).paths == [] # Maps original = struct_pb2.Struct(fields={}) modified = None assert protobuf_helpers.field_mask(original, modified).paths == [] original = None modified = struct_pb2.Struct(fields={}) assert protobuf_helpers.field_mask(original, modified).paths == [] # Oneofs original = struct_pb2.Value(number_value=0.0) modified = None assert protobuf_helpers.field_mask(original, modified).paths == [] original = None modified = struct_pb2.Value(number_value=0.0) assert protobuf_helpers.field_mask(original, modified).paths == []