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.
Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Un'istanza della classe Key rappresenta una chiave immutabile di Datastore.
Questa pagina contiene la documentazione di riferimento dell'API. Per una panoramica, consulta Entità e chiavi NDB.
Introduzione
Una chiave è una chiave Datastore immutabile. Le applicazioni in genere li utilizzano per fare riferimento alle entità. Qualsiasi entità memorizzata ha una chiave. Per ottenere la chiave di un'entità, utilizza la proprietà key del modello.
Per recuperare un'entità dalla relativa chiave, chiama il metodo get() dell'oggetto Key.
Le chiavi supportano i confronti, ad esempio
key1 == key2 o
key1 < key2.
Questi operatori confrontano l'ID applicazione, lo spazio dei nomi e il "percorso dell'antenato" completo. Utilizzano lo stesso ordinamento utilizzato da Datastore per le query quando l'ordinamento avviene in base a una proprietà chiave o a una chiave.
repr(key) o
str(key) restituisce
una rappresentazione di stringa simile
alla forma più breve del costruttore, omettendo l'app e lo spazio dei nomi
a meno che non differiscano dal valore predefinito.
hash(key) funziona. In questo modo, puoi memorizzare le chiavi in
una tabella hash.
Costruttori
Per flessibilità e praticità, sono supportate più firme del costruttore.
classKey(kind1, id1, kind2, id2, ...)
classKey(pairs=[(kind1, id1), (kind2, id2), ...])
classKey(flat=[kind1, id1, kind2, id2, ...])
classKey(urlsafe=string)
Gli argomenti posizionali
kind1, id1, kind2, id2…
sono in ordine "antenato". (Questa è una scorciatoia per
flat=[kind1, id1,
kind2, id2]) I genitori vengono prima dei figli.
I moduli del costruttore con argomenti posizionali, pairs e flat possono anche passare un'altra chiave utilizzando parent=key. Le coppie (kind, id) della chiave principale vengono inserite prima delle coppie (kind, id) passate esplicitamente.
Il parametro della parola chiave urlsafe utilizza
un riferimento serializzato codificato in base64 per il web
ma è meglio considerarlo solo una stringa opaca univoca.
Argomenti aggiuntivi della parola chiave del costruttore:
app
specifica l'ID applicazione (una stringa)
namespace
specifica lo spazio dei nomi (una stringa)
Metodi istanza che non influiscono sul datastore
I seguenti metodi accedono ai contenuti di una chiave. Non svolgono attività di I/O di Datastore.
pairs()
Restituisce una tupla di coppie (kind, id).
flat()
Restituisce una tupla di valori di tipo e ID appiattiti
(kind1, id1, kind2, id2, ...).
app()
Restituisce l'ID applicazione.
id()
Restituisce la stringa o l'ID intero nell'ultima coppia (kind, id),
oppure None se la chiave è incompleta.
string_id()
Restituisce l'ID stringa nell'ultima coppia (kind, id)
oppure None se la chiave ha un ID intero o è incompleta.
integer_id()
Restituisce l'ID intero nell'ultima coppia (kind, id)
o None se la chiave ha un ID stringa o è incompleta.
namespace()
Restituisce lo spazio dei nomi.
kind()
Restituisce il tipo nell'ultima coppia (kind, id).
parent()
Restituisce una chiave costruita da tutte le coppie (kind, id) tranne l'ultima
(o None se la chiave ha una sola coppia (kind, id)).
urlsafe()
Restituisce una versione serializzata della chiave con codifica Base64 sicura per il web.
Nota:
la stringa sicura per gli URL sembra criptica, ma non è criptata.
Può essere facilmente decodificato per recuperare il tipo e l'identificatore dell'entità originale.
to_old_key()
Restituisce un valore Key per la "vecchia" API Datastore (db).
[[["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\u003eThis API for bundled services and \u003ccode\u003eKey\u003c/code\u003e class operations is specifically for first-generation runtimes in the App Engine standard environment, with migration to Python 3 requiring a specific guide.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eKey\u003c/code\u003e class represents an immutable Datastore key, used to refer to entities and to retrieve them using the \u003ccode\u003eget()\u003c/code\u003e method.\u003c/p\u003e\n"],["\u003cp\u003eKeys can be compared using operators such as \u003ccode\u003e==\u003c/code\u003e and \u003ccode\u003e<\u003c/code\u003e, and also support string representation, as well as being used within a hash table.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eKey\u003c/code\u003e class offers various constructor signatures, including those for ancestor order, pairs, flat structures, and URL-safe strings, along with options for specifying the application ID and namespace.\u003c/p\u003e\n"],["\u003cp\u003eThere are multiple methods to access key properties and contents, which do not affect the Datastore, as well as other methods that will interact with the Datastore, like to get or delete an entity.\u003c/p\u003e\n"]]],[],null,["# NDB Key Class\n\n| This page describes how to use the legacy bundled services and APIs. This API can only run in first-generation runtimes in the App Engine standard environment. If you are updating to the App Engine Python 3 runtime, refer to the [migration guide](/appengine/migration-center/standard/migrate-to-second-gen/python-differences) to learn about your migration options for legacy bundled services.\n\nAn instance of the `Key` class represents an immutable\nDatastore key.\n\nThis page has API reference documentation. For an overview,\nsee [NDB Entities and Keys](/appengine/docs/legacy/standard/python/ndb/creating-entities).\n\nIntroduction\n------------\n\nA Key is an immutable Datastore key. Applications normally use them to refer\nto entities. Any entity that has been stored has a key. To get an entity's\nkey, use the model's [key](/appengine/docs/legacy/standard/python/ndb/modelclass#Model_key)\nproperty.\nTo retrieve an entity from its key, call the `Key`\nobject's [get()](#Key_get) method.\n\nKeys support comparisons, for example\n\u003cvar translate=\"no\"\u003ekey1\u003c/var\u003e` == `\u003cvar translate=\"no\"\u003ekey2\u003c/var\u003e or\n\u003cvar translate=\"no\"\u003ekey1\u003c/var\u003e` \u003c `\u003cvar translate=\"no\"\u003ekey2\u003c/var\u003e.\nThese operators compare application ID, namespace, and the full\n\"ancestor path\". They use the same ordering as the Datastore uses\nfor queries when ordering by a key property or by key.\n\n`repr(`\u003cvar translate=\"no\"\u003ekey\u003c/var\u003e`)` or\n`str(`\u003cvar translate=\"no\"\u003ekey\u003c/var\u003e`)` returns\na string representation resembling\nthe shortest constructor form, omitting the app and namespace\nunless they differ from the default value.\n\n`hash(`\u003cvar translate=\"no\"\u003ekey\u003c/var\u003e`)` works. Thus, you can store keys in\na hash table.\n\nConstructors\n------------\n\nFor flexibility and convenience, multiple constructor signatures are\nsupported.\n\nclass Key(\u003cvar translate=\"no\"\u003ekind1\u003c/var\u003e, \u003cvar translate=\"no\"\u003eid1\u003c/var\u003e, \u003cvar translate=\"no\"\u003ekind2\u003c/var\u003e, \u003cvar translate=\"no\"\u003eid2\u003c/var\u003e, ...)\nclass Key(pairs=\\[(\u003cvar translate=\"no\"\u003ekind1\u003c/var\u003e, \u003cvar translate=\"no\"\u003eid1\u003c/var\u003e), (\u003cvar translate=\"no\"\u003ekind2\u003c/var\u003e, \u003cvar translate=\"no\"\u003eid2\u003c/var\u003e), ...\\])\nclass Key(flat=\\[\u003cvar translate=\"no\"\u003ekind1\u003c/var\u003e, \u003cvar translate=\"no\"\u003eid1\u003c/var\u003e, \u003cvar translate=\"no\"\u003ekind2\u003c/var\u003e, \u003cvar translate=\"no\"\u003eid2\u003c/var\u003e, ...\\])\nclass Key(urlsafe=\u003cvar translate=\"no\"\u003estring\u003c/var\u003e)\n\n: The positional arguments\n \u003cvar translate=\"no\"\u003ekind1\u003c/var\u003e, \u003cvar translate=\"no\"\u003eid1\u003c/var\u003e, \u003cvar translate=\"no\"\u003ekind2\u003c/var\u003e, \u003cvar translate=\"no\"\u003eid2\u003c/var\u003e...\n are in \"ancestor\" order. (This is a shortcut for\n `flat=[`\u003cvar translate=\"no\"\u003ekind1\u003c/var\u003e`, `\u003cvar translate=\"no\"\u003eid1\u003c/var\u003e`,\n `\u003cvar translate=\"no\"\u003ekind2\u003c/var\u003e`, `\u003cvar translate=\"no\"\u003eid2\u003c/var\u003e`]`) Parents come before children.\n\n The positional-arguments, `pairs`, and `flat`\n constructor forms can additionally pass in another\n key using parent=\u003cvar translate=\"no\"\u003ekey\u003c/var\u003e.\n The (\u003cvar translate=\"no\"\u003ekind\u003c/var\u003e, \u003cvar translate=\"no\"\u003eid\u003c/var\u003e) pairs of the parent key are\n inserted before the (\u003cvar translate=\"no\"\u003ekind\u003c/var\u003e, \u003cvar translate=\"no\"\u003eid\u003c/var\u003e) pairs\n passed explicitly.\n\n The `urlsafe` keyword parameter uses\n a websafe-base64-encoded serialized\n reference\n but it's best to think of it as just an opaque unique\n string.\n\n Additional constructor keyword arguments:\n\n app\n : specify the application id (a string)\n\n namespace\n : specify the namespace (a string)\n\nInstance Methods that Don't Affect the Datastore\n------------------------------------------------\n\nThe following methods access the contents of a key. They do not\nengage in any Datastore I/O activity.\n\npairs()\n\n: Returns a tuple of (kind, id) pairs.\n\nflat()\n\n: Returns a tuple of flattened kind and id values\n (kind1, id1, kind2, id2, ...).\n\napp()\n\n: Returns the application id.\n\nid()\n\n: Returns the string or integer id in the last (kind, id) pair,\n or `None` if the key is incomplete.\n\nstring_id()\n\n: Returns the string id in the last (kind, id) pair,\n or `None` if the key has an integer id or is incomplete.\n\ninteger_id()\n\n: Returns the integer id in the last (kind, id) pair,\n or `None` if the key has an string id or is incomplete.\n\nnamespace()\n\n: Returns the namespace.\n\nkind()\n\n: Returns the kind in the last (kind, id) pair.\n\nparent()\n\n: Returns a Key constructed from all but the last (kind, id) pair\n (or `None` if the key has just one (kind, id) pair).\n\nurlsafe()\n\n: Returns a websafe-base64-encoded serialized version of the key.\n\n **Note:**\n The URL-safe string looks cryptic, but it is not encrypted!\n It can easily be decoded to recover the original entity's kind and\n identifier.\n\nto_old_key()\n\n: Returns a\n [Key](/appengine/docs/legacy/standard/python/datastore/keyclass)\n for the \"old\" Datastore API (`db`).\n\nInstance Methods that Affect the Datastore\n------------------------------------------\n\nThese methods interact with the Datastore.\n\nget(\\*\\*ctx_options)\n\n: Returns the entity for the Key.\n\n **Arguments**\n\n \\*\\*ctx_options\n : [Context options](/appengine/docs/legacy/standard/python/ndb/functions#context_options)\n\nget_async(\\*\\*ctx_options)\n\n: Returns a\n [Future](/appengine/docs/legacy/standard/python/ndb/futureclass)\n whose eventual result is\n the entity for the Key.\n\n **Arguments**\n\n \\*\\*ctx_options\n : [Context options](/appengine/docs/legacy/standard/python/ndb/functions#context_options)\n\ndelete(\\*\\*ctx_options)\n\n: Delete the entity for the Key.\n\n **Arguments**\n\n \\*\\*ctx_options\n : [Context options](/appengine/docs/legacy/standard/python/ndb/functions#context_options)\n\ndelete_async(\\*\\*ctx_options)\n\n: Asynchronously delete the entity for the Key.\n\n **Arguments**\n\n \\*\\*ctx_options\n : [Context options](/appengine/docs/legacy/standard/python/ndb/functions#context_options)\n\nClass Methods\n-------------\n\nfrom_old_key(k)\n\n: Returns an NDB key from the passed in \"old\" Datastore API\n (`db`)\n [Key](/appengine/docs/legacy/standard/python/datastore/keyclass).\n\n **Arguments**\n\n \\*\\*ctx_options\n : [Context options](/appengine/docs/legacy/standard/python/ndb/functions#context_options)"]]