필드 마스크를 사용한 업데이트

Google Ads API에서는 필드 마스크를 사용하여 업데이트가 이루어집니다. 필드 마스크에는 업데이트로 변경하려는 모든 필드가 나열되며, 지정된 필드가 필드 마스크에 없으면 서버로 전송되더라도 무시됩니다.

필드 마스크 도우미

필드 마스크를 생성하는 데 권장되는 방법은 google.api_core 패키지에 포함된 field_mask 도우미 함수를 사용하는 것입니다. 두 protobuf 객체를 허용하고 두 객체 간에 서로 다른 모든 필드가 포함된 paths 목록이 있는 필드 마스크 객체를 반환합니다.

None가 첫 번째 매개변수로 전달되면 필드 마스크 목록에는 기본값으로 설정되지 않은 두 번째 protobuf 객체의 모든 필드가 포함됩니다.

구성된 필드 마스크 객체는 서버로 전송될 작업 객체에 복사해야 합니다.

새 로컬 객체에서 업데이트

다음 예에서는 빈 CampaignOperation 객체를 만들고 update 필드에서 빈 Campaign 객체를 가져옵니다. 그런 다음 해당 캠페인 객체를 수정하고 None와 비교하여 수정된 network_settings.target_search_network 필드가 포함된 필드 마스크를 생성하는 새 필드 마스크를 만듭니다.

from google.ads.googleads.client import GoogleAdsClient
from google.api_core import protobuf_helpers

# Retrieve a GoogleAdsClient instance.
client = GoogleAdsClient.load_from_storage()

# Create a new campaign operation.
campaign_operation = client.get_type("CampaignOperation")

# Retrieve a new campaign object from its update field and set its resource
# name.
campaign = campaign_operation.update
campaign.resource_name = client.get_service("CampaignService").campaign_path(
    customer_id, campaign_id
)

# Mutate the campaign (use direct attribute assignment in proto-plus).
campaign.network_settings.target_search_network = False

# Create a field mask using the updated campaign.
# The field_mask helper is compatible with raw protobuf message instances,
# which you can access using the ._pb attribute.
field_mask = protobuf_helpers.field_mask(None, campaign._pb)

# Copy the field_mask onto the operation's update_mask field.
client.copy_from(campaign_operation.update_mask, field_mask)

기존 리소스 업데이트

다음 예에서는 유효한 resource_name 및 customer_id가 있다고 가정하고 API에서 가져온 기존 캠페인을 업데이트합니다. 이 전략을 사용하면 updated_campaign가 initial_campaign에서 검색된 모든 필드(resource_name 포함)를 공유하고 생성된 필드 마스크는 API에 network_settings.target_search_network 필드만 변경되었음을 알려줍니다.

from google.ads.googleads.client import GoogleAdsClient
from google.api_core import protobuf_helpers

# Retrieve a GoogleAdsClient instance.
client = GoogleAdsClient.load_from_storage()

# Retrieve an instance of the GoogleAdsService.
googleads_service = client.get_service("GoogleAdsService")

# Search query to retrieve the campaign. Quote string literals in GAQL.
query = f"""
    SELECT
      campaign.network_settings.target_search_network,
      campaign.resource_name
    FROM campaign
    WHERE campaign.resource_name = '{resource_name}'"""

# Submit a query to retrieve a campaign instance.
response = googleads_service.search_stream(
    customer_id=customer_id, query=query
)

# Iterate over results to retrieve the campaign.
initial_campaign = None
for batch in response:
    for row in batch.results:
        initial_campaign = row.campaign
        break

if not initial_campaign:
    raise ValueError(f"Campaign '{resource_name}' not found.")

# Create a new campaign operation.
campaign_operation = client.get_type("CampaignOperation")

# Set the copied campaign object to a variable for easy reference.
updated_campaign = campaign_operation.update

# Copy the retrieved campaign into the new campaign.
# client.copy_from works with both native protobuf messages and messages
# wrapped by the proto-plus library.
client.copy_from(updated_campaign, initial_campaign)

# Mutate the new campaign.
updated_campaign.network_settings.target_search_network = False

# Create a field mask by comparing initial and updated protobuf objects.
field_mask = protobuf_helpers.field_mask(
    initial_campaign._pb, updated_campaign._pb
)

# Copy the field mask onto the operation's update_mask field.
# Note that the client's copy_from method works with both native messages
# and messages wrapped by proto-plus, including google.protobuf.field_mask_pb2.
client.copy_from(campaign_operation.update_mask, field_mask)

필드 지우기 또는 빈 메시지 설정

None와 비교할 때 field_mask 도우미는 빈 값이나 기본값으로 설정된 필드를 무시합니다. 필드를 명시적으로 지우거나 빈 메시지 필드를 설정하려면 필드 경로를 campaign_operation.update_mask.paths에 직접 추가합니다. 자세한 내용은 빈 메시지 객체를 필드로 설정을 참고하세요.