Python 2.7 はサポートが終了しており、2026 年 1 月 31 日に
非推奨になります。非推奨になると、過去に組織のポリシーを使用して以前のランタイムのデプロイを再度有効にしていた場合でも、Python 2.7 アプリケーションをデプロイできなくなります。既存の Python 2.7 アプリケーションは、
非推奨日以降も引き続き実行され、トラフィックを受信します。
サポートされている最新バージョンの Python に移行することをおすすめします。
Message クラス
コレクションでコンテンツを整理
必要に応じて、コンテンツの保存と分類を行います。
Message クラスは、ネットワークまたは処理空間全体で効率的に伝達されるようにメッセージを定義するために使用されます。メッセージはフィールド クラスを使用して定義されます。
Message
は protorpc.messages
モジュールによって提供されます。
はじめに
Message は、フィールド属性と、他の Message や Enum の定義のみを含むことができるという点で、通常のクラスよりも制限されています。このような制限が設けられているのは、Message クラスの構造そのものを、ネットワークまたは処理空間で転送し、クライアントで、または別のサーバーでも直接使用することを意図としているためです。そのため、言語と実装の相違により矛盾が発生することから、メソッドとフィールド以外の属性を構造情報とともに転送することはできません。
初期化と検証
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)
クラス フィールドを定義したら、フィールド値を正確に呼び出すことができます。次の 2 つの呼び出しは同等です:
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 を送出します。
インスタンス メソッド
メッセージ インスタンスには、次のメソッドがあります。
- check_initialized()
- すべての必須フィールドが初期化されているかどうかをチェックします。
- Message オブジェクトが初期化されていない場合は、ValidationError を送出します。
- get_assigned_value(name)
- 属性に設定された値を取得します。値が設定されていない場合は None を返します。
- 引数:
- name
- 取得する属性の名前。
属性に設定された値を返します。属性に値が設定されていない場合は None を返します。
- is_initialized(name)
- Message オブジェクトの初期化ステータスを取得します。メッセージが有効であれば
True
、有効でなければ False
を返します。
- reset(name)
- フィールドに割り当てられた値をリセットします。つまり、デフォルト値が再設定されます。デフォルト値がない場合は None が設定されます。
- 引数:
- name
- リセットするフィールドの名前。
特に記載のない限り、このページのコンテンツはクリエイティブ・コモンズの表示 4.0 ライセンスにより使用許諾されます。コードサンプルは Apache 2.0 ライセンスにより使用許諾されます。詳しくは、Google Developers サイトのポリシーをご覧ください。Java は 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."]]