Python 2.7은 지원이 종료되었으며 2026년 1월 31일에
지원 중단됩니다. 지원 중단 후에는 조직에서 이전에 조직 정책을 사용하여 레거시 런타임의 배포를 다시 사용 설정한 경우에도 Python 2.7 애플리케이션을 배포할 수 없습니다. 기존 Python 2.7 애플리케이션은
지원 중단 날짜 이후에도 계속 실행되고 트래픽을 수신합니다.
지원되는 최신 Python 버전으로 마이그레이션하는 것이 좋습니다.
Message 클래스
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
Message 클래스는 네트워크 또는 프로세스 공간에서 효율적인 전송을 위해 메시지를 정의하는 데 사용됩니다. 메시지는 필드 클래스를 사용하여 정의됩니다.
Message
는 protorpc.messages
모듈에서 제공됩니다.
소개
메시지는 필드 속성과 기타 Message 및 Enum 정의만 포함할 수 있다는 점에서 일반 클래스보다 더 제한적입니다.
이러한 제한이 있는 이유는 Message 클래스 자체의 구조가 네트워크 또는 프로세스 공간에서 전송되며 클라이언트 또는 심지어 다른 서버에 의해 직접 사용되기 때문입니다.
따라서 메소드 및 비필드 속성을 구조적 정보와 함께 전송할 수 없으며, 이로 인해 서로 다른 언어와 구현 간에 불일치 문제가 발생합니다.
초기화 및 유효성 검사
Message 객체는 모든 필수 필드를 포함하고 중첩 메시지도 모두 초기화된 경우 초기화된 것으로 간주됩니다.
초기화되지 않은 경우 'check_initialized'를 호출하면 ValidationError가 발생합니다. 'is_initialized'는 유효 여부를 나타내는 부울 값을 반환합니다.
Google 프로토콜 RPC는 Message 객체가 생성되고 채워질 때 자동으로 해당 객체의 유효성을 검사합니다.
애플리케이션은 Field 인스턴스의 validate() 메소드를 사용하여 지정된 값과 해당 값이 할당된 필드가 서로 호환되는지 여부를 확인할 수 있습니다. 이 메소드를 메시지에 사용하면 메시지 및 하위 메시지의 모든 값이 유효한지 확인합니다. 잘못된 값을 필드에 할당하면 ValidationError가 발생합니다.
다음 예에서는 가상의 주식 거래 애플리케이션에서 Message 객체를 만들고 초기화합니다.
from protorpc import messages
# Trade type.
class TradeType(messages.Enum):
BUY = 1
SELL = 2
SHORT = 3
CALL = 4
class Lot(messages.Message):
price = messages.IntegerField(1, required=True)
quantity = messages.IntegerField(2, required=True)
class Order(messages.Message):
symbol = messages.StringField(1, required=True)
total_quantity = messages.IntegerField(2, required=True)
trade_type = messages.EnumField(TradeType, 3, required=True)
lots = messages.MessageField(Lot, 4, repeated=True)
limit = messages.IntegerField(5)
order = Order(symbol='GOOG',
total_quantity=10,
trade_type=TradeType.BUY)
lot1 = Lot(price=304,
quantity=7)
lot2 = Lot(price=305,
quantity=3)
order.lots = [lot1, lot2]
# Now object is initialized!
order.check_initialized()
생성자
Message 클래스의 생성자는 다음과 같이 정의됩니다.
- class Message(**kwargs)
-
내부 메시지 상태를 초기화합니다.
애플리케이션은 필드 클래스에 해당하는 키워드 인수를 전달하여 생성자를 통해 메시지를 초기화합니다. 예를 들면 다음과 같습니다.
class Date(Message)
day = IntegerField(1)
month = IntegerField(2)
year = IntegerField(3)
클래스 필드를 정의한 후에는 필드 값을 간결하게 호출할 수 있습니다. 다음 두 호출은 동일합니다.
date = Date(day=6, month=6, year=1911)
위 호출은 다음 호출과 동일합니다.
date = Date()
date.day = 6
date.month = 6
date.year = 1911
클래스 메서드
Message 클래스는 다음과 같은 클래스 메소드를 제공합니다.
- all_fields()
- 모든 필드 정의 객체를 가져옵니다. 모든 값에 대한 반복기를 임의의 순서로 반환합니다.
- field_by_name(name)
- 이름별로 필드를 가져옵니다. 이름에 연결된 Field 객체를 반환합니다.
- 해당 이름이 지정된 필드를 찾을 수 없으면 KeyError가 발생합니다.
- field_by_number(number)
- 번호별로 필드를 가져옵니다. 해당 번호에 연결된 Field 객체를 반환합니다.
- 해당 번호가 지정된 필드를 찾을 수 없으면 KeyError가 발생합니다.
인스턴스 메서드
Message 인스턴스에는 다음과 같은 메소드가 있습니다.
- check_initialized()
- 모든 필수 필드가 초기화되었는지 확인합니다.
- Message 객체가 초기화되지 않았으면 ValidationError가 발생합니다.
- get_assigned_value(name)
- 속성의 할당된 값을 가져옵니다. 값이 설정되지 않은 경우 None을 반환합니다.
- 인수:
- name
- 가져올 속성의 이름입니다.
속성의 할당된 값 또는 None(속성에 할당된 값이 없는 경우)을 반환합니다.
- is_initialized(name)
- Message 객체의 초기화 상태를 가져옵니다. 메시지가 유효하면
True
를 반환하고 그렇지 않으면 False
를 반환합니다.
- reset(name)
- 필드에 할당된 값을 재설정합니다(기본값이 재설정됨). 기본값이 없는 경우 None을 반환합니다.
- 인수:
- name
- 재설정할 필드의 이름입니다.
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 Creative Commons Attribution 4.0 라이선스에 따라 라이선스가 부여되며, 코드 샘플에는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 Google Developers 사이트 정책을 참조하세요. 자바는 Oracle 및/또는 Oracle 계열사의 등록 상표입니다.
최종 업데이트: 2025-09-04(UTC)
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["이해하기 어려움","hardToUnderstand","thumb-down"],["잘못된 정보 또는 샘플 코드","incorrectInformationOrSampleCode","thumb-down"],["필요한 정보/샘플이 없음","missingTheInformationSamplesINeed","thumb-down"],["번역 문제","translationIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-09-04(UTC)"],[[["\u003cp\u003eThe \u003ccode\u003eMessage\u003c/code\u003e class defines structured messages for efficient data transmission across networks or processes, using field attributes, other \u003ccode\u003eMessage\u003c/code\u003e definitions, and \u003ccode\u003eEnum\u003c/code\u003e types.\u003c/p\u003e\n"],["\u003cp\u003e\u003ccode\u003eMessage\u003c/code\u003e objects must have all required fields populated and nested messages initialized to be considered valid, which can be checked with \u003ccode\u003echeck_initialized\u003c/code\u003e or \u003ccode\u003eis_initialized\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003e\u003ccode\u003eMessage\u003c/code\u003e objects are validated upon creation and population, and assigning an invalid value will raise a \u003ccode\u003eValidationError\u003c/code\u003e, while the \u003ccode\u003evalidate()\u003c/code\u003e method can check value compatibility with a field.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eMessage\u003c/code\u003e constructor accepts keyword arguments corresponding to field classes, and values can be assigned directly during object creation or afterward, with the constructor supporting both methods.\u003c/p\u003e\n"],["\u003cp\u003eThe Message class offers class methods like \u003ccode\u003eall_fields\u003c/code\u003e, \u003ccode\u003efield_by_name\u003c/code\u003e, \u003ccode\u003efield_by_number\u003c/code\u003e to access field information, and instance methods such as \u003ccode\u003eget_assigned_value\u003c/code\u003e, and \u003ccode\u003ereset\u003c/code\u003e for handling field values.\u003c/p\u003e\n"]]],[],null,["# The Message Class\n\nThe Message class is used to define messages for efficient transmission across network or process space. Messages are defined using [field classes](/appengine/docs/legacy/standard/python/tools/protorpc/messages/fieldclasses).\n\n`Message` is provided by the `protorpc.messages` module.\n\nIntroduction\n------------\n\nMessages are more restricted than normal classes in that they may only contain field attributes and other Message and Enum definitions.\nThese restrictions are in place because the structure of the Message class itself is intended to be transmitted across network or process space and used directly by clients or even other servers.\nAs such, methods and non-field attributes cannot be transmitted with structural information, which causes discrepancies between different languages and implementations.\n\n### Initialization and Validation\n\nA Message object is considered to be initialized if it has all required fields and any nested messages are also initialized.\n\nCalling 'check_initialized' will raise a ValidationError if it is not initialized; 'is_initialized' returns a boolean value indicating if it is valid.\n\nGoogle Protocol RPC validates Message objects automatically when they are created and populated.\nYour application can validate whether a given value is compatible with a field that it is assigned to using the Field instance's [validate()](/appengine/docs/legacy/standard/python/tools/protorpc/messages/fieldclass#validate) method. When used on a message, this method checks that all values of a message and its sub-messages are valid. Assigning an invalid value to a field raises a [ValidationError](/appengine/docs/legacy/standard/python/tools/protorpc/messages/exceptions#ValidationError).\n\nThe following example creates and initializes Message objects in a fictitious stock trading application. \n\n```python\nfrom protorpc import messages\n\n# Trade type.\nclass TradeType(messages.Enum):\n BUY = 1\n SELL = 2\n SHORT = 3\n CALL = 4\n\nclass Lot(messages.Message):\n price = messages.IntegerField(1, required=True)\n quantity = messages.IntegerField(2, required=True)\n\nclass Order(messages.Message):\n symbol = messages.StringField(1, required=True)\n total_quantity = messages.IntegerField(2, required=True)\n trade_type = messages.EnumField(TradeType, 3, required=True)\n lots = messages.MessageField(Lot, 4, repeated=True)\n limit = messages.IntegerField(5)\n\norder = Order(symbol='GOOG',\n total_quantity=10,\n trade_type=TradeType.BUY)\n\nlot1 = Lot(price=304,\n quantity=7)\n\nlot2 = Lot(price=305,\n quantity=3)\n\norder.lots = [lot1, lot2]\n\n# Now object is initialized!\norder.check_initialized()\n```\n\nConstructor\n-----------\n\nThe constructor of the Message class is defined as follows:\n\nclass Message(\\*\\*kwargs)\n\n: Initialize the internal messages state.\n\n An application initializes a message via the constructor by passing in keyword arguments corresponding to [field classes](/appengine/docs/legacy/standard/python/tools/protorpc/messages/fieldclasses). For example: \n\n ```python\n class Date(Message)\n day = IntegerField(1)\n month = IntegerField(2)\n year = IntegerField(3)\n ```\n\n After defining the class field, you can concisely invoke field values. The following two invocations are equivalent: \n\n ```python\n date = Date(day=6, month=6, year=1911)\n ```\n\n Is equivalent to: \n\n ```python\n date = Date()\n date.day = 6\n date.month = 6\n date.year = 1911\n ```\n\nClass Methods\n-------------\n\nThe Message class provides the following class methods:\n\nall_fields()\n: Gets all field definition objects. Returns an iterator over all values in arbitrary order.\n\nfield_by_name(name)\n: Gets fields by name. Returns a Field object associated with the name.\n: Raises a [KeyError](http://wiki.python.org/moin/KeyError) if no field by that name is found.\n\nfield_by_number(number)\n: Gets a field by number. Returns the field object associated with that number.\n: Raises a [KeyError](http://wiki.python.org/moin/KeyError) if no field by that number is found.\n\nInstance Methods\n----------------\n\nMessage instances have the following methods:\n\ncheck_initialized()\n: Checks that all required fields are initialized.\n: Raises a [ValidationError](/appengine/docs/legacy/standard/python/tools/protorpc/messages/exceptions#ValidationError) if the Message object is not initialized.\n\nget_assigned_value(name)\n: Gets the assigned value of an attribute. If the value is unset, returns None.\n: Arguments:\n\n name\n : Name of the attribute to get.\n\n Returns the assigned value of an attribute, or None if the attribute has no assigned value.\n\nis_initialized(name)\n: Gets the initialization status for the Message object. Returns `True` if the message is valid, else `False`.\n\nreset(name)\n: Resets the assigned value for a field, which re-establishes the default value or, if there is no default value, None.\n: Arguments:\n\n name\n : Name of the field to reset."]]