La classe Key
Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Remarque :
Les développeurs qui créent des applications sont vivement encouragés à utiliser la bibliothèque cliente NDB qui présente plusieurs avantages supplémentaires par rapport à cette bibliothèque cliente, tels que la mise en cache automatique des entités via l'API Memcache. Si vous utilisez actuellement l'ancienne bibliothèque cliente DB, consultez le guide de migration de DB vers NDB.
Une instance de la classe Key représente une clé unique correspondant à une entité Datastore.
La classe Key
est fournie par le module google.appengine.ext.db
.
Introduction
Chaque instance de modèle possède une clé d'identification, qui inclut le genre d'entité de l'instance ainsi qu'un identifiant unique. L'identifiant peut correspondre à une chaîne de nom de clé, attribuée explicitement par l'application lors de la création de l'instance, ou à un ID numérique entier, attribué automatiquement par App Engine lorsque l'instance est écrite (à l'aide de la méthode put) dans le datastore. La méthode
key()
de l'instance de modèle renvoie l'objet Key
de l'instance. Si aucune clé n'a été attribuée à l'instance, key()
génère une erreur
NotSavedError
.
Une application peut récupérer une instance de modèle associée à un objet Key donné à l'aide de la fonction get().
Les instances de la classe Key peuvent être des valeurs de propriétés d'entités Datastore, y compris des propriétés dynamiques Expando et des membres ListProperty. Le modèle ReferenceProperty propose des fonctionnalités pour les valeurs de propriétés Key, telles que le déréférencement automatique.
Constructeur
- class Key(encoded=None)
-
Clé unique d'un objet Datastore.
Il est possible de convertir une clé en chaîne en transmettant l'objet Key à str()
.
La chaîne est sécurisée pour les URL : elle n'utilise que des caractères valides dans les URL. Vous pouvez également reconvertir la représentation sous forme de chaîne de la clé en un objet Key en la transmettant au constructeur Key (l'argument encoded).
Remarque : La chaîne d'une clé semble difficile à lire, mais elle n'est pas chiffrée. Elle peut être reconvertie en données de clé brutes, avec le genre et l'identifiant. Si vous ne souhaitez exposer ces données à vos utilisateurs (pour éviter qu'ils devinent facilement les clés d'autres entités), chiffrez ces chaînes ou utilisez une autre méthode.
- encoded
- Forme
str
d'une instance de la classe Key à reconvertir en objet Key.
Méthodes des classes
La classe Key fournit la méthode de classe suivante :
- Key.from_path(*path, parent=None, namespace=None)
-
Crée un objet Key à partir d'un chemin d'accès ancêtre facultatif (dans un objet Key existant) et d'un ou plusieurs nouveaux composants de chemin. Chaque composant de chemin comporte un nom de genre (kind
) et un identifiant (id_or_name
), qui peut être un nombre ou une chaîne de caractères.
Un chemin d'accès représente la hiérarchie des relations parent-enfant d'une entité. Chaque entité du chemin d'accès est représentée par son genre, ainsi que par son ID numérique ou son nom de clé. Le chemin d'accès complet représente l'entité, qui apparaît en dernier dans le chemin d'accès, avec ses ancêtres (parents), qui correspondent aux entités précédentes.
Par exemple, l'appel suivant crée un objet Key pour une entité de genre Address
avec l'ID numérique 9876
, sous la clé parente User/Boris
:
k = Key.from_path('User', 'Boris', 'Address', 9876)
Vous pouvez également créer cet objet Key à l'aide de l'appel suivant :
p1 = Key.from_path('User', 'Boris')
k = Key.from_path('Address', 9876, parent=p1)
Pour en savoir plus sur les chemins d'accès, consultez la page Entités, propriétés et clés.
Arguments
- path
- Liste des composants de chemin d'ancêtre, chaque composant étant constitué d'un genre et d'un identifiant :
- Genre : genre de l'entité, représenté sous forme de chaîne ou de chaîne Unicode
- Identifiant :
id
spécifié sous forme de chaîne ou d'objet long. L'ID ne peut pas correspondre au chiffre 0.
- namespace=None
- Espace de noms à définir pour cet objet Key uniquement. Si vous fournissez un espace de noms ici, il remplace l'espace de noms actuel défini dans namespace_manager. Si la valeur
None
est spécifiée, l'API utilise l'espace de noms actuel de namespace_manager.get_namespace.
- parent=None
- Clé parente facultative. Si vous ne fournissez aucune valeur, la valeur par défaut est
None
.
Méthodes des instances
Les méthodes des instances de la classe Key sont les suivantes :
- app()
-
Renvoie le nom de l'application qui a stocké l'entité de données.
- has_id_or_name()
-
Renvoie True
si l'entité a un nom ou un identifiant numérique.
- id()
-
Renvoie l'identifiant numérique de l'entité de données, sous forme d'entier, ou None
si l'entité n'a pas d'identifiant numérique.
- id_or_name()
-
Renvoie le nom ou l'identifiant numérique de l'entité de données, selon le cas, ou None
si l'entité ne possède ni nom ni identifiant numérique.
- kind()
-
Renvoie le kind de l'entité de données, sous forme de chaîne.
- name()
-
Renvoie le nom de l'entité de données, ou None
si l'entité n'a pas de nom.
- namespace()
-
Renvoie l'espace de noms de l'entité de données. Si l'entité ne dispose d'aucun espace de noms, cette méthode renvoie l'espace de noms actuel défini dans namespace_manager.
- parent()
-
Renvoie l'objet Key de l'entité parente de l'entité de données, ou None
si l'entité n'a pas de parent.
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/09/04 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 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."]]