Python 2.7 已終止支援,並將於 2026 年 1 月 31 日
淘汰。淘汰後,您將無法部署 Python 2.7 應用程式,即使貴機構先前曾使用機構政策重新啟用舊版執行階段的部署作業,也無法部署。現有的 Python 2.7 應用程式在
淘汰日期過後,仍會繼續執行並接收流量。建議您
改用系統支援的最新 Python 版本。
金鑰類別
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
附註:我們強烈建議建構新應用程式的開發人員使用 NDB 用戶端程式庫,因為 NDB 用戶端程式庫與本用戶端程式庫相較之下有幾個優點,例如能透過 Memcache API 自動將實體加入快取。如果您目前使用的是舊版的 DB 用戶端程式庫,請參閱從 DB 至 NDB 的遷移指南。
Key 類別的執行個體代表的是資料儲存庫實體的唯一金鑰。
Key
由 google.appengine.ext.db
模組提供。
簡介
每個模型例項都有一個用於識別的金鑰,其中包含例項的實體類型,以及不重複的ID。ID 可能是「金鑰名稱」字串,由應用程式在執行個體建立時明確指派,或是整數的「數字 ID」,由 App Engine 在執行個體寫入 (put) 至資料儲存庫時自動指派。模型執行個體的
key()
方法會傳回執行個體的 Key
物件。如果執行個體尚未指派金鑰,key()
會發出
NotSavedError
。
應用程式可使用 get() 函式擷取指定 Key 的模型執行個體。
Key 執行個體可能為資料儲存庫實體屬性值,包括 Expando 動態屬性和 ListProperty 成員。ReferenceProperty 模型提供關鍵屬性值的功能,例如自動解析。
建構函式
- class Key(encoded=None)
-
資料儲存庫物件的唯一金鑰。
您可以將 Key 物件傳遞至 str()
,將金鑰轉換為字串。字串為「urlsafe」,只使用可在網址中使用的字元。您可以將金鑰的字串表示法傳遞至 Key 建構函式 (encoded 引數),藉此將金鑰轉換回 Key 物件。
注意:代表金鑰的字串看似為隱密內容,但實際上未經加密!它可轉換回原始的金鑰資料,包含種類與 ID。如果您不想將這類資料提供給使用者 (並讓他們輕易猜出其他實體的金鑰),請對這些字串加密或使用其他內容。
- encoded
- Key 例項的
str
形式,可轉換回 Key。
類別方法
Key 類別提供的類別方法如下:
- Key.from_path(*path, parent=None, namespace=None)
-
這會透過 (選用的) 祖系路徑 (位於現有的 Key 物件) 以及一或多個新路徑元件,建構出新的 Key 物件。每個路徑元件都包含類型名稱 (kind
) 和 ID (id_or_name
),ID 可以是數字或字元字串。
路徑代表實體的父項與子項之間的關係階層。路徑中的所有實體都能夠以實體種類加上其數字 ID 或其金鑰名稱來表示。完整路徑代表出現在路徑最後的實體,而且其祖系 (父項) 為之前的實體。
舉例來說,以下呼叫會在父項鍵 User/Boris
下,為類型為 Address
且數字 ID 為 9876
的實體建立索引鍵:
k = Key.from_path('User', 'Boris', 'Address', 9876)
另一個建立相同金鑰的方法如下:
p1 = Key.from_path('User', 'Boris')
k = Key.from_path('Address', 9876, parent=p1)
如要進一步瞭解路徑的相關資訊,請參閱實體、屬性和金鑰頁面。
引數
- path
- 一或多個祖系路徑元件的清單,其中每個元件都包含類型和 ID:
- 種類 — 實體種類,以字串或 Unicode 字串表示。
- ID -
id
,以字串或長整數指定。不可為數字 0。
- namespace=None
- 僅為此金鑰設定的命名空間。如果您在此提供命名空間,系統會覆寫 namespace_manager 中目前設定的命名空間。如果為
None
,API 會透過 namespace_manager.get_namespace 使用目前的命名空間。
- parent=None
- 選用父項金鑰。如未提供,預設為
None
。
實例方法
Key 執行個體的方法如下:
- 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
。
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2025-09-04 (世界標準時間)。
[[["容易理解","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 (世界標準時間)。"],[[["\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."]]