Protobuf 메시지

버전 14.0.0 드림 새로운 필수 구성 매개변수 도입 라이브러리에서 반환 여부를 지정하는 use_proto_plus proto-plus 메시지 또는 protobuf 메시지. 자세한 내용은 이 매개변수를 설정하는 방법은 구성 문서를 참조하세요.

이 섹션에서는 충분히 읽고 이해하는 것이 좋습니다. 정보에 입각한 결정을 내리기 위해 여러 옵션이 제공됩니다. 그러나 코드를 변경하지 않고 14.0.0 버전으로 업그레이드하는 경우 use_proto_plus에서 True로: 인터페이스가 브레이킹되는 것을 방지합니다.

Proto-plus 메시지와 protobuf 메시지 비교

10.0.0 버전에서 Python 클라이언트 라이브러리가 새 코드 생성기로 마이그레이션되었습니다. Google Cloud의 proto-plus를 더 많이 동작하도록 하여 protobuf 메시지 인터페이스의 인체공학을 개선합니다. 기본 Python 객체와 같은 객체입니다. 이러한 개선의 단점은 proto-plus 성능 오버헤드가 발생합니다

Proto+ 성능

proto-plus의 핵심 이점 중 하나는 protobuf를 메시지 잘 알려진 유형을 사용하여 기본 Python 유형을 type'이라는 프로세스를 통해 마샬링(marshaling)을 제공합니다.

마샬링은 proto-plus 메시지 인스턴스에서 필드가 액세스될 때 발생합니다. 특히 필드가 읽히거나 설정된 경우(예: protobuf) 정의:

syntax = "proto3";

message Dog {
  string name = 1;
}

이 정의가 proto-plus 클래스로 변환되면 :

import proto

class Dog(proto.Message):
    name = proto.Field(proto.STRING, number=1)

그런 다음 평소와 같이 Dog 클래스를 초기화하고 name 필드에 액세스할 수 있습니다. 다른 모든 Python 객체:

dog = Dog()
dog.name = "Scruffy"
print(dog.name)

name 필드를 읽고 설정할 때 값이 네이티브 Python str 유형을 string 유형으로 변환하므로 값이 protobuf 런타임과 호환되는지 여부

10.0.0 버전 출시 이후 수행한 분석 결과 이러한 유형의 전환을 수행하는 데 소요된 시간이 성능에 미치는 영향을 이해하기 위해 사용자에게 protobuf 사용 옵션을 제공하는 것이 중요함 메시지를 보낼 수 있습니다

proto-plus 및 protobuf 메시지의 사용 사례

Proto-plus 메시지 사용 사례
Proto-plus는 protobuf 메시지에 비해 여러 인체 공학적 개선사항을 제공합니다. 유지관리 및 읽기 쉬운 코드를 작성하는 데 이상적입니다. 포드는 사용 및 이해하기가 더 쉽습니다.
Protobuf 메시지 사용 사례
특히 앱에서 성능에 민감한 사용 사례에 protobuf를 사용합니다. 대규모 보고서를 신속하게 처리해야 하거나 작업을 수행할 수 있습니다. 예를 들어 BatchJobService 또는 OfflineUserDataJobService입니다.

동적으로 메시지 유형 변경

앱에 적합한 메시지 유형을 선택하면 특정 워크플로에 다른 유형을 사용해야 하는 경우도 있습니다. 이 경우에는 API에서 제공하는 유틸리티를 사용하여 두 유형 간에 동적으로 쉽게 클라이언트 라이브러리로 대체될 수 있습니다. 위와 동일한 Dog 메시지 클래스 사용:

from google.ads.googleads import util

# Proto-plus message type
dog = Dog()

# Protobuf message type
dog = util.convert_proto_plus_to_protobuf(dog)

# Back to proto-plus message type
dog = util.convert_protobuf_to_proto_plus(dog)

Protobuf 메시지 인터페이스의 차이점

proto-plus 인터페이스는 세부정보이지만 여기서는 Google Ads 클라이언트의 일반적인 사용 사례에 영향을 미치는 몇 가지 주요 차이점 있습니다.

바이트 직렬화

Proto-Plus 메시지
serialized = type(campaign).serialize(campaign)
deserialized = type(campaign).deserialize(serialized)
Protobuf 메시지
serialized = campaign.SerializeToString()
deserialized = campaign.FromString(serialized)

JSON 직렬화

Proto-Plus 메시지
serialized = type(campaign).to_json(campaign)
deserialized = type(campaign).from_json(serialized)
Protobuf 메시지
from google.protobuf.json_format import MessageToJson, Parse

serialized = MessageToJson(campaign)
deserialized = Parse(serialized, campaign)

필드 마스크

api-core는 protobuf를 사용하도록 설계됨 메시지 인스턴스 따라서 proto-plus 메시지를 사용할 때는 protobuf로 변환하세요. 메시지를 사용하여 도우미 활용:

Proto-Plus 메시지
from google.api_core.protobuf_helpers import field_mask

campaign = client.get_type("Campaign")
protobuf_campaign = util.convert_proto_plus_to_protobuf(campaign)
mask = field_mask(None, protobuf_campaign)
Protobuf 메시지
from google.api_core.protobuf_helpers import field_mask

campaign = client.get_type("Campaign")
mask = field_mask(None, campaign)

열거형

proto-plus 메시지에 의해 노출되는 enum은 Python의 네이티브 enum 유형이므로 여러 편의 메서드를 상속합니다.

enum 유형 검색

GoogleAdsClient.get_type 메서드를 사용하여 enum을 검색하면 메시지 사용되는지 여부에 따라 약간 달라집니다. proto-plus 또는 protobuf 메시지로 구성됩니다. 예를 들면 다음과 같습니다.

Proto-Plus 메시지
val = client.get_type("CampaignStatusEnum").CampaignStatus.PAUSED
Protobuf 메시지
val = client.get_type("CampaignStatusEnum").PAUSED

enum을 더 간단하게 검색할 수 있도록 에 편의 속성이 있습니다. 일관된 인터페이스를 갖는 GoogleAdsClient 인스턴스 사용 중인 메시지 유형:

val = client.enums.CampaignStatusEnum.PAUSED

enum 값 검색

경우에 따라 특정 enum의 값 또는 필드 ID를 알면 예를 들어 CampaignStatusEnumPAUSED3에 해당합니다.

Proto-Plus 메시지
campaign = client.get_type("Campaign")
campaign.status = client.enums.CampaignStatusEnum.PAUSED
# To read the value of campaign status
print(campaign.status.value)
Protobuf 메시지
campaign = client.get_type("Campaign")
status_enum = client.enums.CampaignStatusEnum
campaign.status = status_enum.PAUSED
# To read the value of campaign status
print(status_enum.CampaignStatus.Value(campaign.status))

enum 이름 검색

enum 필드의 이름을 알면 도움이 될 때가 있습니다. 예를 들어 API에서 객체를 읽을 때 가장 오래된 캠페인 상태를 정수 3는 다음에 해당합니다.

Proto-Plus 메시지
campaign = client.get_type("Campaign")
campaign.status = client.enums.CampaignStatusEnum.PAUSED
# To read the name of campaign status
print(campaign.status.name)
Protobuf 메시지
campaign = client.get_type("Campaign")
status_enum = client.enums.CampaignStatusEnum
# Sets the campaign status to the int value for PAUSED
campaign.status = status_enum.PAUSED
# To read the name of campaign status
status_enum.CampaignStatus.Name(campaign.status)

반복 필드

proto-plus 문서, 반복되는 필드는 일반적으로 유형이 지정된 목록과 동일합니다. 즉, list와 거의 동일하게 동작합니다.

반복 스칼라 필드에 추가

반복되는 스칼라에 값을 추가할 때 type 필드, 예를 들면 다음과 같습니다. string 또는 int64 필드, 인터페이스는 메시지와 관계없이 동일합니다. 유형:

Proto-Plus 메시지
ad.final_urls.append("https://www.example.com")
Protobuf 메시지
ad.final_urls.append("https://www.example.com")

여기에는 다른 모든 일반적인 list 메서드도 포함됩니다(예: extend).

Proto-Plus 메시지
ad.final_urls.extend(["https://www.example.com", "https://www.example.com/2"])
Protobuf 메시지
ad.final_urls.extend(["https://www.example.com", "https://www.example.com/2"])

반복되는 필드에 메시지 유형 추가

반복된 필드가 스칼라가 아닌 경우 type, 즉 이 객체를 반복되는 필드는 약간 다릅니다

Proto-Plus 메시지
frequency_cap = client.get_type("FrequencyCapEntry")
frequency_cap.cap = 100
campaign.frequency_caps.append(frequency_cap)
Protobuf 메시지
# The add method initializes a message and adds it to the repeated field
frequency_cap = campaign.frequency_caps.add()
frequency_cap.cap = 100

반복 필드 할당

스칼라 및 비스칼라 반복 필드 모두에 대해 필드를 다양한 방식으로 지원합니다.

Proto-Plus 메시지
# In proto-plus it's possible to use assignment.
urls = ["https://www.example.com"]
ad.final_urls = urls
Protobuf 메시지
# Protobuf messages do not allow assignment, but you can replace the
# existing list using slice syntax.
urls = ["https://www.example.com"]
ad.final_urls[:] = urls

빈 메일

메시지 인스턴스에 정보를 입력하거나 필드가 설정되어 있어야 합니다.

Proto-Plus 메시지
# When using proto-plus messages you can simply check the message for
# truthiness.
is_empty = bool(campaign)
is_empty = not campaign
Protobuf 메시지
is_empty = campaign.ByteSize() == 0

메시지 사본

proto-plus 및 protobuf 메시지에 모두 copy_from를 사용하는 것이 좋습니다. GoogleAdsClient의 도우미 메서드를 호출합니다.

client.copy_from(campaign, other_campaign)

빈 메시지 필드

빈 메시지 필드를 설정하는 프로세스는 선택합니다. 필드에 빈 메시지를 복사하기만 하면 됩니다. 있습니다. 메시지 사본 섹션 및 빈 메시지 필드 가이드를 참조하세요. 이 예시에서는 빈 메시지 필드를 설정하는 방법은 다음과 같습니다.

client.copy_from(campaign.manual_cpm, client.get_type("ManualCpm"))

예약된 단어인 필드 이름

proto-plus 메시지를 사용할 때 필드 이름은 자동으로 Python에서 예약된 단어인 경우 뒤에 밑줄이 표시됩니다. 다음은 Asset 인스턴스 작업 예시:

asset = client.get_type("Asset")
asset.type_ = client.enums.AssetTypeEnum.IMAGE

예약된 전체 목록의 이름 가식적(gapic) 상태에서 구성됩니다. 생성기 모듈을 사용한 가능 프로그래매틱 방식으로도 액세스할 수 있습니다.

먼저 모듈을 설치합니다.

python -m pip install gapic-generator

그런 다음 Python REPL 또는 스크립트에서 다음을 수행합니다.

import gapic.utils
print(gapic.utils.reserved_names.RESERVED_NAMES)

현장 정보

protobuf 메시지 인스턴스의 필드는 기본값을 가지므로 필드가 설정되었는지 여부를 항상 직관적으로 알 수 있습니다.

Proto-Plus 메시지
# Use the "in" operator.
has_field = "name" in campaign
Protobuf 메시지
campaign = client.get_type("Campaign")
# Determines whether "name" is set and not just an empty string.
campaign.HasField("name")

protobuf Message 드림 클래스 인터페이스에는 HasField 메서드가 있어서 메시지가 설정된 경우에도 마찬가지입니다.

Protobuf 메시지 메서드

protobuf 메시지 인터페이스에는 지원되지 않는 몇 가지 편의 메서드가 포함되어 있습니다. proto-plus 인터페이스의 일부 하지만 Cloud Build를 사용하여 proto-plus 메시지를 protobuf 상응 대상으로 변환:

# Accessing the ListFields method
protobuf_campaign = util.convert_protobuf_to_proto_plus(campaign)
print(campaign.ListFields())

# Accessing the Clear method
protobuf_campaign = util.convert_protobuf_to_proto_plus(campaign)
print(campaign.Clear())

Issue Tracker

이번 변경사항에 대해 궁금한 점이 있거나 Google 계정으로 이전하는 데 문제가 있는 경우 14.0.0 버전의 라이브러리를 다운로드한 후 게시: 있습니다.