Key
類別的例項代表不變的 Datastore 金鑰。
本頁面中包含 API 的參考說明文件。如需總覽說明,請參閱「NDB 實體和金鑰」。
簡介
Key 是一個不變的 Datastore 金鑰。應用程式通常使用金鑰以參照實體。每一個儲存的實體皆擁有一個金鑰。. 如要取得實體的金鑰,請使用模型的「key」屬性。如要從該金鑰中擷取實體,請呼叫 Key
物件的 get() 方法。
鍵可支援比較,例如 key1 == key2
或 key1 < key2
。這些運算可以拿來比較應用程式 ID、命名空間,以及完整的祖系路徑。當要依照金鑰屬性或金鑰進行排序時,與 Datastore 進行查詢時使用的排序相同。
repr(key)
或 str(key)
會傳回類似於最短建構函式之型式來表示字串,且省略應用程式和命名空間,除非其與預設值不同。
hash(key)
運作。因此,您可以將金鑰儲存在雜湊表中。
建構函式
為了更為彈性及便利,系統支援多個建構函式簽章。
- class Key(kind1, id1, kind2, id2, ...)
- class Key(pairs=[(kind1, id1), (kind2, id2), ...])
- class Key(flat=[kind1, id1, kind2, id2, ...])
- class Key(urlsafe=string)
-
位置引數 kind1、id1、kind2、id2... 依據「祖系」排序。(這是
flat=[kind1, id1, kind2, id2]
的捷徑) 父項排在子項前面。位置引數、
pairs
和flat
建構函式可以使用 parent=key 傳入另一個金鑰。父項金鑰的 (kind、id) 組合會插入明確傳遞的 (kind、id) 組合之前。urlsafe
關鍵字參數會使用以網路安全 Base64 編碼的序列化參照,但最好將其視為不透明的專屬字串。其他建構函式關鍵字引數:
- 應用程式
- 指定應用程式 ID (字串)
- namespace
- 指定命名空間 (字串)
不影響 Datastore 的範例方法
使用以下方法存取金鑰的內容,這些方法不涉及 Datastore 的 I/O 活動。
- pairs()。
-
傳回 (kind, id) 的組合。
- flat()
-
傳回整併種類的組合以及 id 值 (kind1, id1, kind2, id2, ...)。
- app()
-
傳回應用程式 id。
- id()
-
傳回最後一個 (kind, id) 組合的字串或整數 ID,如果鍵不完整,則傳回
None
。 - string_id()
-
傳回最後一個 (kind, id) 組合的字串 ID,如果鍵有整數 ID 或不完整,則傳回
None
。 - integer_id()
-
傳回最後一個 (kind, id) 組合的整數 ID,如果鍵有字串 ID 或不完整,則傳回
None
。 - namespace()
-
傳回命名空間。
- kind()
-
傳回最後一個 (kind, id) 組合的種類。
- parent()
-
傳回從所有 (kind, id) 組成的金鑰,但不包含最後一個組合 (如果金鑰只有一個 (kind, id) 組合,則傳回
None
)。 - urlsafe()
-
傳回金鑰的「websafe-base64-encoded」編碼序列化版本。
注意:可在網路上安全使用的字串看起來很神秘,但並未加密!這類資料很容易解碼,可用來復原原始實體的種類和 ID。
- to_old_key()
-
為「舊版」Datastore API (
db
) 傳回Key
。
影響 Datastore 的範例方法
這些方法與 Datastore 的互動。
- get(**ctx_options)
-
傳回 Key 的實體。
引數
- **ctx_options
- 背景資訊選項
- get_async(**ctx_options)
-
傳回
Future
,其最終結果為 Key 的實體。引數
- **ctx_options
- 背景資訊選項
- delete(**ctx_options)
-
刪除 Key 的實體。
引數
- **ctx_options
- 背景資訊選項
- delete_async(**ctx_options)
-
非同步刪除 Key 的實體。
引數
- **ctx_options
- 背景資訊選項