Schlüsselklasse
Mit Sammlungen den Überblick behalten
Sie können Inhalte basierend auf Ihren Einstellungen speichern und kategorisieren.
Hinweis: Entwicklern von neuen Anwendungen wird dringend empfohlen, die NDB-Clientbibliothek zu verwenden. Diese bietet im Vergleich zur vorliegenden Clientbibliothek verschiedene Vorteile, z. B. das automatische Caching von Entitäten über die Memcache API. Wenn Sie derzeit die ältere DB-Clientbibliothek verwenden, finden Sie weitere Informationen im Leitfaden zur Migration von DB- zu NDB-Clientbibliotheken.
Eine Instanz der Schlüsselklasse stellt einen eindeutigen Schlüssel für eine Datenspeicherentität dar.
Key
wird vom Modul google.appengine.ext.db
bereitgestellt.
Einführung
Jede Modellinstanz enthält einen Identifizierungsschlüssel, der den Entitätstyp der Instanz und eine eindeutige Kennzeichnung umfasst. Die Kennzeichnung kann entweder ein Schlüsselnamenstring sein, der beim Erstellen der Instanz explizit von der Anwendung zugewiesen wird, oder eine ganzzahlige numerische ID, die beim Schreiben der Instanz in Datastore automatisch von App Engine zugewiesen wird (put-Vorgang). Die Methode
key()
der Modellinstanz gibt das Key
-Objekt für die Instanz zurück. Wenn der Instanz noch kein Schlüssel zugewiesen wurde, löst key()
den Fehler
NotSavedError
aus.
Eine Anwendung kann mithilfe der get() eine Modellinstanz für einen bestimmten Schlüssel abrufen.
Schlüsselinstanzen können Werte für Attribute von Datastore-Entitäten sein, einschließlich dynamische Expando-Attribute und Mitglieder vom Typ ListProperty. Das Modell ReferenceProperty stellt Funktionen wie die automatische Dereferenzierung für Werte von Schlüsselattributen bereit.
Konstruktor
- Klasse Key(encoded=None)
-
Ein eindeutiger Schlüssel für ein Datenspeicherobjekt.
Durch Übergabe des Schlüsselobjekts an str()
kann ein Schlüssel in einen String konvertiert werden.
Der String ist "URL-sicher", d. h., es werden nur Zeichen verwendet, die für URLs zulässig sind. Sie können die Stringdarstellung des Schlüssels wieder in ein Schlüsselobjekt konvertieren. Dazu müssen Sie den Schlüssel an den Schlüsselkonstruktor (das codierte Argument) übergeben.
Hinweis: Die Stringdarstellung eines Schlüssels sieht verschlüsselt aus, ist es jedoch nicht. Sie kann wieder in die Schlüsselrohdaten, also Typ und Kennzeichnung, konvertiert werden. Wenn Ihre Nutzer keinen Zugriff auf diese Daten und damit auch nicht die Möglichkeit haben sollen, die Schlüssel anderer Entitäten leicht zu erraten, verschlüsseln Sie diese Strings oder verwenden eine andere Methode.
- encoded
- Die
str
-Form einer Schlüsselinstanz, die wieder in einen Schlüssel konvertiert werden soll.
Klassenmethoden
Die Schlüsselklasse stellt die folgenden Klassenmethoden bereit:
- Key.from_path(*path, parent=None, namespace=None)
-
Erstellt ein neues Schlüsselobjekt aus einem (optionalen) Ancestor-Pfad (in einem vorhandenen Schlüsselobjekt) und einer oder mehreren neuen Pfadkomponenten. Jede Pfadkomponente besteht aus dem Namen eines Typs (kind
) und einer Kennzeichnung (id_or_name
), die entweder eine Zahl oder ein Zeichenstring ist.
Ein Pfad stellt die Hierarchie von Beziehungen über- und untergeordneter Beziehungen für eine Entität dar. Jede Entität im Pfad wird durch den Typ der Entität und ihre numerische ID oder ihren Schlüsselnamen dargestellt. Der vollständige Pfad stellt die Entität dar, die als letzte Entität im Pfad angezeigt wird. Davor sind deren übergeordnete Entitäten zu finden.
Der folgende Aufruf erstellt beispielsweise einen Schlüssel für eine Entität vom Typ Address
mit der numerischen ID 9876
unter dem übergeordneten Schlüssel User/Boris
:
k = Key.from_path('User', 'Boris', 'Address', 9876)
Derselbe Schlüssel kann auch so erstellt werden:
p1 = Key.from_path('User', 'Boris')
k = Key.from_path('Address', 9876, parent=p1)
Weitere Informationen zu Pfaden finden Sie auf der Seite Entitäten, Properties und Schlüssel.
Argumente
- path
- Eine oder mehrere Ancestor-Pfadkomponenten, wobei jede Komponente aus einem Typ und einer Kennzeichnung besteht:
- Typ – Der Entitätstyp, dargestellt als String oder Unicode-String.
- Kennzeichnung – Die
id
, angegeben als String oder "long". Die Zahl 0 darf nicht verwendet werden.
- namespace=None
- Der Namespace, der nur für diesen Schlüssel festgelegt werden soll. Wenn Sie hier einen Namespace angeben, wird der aktuelle Namespace in namespace_manager überschrieben. Bei Angabe von
None
verwendet die API den aktuellen Namespace aus namespace_manager.get_namespace.
- parent=None
- Optionaler übergeordneter Schlüssel. Standardmäßig wird
None
verwendet, sofern keine Angabe gemacht wird.
Instanzmethoden
Schlüsselinstanzen weisen die folgenden Methoden auf:
- app()
-
Gibt den Namen der Anwendung zurück, in der die Datenentität gespeichert wurde.
- has_id_or_name()
-
Gibt True
zurück, wenn die Entität entweder einen Namen oder eine numerische ID aufweist.
- id()
-
Gibt die numerische ID der Datenentität als Ganzzahl oder None
zurück, wenn die Entität keine numerische ID hat.
- id_or_name()
-
Gibt je nach Vorhandensein entweder den Namen oder die numerische ID der Datenentität oder aber None
zurück, wenn die Entität weder einen Namen noch eine numerische ID hat.
- kind()
-
Gibt den Typ der Datenentität als String zurück.
- name()
-
Gibt den Namen der Datenentität oder None
zurück, wenn die Entität keinen Namen hat.
- namespace()
-
Gibt den Namespace der Datenentität zurück. Wenn die Entität keinen aktuellen Namespace hat, gibt diese Methode den aktuellen Namespace aus namespace_manager zurück.
- parent()
-
Gibt den Schlüssel der übergeordneten Entität der Datenentität oder None
zurück, wenn die Entität kein übergeordnetes Element hat.
Sofern nicht anders angegeben, sind die Inhalte dieser Seite unter der Creative Commons Attribution 4.0 License und Codebeispiele unter der Apache 2.0 License lizenziert. Weitere Informationen finden Sie in den Websiterichtlinien von Google Developers. Java ist eine eingetragene Marke von Oracle und/oder seinen Partnern.
Zuletzt aktualisiert: 2025-09-04 (UTC).
[[["Leicht verständlich","easyToUnderstand","thumb-up"],["Mein Problem wurde gelöst","solvedMyProblem","thumb-up"],["Sonstiges","otherUp","thumb-up"]],[["Schwer verständlich","hardToUnderstand","thumb-down"],["Informationen oder Beispielcode falsch","incorrectInformationOrSampleCode","thumb-down"],["Benötigte Informationen/Beispiele nicht gefunden","missingTheInformationSamplesINeed","thumb-down"],["Problem mit der Übersetzung","translationIssue","thumb-down"],["Sonstiges","otherDown","thumb-down"]],["Zuletzt aktualisiert: 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."]]