Python 2.7 已达到支持终止期限,并将于 2026 年 1 月 31 日
弃用。弃用后,您将无法部署 Python 2.7 应用,即使您的组织之前曾使用组织政策重新启用旧版运行时的部署也是如此。现有的 Python 2.7 应用在
弃用日期之后将继续运行并接收流量。我们建议您
迁移到最新支持的 Python 版本。
Key 类
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
注意:强烈建议构建新应用的开发者使用 NDB 客户端库,它与 DB 客户端库相比具有多项优势,例如可通过 Memcache API 进行自动实体缓存。如果您当前使用的是较早的 DB 客户端库,请参阅 DB 到 NDB 的迁移指南
Key 类的实例代表数据存储区实体的唯一键。
Key
由 google.appengine.ext.db
模块提供。
简介
每个模型实例都具有一个标识键,其中包含实例的实体种类以及唯一标识符。标识符可以是创建实例时由应用显式分配的键名字符串,也可以是将实例写入 (put) Datastore 时由 App Engine 自动分配的整数 ID。模型实例的
key()
方法会返回该实例的 Key
对象。如果尚未向实例分配键,调用 key()
会引发
NotSavedError
。
应用可以使用 get() 函数来检索给定 Key 的模型实例。
Key 实例可以是 Datastore 实体属性的值,包括 Expando 动态属性和 ListProperty 成员。ReferenceProperty 模型为 Key 属性值提供自动解引用等功能。
构造函数
- class Key(encoded=None)
-
数据存储区对象的唯一键。
键可以转换为字符串,只需将 Key 对象传递给 str()
即可。
字符串为“urlsafe”,仅使用适合在网址中使用的字符。键的字符串表示形式可以转换回为 Key 对象,只需将其传递给 Key 构造函数(encoded 参数)即可。
注意:键的字符串表示形式看起来已加密,但实际未加密!它可以转换为原始键数据,包括种类和标识符。如果您不希望向用户公开此数据(让他们能轻松猜出其他实体的键),请对这些字符串进行加密,或者使用其他内容。
- encoded
- 可以转换回 Key 的 Key 实例的
str
形式。
类方法
Key 类提供以下类方法:
- Key.from_path(*path, parent=None, namespace=None)
-
可通过(可选)祖先路径(在现有 Key 对象中)及一个或多个新路径组件构建新的 Key 对象。每个路径组件都由种类名称 (kind
) 和标识符 (id_or_name
) 组成,此标识符为数字或字符串。
路径代表实体的父子关系的层次结构。路径中的每个实体都由实体的种类及其数字 ID 或其键名称表示。完整路径代表路径中最后显示的实体,其祖先(父项)作为前续实体。
例如,以下调用会根据父键 User/Boris
为种类为 Address
并且数字 ID 为 9876
的实体创建一个 Key:
k = Key.from_path('User', 'Boris', 'Address', 9876)
创建相同 Key 的另一种方法如下所示:
p1 = Key.from_path('User', 'Boris')
k = Key.from_path('Address', 9876, parent=p1)
如需详细了解路径,请参阅实体、属性和键页面。
参数
- path
- 一个或多个祖先路径组件的列表,其中每个组件由种类和标识符组成:
- 种类 - 实体种类,以字符串或 Unicode 字符串的形式表示。
- 标识符 -
id
,指定为字符串或长整数。不能为数字 0。
- namespace=None
- 仅为此 Key 设置的命名空间。如果您在此处提供一个命名空间,则该命名空间会替换 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
。
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):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"]],["最后更新时间 (UTC):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."]]