Python 2.7 ha raggiunto la fine del supporto
e verrà
ritirato
il 31 gennaio 2026. Dopo il ritiro, non potrai eseguire il deployment di applicazioni Python 2.7, anche se la tua organizzazione ha utilizzato in precedenza un criterio dell'organizzazione per riattivare i deployment di runtime legacy. Le tue applicazioni Python 2.7 esistenti continueranno a essere eseguite e a ricevere traffico dopo la
data di ritiro. Ti consigliamo di
eseguire la migrazione all'ultima versione supportata di Python.
La classe Key
Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Nota:
gli sviluppatori che creano nuove applicazioni sono vivamente incoraggiati a utilizzare la
libreria client NDB, che offre diversi vantaggi
rispetto a questa libreria client, ad esempio la memorizzazione nella cache automatica delle entità tramite l'API Memcache. Se al momento utilizzi la libreria client DB precedente, leggi la
guida alla migrazione da DB a NDB
Un'istanza della classe Key rappresenta una chiave univoca per un'entità Datastore.
Key
è fornito dal modulo google.appengine.ext.db
.
Introduzione
Ogni istanza del modello ha una chiave di identificazione,che include il tipo di entità dell'istanza insieme a un identificatore univoco. L'identificatore può essere una stringa nome chiave, assegnata esplicitamente dall'applicazione al momento della creazione dell'istanza, o un ID numerico intero,assegnato automaticamente da App Engine quando l'istanza viene scritta
(put)
in Datastore. Il metodo
key()
dell'istanza del modello restituisce l'oggetto Key
per l'istanza. Se all'istanza non è stata ancora assegnata una chiave, key()
genera un
NotSavedError
.
Un'applicazione può recuperare un'istanza di modello per una determinata chiave utilizzando la funzione get().
Le istanze di chiave possono essere valori per le proprietà dell'entità Datastore, incluse le proprietà dinamiche Expando e i membri ListProperty. Il modello ReferenceProperty fornisce funzionalità per i valori della proprietà Key, come il dereferenziamento automatico.
Costruttore
- class Key(encoded=None)
-
Una chiave univoca per un oggetto Datastore.
Una chiave può essere convertita in una stringa passando l'oggetto Key a
str()
.
La stringa è "urlsafe": utilizza solo caratteri validi per l'uso negli URL. La rappresentazione stringa della chiave può essere convertita nuovamente in un oggetto Key passandola al costruttore Key (l'argomento codificato).
Nota:la rappresentazione di una chiave sotto forma di stringa sembra enigmatica, ma non è criptata. Può essere convertito nuovamente nei dati chiave non elaborati, sia di tipo che di identificativo. Se non vuoi esporre questi dati agli utenti (e consentire loro di indovinare facilmente le chiavi di altre entità), cripta queste stringhe o utilizza qualcos'altro.
- codificato
- La forma
str
di un'istanza Key da convertire nuovamente in una Key.
Metodi di classe
La classe Key fornisce il seguente metodo di classe:
- Key.from_path(*path, parent=None, namespace=None)
-
Consente di creare un nuovo oggetto Key da un percorso (facoltativo) di un antenato (in un oggetto Key esistente) e da uno o più nuovi componenti del percorso. Ogni componente del percorso è costituito da un nome Tipo (kind
) e da un identificatore (id_or_name
), che può essere un numero o una stringa di caratteri.
Un percorso rappresenta la gerarchia delle relazioni padre-figlio per un'entità. Ogni entità nel percorso è rappresentata dal tipo di entità e dal relativo ID numerico o dal nome della chiave. Il percorso completo rappresenta l'entità visualizzata per ultima nel percorso, con i suoi antenati (genitori) come entità precedenti.
Ad esempio, la chiamata seguente crea una chiave per un'entità di tipo
Address
con ID numerico 9876
, sotto la chiave principale User/Boris
:
k = Key.from_path('User', 'Boris', 'Address', 9876)
Un modo alternativo per creare la stessa chiave è il seguente:
p1 = Key.from_path('User', 'Boris')
k = Key.from_path('Address', 9876, parent=p1)
Per ulteriori informazioni sui percorsi, consulta la pagina Entità, proprietà e chiavi.
Argomenti
- path
- Un elenco di uno o più componenti del percorso dell'antenato, in cui ogni componente è costituito da un tipo e da un identificatore:
- kind: il tipo di entità, rappresentato come stringa o stringa Unicode.
- identifier:
il valore
id
, specificato come stringa o long. Non può essere il numero 0.
- namespace=None
- Lo spazio dei nomi da impostare solo per questa chiave. Se fornisci uno spazio dei nomi qui, questo sostituisce lo spazio dei nomi corrente impostato in namespace_manager. Se
None
, l'API utilizza il namespace corrente di namespace_manager.get_namespace.
- parent=None
- Chiave principale facoltativa. Se non viene fornito, il valore predefinito è
None
.
Metodi istanza
Le istanze Key hanno i seguenti metodi:
- app()
-
Restituisce il nome dell'applicazione che ha archiviato l'entità di dati.
- has_id_or_name()
-
Restituisce True
se l'entità ha un nome o un ID numerico.
- id()
-
Restituisce l'ID numerico dell'entità di dati come numero intero o None
se l'entità non ha un ID numerico.
- id_or_name()
-
Restituisce il nome o l'ID numerico dell'entità di dati, a seconda di quale sia presente, o None
se l'entità non ha né un nome né un ID numerico.
- kind()
-
Restituisce il tipo di entità di dati sotto forma di stringa.
- name()
-
Restituisce il nome dell'entità di dati o None
se l'entità non ha un nome.
- namespace()
-
Restituisce lo spazio dei nomi dell'entità di dati. Se l'entità non ha uno spazio dei nomi corrente, questo metodo restituisce lo spazio dei nomi corrente impostato in namespace_manager.
- parent()
-
Restituisce la chiave dell'entità principale dell'entità di dati o None
se l'entità non ha un'entità principale.
Salvo quando diversamente specificato, i contenuti di questa pagina sono concessi in base alla licenza Creative Commons Attribution 4.0, mentre gli esempi di codice sono concessi in base alla licenza Apache 2.0. Per ulteriori dettagli, consulta le norme del sito di Google Developers. Java è un marchio registrato di Oracle e/o delle sue consociate.
Ultimo aggiornamento 2025-09-04 UTC.
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Difficile da capire","hardToUnderstand","thumb-down"],["Informazioni o codice di esempio errati","incorrectInformationOrSampleCode","thumb-down"],["Mancano le informazioni o gli esempi di cui ho bisogno","missingTheInformationSamplesINeed","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 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."]]