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

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

필드 마스크 도우미

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

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

생성되면 필드 마스크 객체를 서버로 전송될 작업 객체에 복사해야 합니다.

새 로컬 객체에서 업데이트

다음 예에서는 빈 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 포함)를 공유하고 생성된 필드 마스크는 network_settings.target_search_network 필드만 변경되었음을 API에 알립니다.

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에 직접 추가합니다. 자세한 내용은 빈 메시지 객체를 필드로 설정을 참고하세요.