Python 2.7 はサポートが終了しており、2026 年 1 月 31 日に
非推奨になります。非推奨になると、過去に組織のポリシーを使用して以前のランタイムのデプロイを再度有効にしていた場合でも、Python 2.7 アプリケーションをデプロイできなくなります。既存の Python 2.7 アプリケーションは、
非推奨日以降も引き続き実行され、トラフィックを受信します。
サポートされている最新バージョンの Python に移行することをおすすめします。
Key クラス
コレクションでコンテンツを整理
必要に応じて、コンテンツの保存と分類を行います。
注: 新しいアプリケーションを作成する際は、NDB クライアント ライブラリを使用することを強くおすすめします。NDB クライアント ライブラリには、Memcache API によるエンティティの自動キャッシュをはじめ、このクライアント ライブラリにはないメリットがあります。古い DB クライアント ライブラリを現在使用している場合は、DB から NDB への移行ガイドをお読みください。
Key クラスのインスタンスは、Datastore エンティティの一意のキーを表します。
Key
は google.appengine.ext.db
モジュールによって提供されます。
はじめに
すべてのモデル インスタンスには、識別のためのキーがあります。このキーには、インスタンスのエンティティの種類と一意の識別子が含まれています。識別子は、インスタンスの作成時にアプリケーションで明示的に割り当てたキー名の文字列か、またはインスタンスがデータストアに書き込まれた(put)時点で App Engine により自動的に割り当てられた整数の数値 ID のいずれかです。モデル インスタンスの
key()
メソッドは、このインスタンスに応じた Key
オブジェクトを返します。インスタンスにキーが割り当てられていない場合、key()
は
NotSavedError
を生成します。
アプリケーションで get() 関数を使用すると、指定キーのモデル インスタンスを取得できます。
キー インスタンスは、Datastore エンティティ プロパティの値になります(Expando 動的プロパティや ListProperty メンバーなど)。ReferenceProperty モデルは、自動逆参照など、Key プロパティ値の機能を提供します。
コンストラクタ
- class Key(encoded=None)
-
Datastore オブジェクトの一意のキー。
Key オブジェクトを str()
に渡すと、キーを文字列に変換できます。文字列は urlsafe になります。URL で使用できる文字だけを使用します。キーの文字列表現は、Key コンストラクタ(encoded 引数)を使用すると、Key オブジェクトに戻すことができます。
注: キーの文字列表現は暗号のように見えますが、実際には暗号化されていません。未加工のキーデータ(種類と識別子)に戻すことができます。このデータをユーザーに公開しない場合(他のエンティティのキーの推測を許可しない場合)には、これらの文字列を暗号化するか、別のものを使用してください。
- encoded
- キーに戻す Key インスタンスの
str
フォーム。
クラスメソッド
Key クラスは、次のクラスメソッドを提供します。
- Key.from_path(*path, parent=None, namespace=None)
-
任意の祖先パス(既存の Key オブジェクト)から新しい Key オブジェクトを作成します。また、1 つ以上の新しいパス コンポーネントを作成します。パス コンポーネントは、種類名(kind
)と識別子(id_or_name
)から構成されます。これらは、数値または文字列になります。
パスは、エンティティの親子関係を反映する階層を表します。パスのエンティティはすべてエンティティの種類で表現されます。これらは、数値 ID またはキー名になります。フルパスは、パスの最後にあり、先行するエンティティとして祖先(親)が存在するエンティティを表します。
たとえば、次の呼び出しでは、種類 Address
、数値 ID 9876
のエンティティに親キー User/Boris
を使用してキーを作成しています。
k = Key.from_path('User', 'Boris', 'Address', 9876)
次の方法でも同じキーを作成できます。
p1 = Key.from_path('User', 'Boris')
k = Key.from_path('Address', 9876, parent=p1)
パスの詳細については、エンティティ、プロパティ、キーをご覧ください。
引数
- path
- 1 つ以上の祖先パス コンポーネントのリスト。各コンポーネントは、種類と識別子から構成されます。
- 種類 - エンティティの種類。文字列または Unicode 文字列で表します。
- 識別子 -
id
。文字列または long 型として指定します。0 にはできません。
- namespace=None
- このキーにのみ設定する名前空間。名前空間を指定すると、namespace_manager で現在設定されている名前空間が上書きされます。
None
の場合、API は namespace_manager.get_namespace から現在の名前空間を取得します。
- parent=None
- 親キー(省略可)。指定しない場合、デフォルトは
None
です。
インスタンス メソッド
キー インスタンスには次のメソッドがあります。
- app()
-
データ エンティティを保存しているアプリケーションの名前を返します。
- has_id_or_name()
-
エンティティが名前または数値 ID の場合、True
を返します。
- id()
-
データ エンティティの数値 ID を返します。エンティティに数値 ID がない場合には None
を返します。
- id_or_name()
-
データ エンティティの名前または数値 ID を返します。エンティティに名前も数値 ID もない場合には None
を返します。
- kind()
-
データ エンティティの種類を文字列で返します。
- name()
-
データ エンティティの名前を返します。エンティティに名前がない場合には None
を返します。
- namespace()
-
データ エンティティの名前空間を返します。エンティティに名前空間がない場合、このメソッドは、namespace_manager に設定されている名前空間を返します。
- parent()
-
データ エンティティの親のキーを返します。エンティティに親がない場合には None
を返します。
特に記載のない限り、このページのコンテンツはクリエイティブ・コモンズの表示 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 Key class represents a unique identifier for a Datastore entity, encompassing its entity kind and a unique identifier which can be either a key name or a numeric ID.\u003c/p\u003e\n"],["\u003cp\u003eDevelopers are encouraged to use the NDB Client Library instead of the older DB Client Library, as NDB offers improved features like automatic entity caching.\u003c/p\u003e\n"],["\u003cp\u003eKey objects can be converted to and from "urlsafe" string representations, although these strings are not encrypted and reveal the underlying key data.\u003c/p\u003e\n"],["\u003cp\u003eThe Key.from_path() class method allows the creation of new Key objects by specifying an optional ancestor path and one or more path components, defining the hierarchy of parent-child relationships.\u003c/p\u003e\n"],["\u003cp\u003eKey instances provide various methods such as kind(), id(), name(), namespace(), and parent() to access information about the data entity associated with that key.\u003c/p\u003e\n"]]],[],null,["# The Key Class\n\n**Note:**\nDevelopers building new applications are **strongly encouraged** to use the\n[NDB Client Library](/appengine/docs/legacy/standard/python/ndb), which has several benefits\ncompared to this client library, such as automatic entity caching via the Memcache\nAPI. If you are currently using the older DB Client Library, read the\n[DB to NDB Migration Guide](/appengine/docs/legacy/standard/python/ndb/db_to_ndb)\n\nAn instance of the Key class represents a unique key for a Datastore entity.\n\n`Key` is provided by the `google.appengine.ext.db` module.\n\nIntroduction\n------------\n\nEvery model instance has an identifying\n*[key](./#Kinds_keys_and_identifiers),*\nwhich includes the instance's\n*[entity kind](/appengine/docs/legacy/standard/python/datastore/entities#Kinds_and_identifiers)*\nalong with a unique *identifier.* The identifier may be either a *key name* string, assigned explicitly by the application when the instance is created, or an integer *numeric ID,* assigned automatically by App Engine when the instance is written\n([put](/appengine/docs/legacy/standard/python/datastore/modelclass#Model_put))\nto the Datastore. The model instance's\n[key()](/appengine/docs/legacy/standard/python/datastore/modelclass#Model_key)\nmethod returns the `Key` object for the instance. If the instance has not yet been assigned a key, `key()` raises a\n[NotSavedError](/appengine/docs/legacy/standard/python/datastore/exceptions#NotSavedError).\n\nAn application can retrieve a model instance for a given Key using the [get()](/appengine/docs/legacy/standard/python/datastore/functions#get) function.\n\nKey instances can be values for Datastore entity properties, including [Expando](/appengine/docs/legacy/standard/python/datastore/expandoclass) dynamic properties and [ListProperty](/appengine/docs/legacy/standard/python/datastore/typesandpropertyclasses#ListProperty) members. The [ReferenceProperty](/appengine/docs/legacy/standard/python/datastore/typesandpropertyclasses#ReferenceProperty) model provides features for Key property values such as automatic dereferencing.\n\nConstructor\n-----------\n\nclass Key(encoded=None)\n\n: A unique key for a Datastore object.\n\n A key can be converted to a string by passing the Key object to\n `str()`.\n The string is \"urlsafe\"---it uses only characters valid\n for use in URLs. The string representation of\n the key can be converted back to a Key object by\n passing it to the Key constructor (the\n encoded argument).\n\n **Note:** The string representation of a key looks\n cryptic, but is not\n encrypted! It can be converted back to the raw key data, both kind and\n identifier. If you don't want to expose this data to your users (and allow\n them to easily guess other entities' keys), then encrypt these strings\n or use something else.\n\n encoded\n : The `str` form of a Key instance to convert back into a Key.\n\nClass Methods\n-------------\n\nThe Key class provides the following class method:\n\nKey.from_path(\\*path, parent=None, namespace=None)\n\n: Builds a new Key object from an (optional) ancestor path (in an existing Key object), and one or more new path components. Each path\n component consists of a Kind name (`kind`) and an identifier (`id_or_name`), which is either a number or a character string.\n\n A path represents the hierarchy of parent-child relationships for an entity. Each entity in the path is represented by the entity's kind, and either its numeric ID or its key name. The full path represents the entity that appears last in the path, with its ancestors (parents) as preceding entities.\n\n For example, the following call creates a Key for an entity of kind\n `Address` with numeric ID `9876`, under the parent key `User/Boris`: \n\n ```\n k = Key.from_path('User', 'Boris', 'Address', 9876)\n ```\n\n An alternative way of creating the same Key is as follows: \n\n ```\n p1 = Key.from_path('User', 'Boris')\n k = Key.from_path('Address', 9876, parent=p1)\n ```\n\n For more information about paths, see the [Entities, Properties, and Keys](/appengine/docs/legacy/standard/python/datastore/entities#Ancestor_paths) page.\n\n Arguments\n\n path\n : A list of one or more ancestor path components, where each component consists of a kind and an identifier:\n\n - kind --- The entity kind, represented as a string or a Unicode string.\n - identifier --- The `id`, specified as a string or long. It cannot be the number 0.\n\n namespace=None\n : The namespace to set for this Key only. If you supply a namespace here, it overrides the current namespace set in the [namespace_manager](/appengine/docs/legacy/standard/python/refdocs/modules/google/appengine/api/namespace_manager/namespace_manager). If `None`, the API uses the current namespace from [namespace_manager.get_namespace](/appengine/docs/legacy/standard/python/refdocs/modules/google/appengine/api/namespace_manager/namespace_manager#get_namespace).\n\n parent=None\n : Optional parent key. If not supplied, defaults to `None`.\n\n### Instance Methods\n\nKey instances have the following methods:\n\napp()\n\n: Returns the name of the application that stored the data entity.\n\nhas_id_or_name()\n\n: Returns `True` if the entity has either a name or a numeric ID.\n\nid()\n\n: Returns the numeric ID of the data entity, as an integer, or `None` if the entity does not have a numeric ID.\n\nid_or_name()\n\n: Returns the name or numeric ID of the data entity, whichever it has, or `None` if the entity has neither a name nor a numeric ID.\n\nkind()\n\n: Returns the kind of the data entity, as a string.\n\nname()\n\n: Returns the name of the data entity, or `None` if the entity does not have a name.\n\nnamespace()\n\n: Returns the namespace of the data entity. If the entity does not have a current namespace, this method returns the current namespace set in the [namespace_manager](/appengine/docs/legacy/standard/python/multitenancy/functions).\n\nparent()\n\n: Returns the Key of the data entity's parent entity, or `None` if the entity has no parent."]]