-
Notifications
You must be signed in to change notification settings - Fork 64
/
key.py
1613 lines (1328 loc) · 57.9 KB
/
key.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Provides a :class:`.Key` for Google Cloud Datastore.
.. testsetup:: *
from google.cloud import ndb
A key encapsulates the following pieces of information, which together
uniquely designate a (possible) entity in Google Cloud Datastore:
* a Google Cloud Platform project (a string)
* a list of one or more ``(kind, id)`` pairs where ``kind`` is a string
and ``id`` is either a string or an integer
* an optional database (a string)
* an optional namespace (a string)
The application ID must always be part of the key, but since most
applications can only access their own entities, it defaults to the
current application ID and you rarely need to worry about it.
The database is an optional database ID. If unspecified, it defaults
to that of the client.
For usage in Cloud NDB, the default database should always be referred
to as an empty string; please do not use "(default)".
The namespace designates a top-level partition of the key space for a
particular application. If you've never heard of namespaces, you can
safely ignore this feature.
Most of the action is in the ``(kind, id)`` pairs. A key must have at
least one ``(kind, id)`` pair. The last ``(kind, id)`` pair gives the kind
and the ID of the entity that the key refers to, the others merely
specify a "parent key".
The kind is a string giving the name of the model class used to
represent the entity. In more traditional databases this would be
the table name. A model class is a Python class derived from
:class:`.Model`. Only the class name itself is used as the kind. This means
all your model classes must be uniquely named within one application. You can
override this on a per-class basis.
The ID is either a string or an integer. When the ID is a string, the
application is in control of how it assigns IDs. For example, you
could use an email address as the ID for Account entities.
To use integer IDs, it's common to let the datastore choose a unique ID for
an entity when first inserted into the datastore. The ID can be set to
:data:`None` to represent the key for an entity that hasn't yet been
inserted into the datastore. The completed key (including the assigned ID)
will be returned after the entity is successfully inserted into the datastore.
A key for which the ID of the last ``(kind, id)`` pair is set to :data:`None`
is called an **incomplete key** or **partial key**. Such keys can only be used
to insert entities into the datastore.
A key with exactly one ``(kind, id)`` pair is called a top level key or a
root key. Top level keys are also used as entity groups, which play a
role in transaction management.
If there is more than one ``(kind, id)`` pair, all but the last pair
represent the "ancestor path", also known as the key of the "parent entity".
Other constraints:
* Kinds and string IDs must not be empty and must be at most 1500 bytes
long (after UTF-8 encoding)
* Integer IDs must be at least ``1`` and at most ``2**63 - 1`` (i.e. the
positive part of the range for a 64-bit signed integer)
In the "legacy" Google App Engine runtime, the default namespace could be
set via the namespace manager (``google.appengine.api.namespace_manager``).
On the gVisor Google App Engine runtime (e.g. Python 3.7), the namespace
manager is not available so the default is to have an unset or empty
namespace. To explicitly select the empty namespace pass ``namespace=""``.
"""
import base64
import functools
from google.cloud.datastore import _app_engine_key_pb2
from google.cloud.datastore import key as _key_module
import google.cloud.datastore
from google.cloud.ndb import exceptions
from google.cloud.ndb import _options
from google.cloud.ndb import tasklets
from google.cloud.ndb import utils
__all__ = ["Key", "UNDEFINED"]
_APP_ID_ENVIRONMENT = "APPLICATION_ID"
_APP_ID_DEFAULT = "_"
_WRONG_TYPE = "Cannot construct Key reference on non-Key class; received {!r}"
_REFERENCE_APP_MISMATCH = (
"Key reference constructed uses a different app {!r} than the one specified {!r}"
)
_REFERENCE_DATABASE_MISMATCH = "Key reference constructed uses a different database {!r} than the one specified {!r}"
_REFERENCE_NAMESPACE_MISMATCH = (
"Key reference constructed uses a different namespace {!r} than "
"the one specified {!r}"
)
_INVALID_ID_TYPE = "Key ID must be a string or a number; received {!r}"
_NO_LEGACY = "The `google.appengine.ext.db` module is not available."
_MAX_INTEGER_ID = 0x7FFFFFFFFFFFFFFF # 2 ** 63 - 1
_MAX_KEYPART_BYTES = 1500
_BAD_KIND = "Key kind string must be a non-empty string up to {:d} bytes; received {}"
_BAD_INTEGER_ID = "Key ID number is outside of range [1, 2^63 - 1]; received {:d}"
_BAD_STRING_ID = (
"Key name strings must be non-empty strings up to {:d} bytes; received {}"
)
UNDEFINED = object()
"""Sentinel value.
Used to indicate a database or namespace hasn't been explicitly set in key construction.
Used to distinguish between not passing a value and passing `None`, which
indicates the default database/namespace.
"""
class Key(object):
"""An immutable datastore key.
For flexibility and convenience, multiple constructor signatures are
supported.
The primary way to construct a key is using positional arguments:
.. testsetup:: *
from unittest import mock
from google.cloud.ndb import context as context_module
client = mock.Mock(
project="testing",
database=None,
namespace=None,
stub=mock.Mock(spec=()),
spec=("project", "database", "namespace", "stub"),
)
context = context_module.Context(client).use()
context.__enter__()
kind1, id1 = "Parent", "C"
kind2, id2 = "Child", 42
.. testcleanup:: *
context.__exit__(None, None, None)
.. doctest:: key-constructor-primary
>>> ndb.Key(kind1, id1, kind2, id2)
Key('Parent', 'C', 'Child', 42)
This is shorthand for either of the following two longer forms:
.. doctest:: key-constructor-flat-or-pairs
>>> ndb.Key(pairs=[(kind1, id1), (kind2, id2)])
Key('Parent', 'C', 'Child', 42)
>>> ndb.Key(flat=[kind1, id1, kind2, id2])
Key('Parent', 'C', 'Child', 42)
Either of the above constructor forms can additionally pass in another
key via the ``parent`` keyword. The ``(kind, id)`` pairs of the parent key
are inserted before the ``(kind, id)`` pairs passed explicitly.
.. doctest:: key-constructor-parent
>>> parent = ndb.Key(kind1, id1)
>>> parent
Key('Parent', 'C')
>>> ndb.Key(kind2, id2, parent=parent)
Key('Parent', 'C', 'Child', 42)
You can also construct a Key from a "urlsafe" encoded string:
.. doctest:: key-constructor-urlsafe
>>> ndb.Key(urlsafe=b"agdleGFtcGxlcgsLEgRLaW5kGLkKDA")
Key('Kind', 1337, project='example')
For rare use cases the following constructors exist:
.. testsetup:: key-constructor-rare
from google.cloud.datastore import _app_engine_key_pb2
reference = _app_engine_key_pb2.Reference(
app="example",
path=_app_engine_key_pb2.Path(element=[
_app_engine_key_pb2.Path.Element(type="Kind", id=1337),
]),
)
.. doctest:: key-constructor-rare
>>> # Passing in a low-level Reference object
>>> reference
app: "example"
path {
element {
type: "Kind"
id: 1337
}
}
<BLANKLINE>
>>> ndb.Key(reference=reference)
Key('Kind', 1337, project='example')
>>> # Passing in a serialized low-level Reference
>>> serialized = reference.SerializeToString()
>>> serialized
b'j\\x07exampler\\x0b\\x0b\\x12\\x04Kind\\x18\\xb9\\n\\x0c'
>>> ndb.Key(serialized=serialized)
Key('Kind', 1337, project='example')
>>> # For unpickling, the same as ndb.Key(**kwargs)
>>> kwargs = {"pairs": [("Cheese", "Cheddar")], "namespace": "good"}
>>> ndb.Key(kwargs)
Key('Cheese', 'Cheddar', namespace='good')
The "urlsafe" string is really a websafe-base64-encoded serialized
``Reference``, but it's best to think of it as just an opaque unique
string.
If a ``Reference`` is passed (using one of the ``reference``,
``serialized`` or ``urlsafe`` keywords), the positional arguments and
``namespace`` must match what is already present in the ``Reference``
(after decoding if necessary). The parent keyword cannot be combined with
a ``Reference`` in any form.
Keys are immutable, which means that a Key object cannot be modified
once it has been created. This is enforced by the implementation as
well as Python allows.
Keys also support interaction with the datastore; the methods :meth:`get`,
:meth:`get_async`, :meth:`delete` and :meth:`delete_async` are
the only ones that engage in any kind of I/O activity.
Keys may be pickled.
Subclassing Key is best avoided; it would be hard to get right.
Args:
path_args (Union[Tuple[str, ...], Tuple[Dict]]): Either a tuple of
``(kind, id)`` pairs or a single dictionary containing only keyword
arguments.
reference (Optional[\
~google.cloud.datastore._app_engine_key_pb2.Reference]): A
reference protobuf representing a key.
serialized (Optional[bytes]): A reference protobuf serialized to bytes.
urlsafe (Optional[bytes]): A reference protobuf serialized to bytes. The
raw bytes are then converted to a websafe base64-encoded string.
pairs (Optional[Iterable[Tuple[str, Union[str, int]]]]): An iterable
of ``(kind, id)`` pairs. If this argument is used, then
``path_args`` should be empty.
flat (Optional[Iterable[Union[str, int]]]): An iterable of the
``(kind, id)`` pairs but flattened into a single value. For
example, the pairs ``[("Parent", 1), ("Child", "a")]`` would be
flattened to ``["Parent", 1, "Child", "a"]``.
project (Optional[str]): The Google Cloud Platform project (previously
on Google App Engine, this was called the Application ID).
app (Optional[str]): DEPRECATED: Synonym for ``project``.
namespace (Optional[str]): The namespace for the key.
parent (Optional[Key]): The parent of the key being
constructed. If provided, the key path will be **relative** to the
parent key's path.
database (Optional[str]): The database to use.
Defaults to that of the client if a parent was specified, and
to the default database if it was not.
Raises:
TypeError: If none of ``reference``, ``serialized``, ``urlsafe``,
``pairs`` or ``flat`` is provided as an argument and no positional
arguments were given with the path.
"""
_hash_value = None
def __new__(cls, *path_args, **kwargs):
_constructor_handle_positional(path_args, kwargs)
instance = super(Key, cls).__new__(cls)
if "reference" in kwargs or "serialized" in kwargs or "urlsafe" in kwargs:
ds_key, reference = _parse_from_ref(cls, **kwargs)
elif "pairs" in kwargs or "flat" in kwargs:
ds_key = _parse_from_args(**kwargs)
reference = None
else:
raise TypeError("Key() cannot create a Key instance without arguments.")
instance._key = ds_key
instance._reference = reference
return instance
@classmethod
def _from_ds_key(cls, ds_key):
"""Factory constructor for a :class:`~google.cloud.datastore.key.Key`.
This bypasses the actual constructor and directly sets the ``_key``
attribute to ``ds_key``.
Args:
ds_key (~google.cloud.datastore.key.Key): A key from
``google-cloud-datastore``.
Returns:
Key: The constructed :class:`Key`.
"""
key = super(Key, cls).__new__(cls)
key._key = ds_key
key._reference = None
return key
def __repr__(self):
"""String representation used by :class:`str() <str>` and :func:`repr`.
We produce a short string that conveys all relevant information,
suppressing project, database, and namespace when they are equal to their
respective defaults.
In many cases, this string should be able to be used to invoke the constructor.
For example:
.. doctest:: key-repr
>>> key = ndb.Key("hi", 100)
>>> repr(key)
"Key('hi', 100)"
>>>
>>> key = ndb.Key(
... "bye", "hundred", project="specific", database="db", namespace="space",
... )
>>> str(key)
"Key('bye', 'hundred', project='specific', database='db', namespace='space')"
"""
args = ["{!r}".format(item) for item in self.flat()]
if self.project() != _project_from_app(None):
args.append("project={!r}".format(self.app()))
if self.database():
args.append("database={!r}".format(self.database()))
if self.namespace() is not None:
args.append("namespace={!r}".format(self.namespace()))
return "Key({})".format(", ".join(args))
def __str__(self):
"""Alias for :meth:`__repr__`."""
return self.__repr__()
def __hash__(self):
"""Hash value, for use in dictionary lookups.
.. note::
This ignores ``app``, ``database``, and ``namespace``. Since :func:`hash` isn't
expected to return a unique value (it just reduces the chance of
collision), this doesn't try to increase entropy by including other
values. The primary concern is that hashes of equal keys are
equal, not the other way around.
"""
hash_value = self._hash_value
if hash_value is None:
self._hash_value = hash_value = hash(self.pairs())
return hash_value
def _tuple(self):
"""Helper to return an orderable tuple."""
return (self.app(), self.namespace(), self.database() or "", self.pairs())
def __eq__(self, other):
"""Equality comparison operation."""
if not isinstance(other, Key):
return NotImplemented
return self._tuple() == other._tuple()
def __ne__(self, other):
"""The opposite of __eq__."""
if not isinstance(other, Key):
return NotImplemented
return not self.__eq__(other)
def __lt__(self, other):
"""Less than ordering."""
if not isinstance(other, Key):
raise TypeError
return self._tuple() < other._tuple()
def __le__(self, other):
"""Less than or equal ordering."""
if not isinstance(other, Key):
raise TypeError
return self._tuple() <= other._tuple()
def __gt__(self, other):
"""Greater than ordering."""
if not isinstance(other, Key):
raise TypeError
return not self <= other
def __ge__(self, other):
"""Greater than or equal ordering."""
if not isinstance(other, Key):
raise TypeError
return not self < other
def __getstate__(self):
"""Private API used for pickling.
Returns:
Tuple[Dict[str, Any]]: A tuple containing a single dictionary of
state to pickle. The dictionary has four keys: ``pairs``, ``app``,
``database``, and ``namespace``.
"""
to_pickle = (
{
"pairs": self.pairs(),
"app": self.app(),
"namespace": self.namespace(),
},
)
if self.database():
to_pickle[0]["database"] = self.database()
return to_pickle
def __setstate__(self, state):
"""Private API used for unpickling.
Args:
state (Tuple[Dict[str, Any]]): A tuple containing a single
dictionary of pickled state. This should match the signature
returned from :func:`__getstate__`, in particular, it should
have four keys: ``pairs``, ``app``, ``database``, and ``namespace``.
Raises:
TypeError: If the ``state`` does not have length 1.
TypeError: If the single element in ``state`` is not a dictionary.
"""
if len(state) != 1:
msg = "Invalid state length, expected 1; received {:d}".format(len(state))
raise TypeError(msg)
kwargs = state[0]
if not isinstance(kwargs, dict):
raise TypeError(
"Key accepts a dict of keyword arguments as state; "
"received {!r}".format(kwargs)
)
flat = _get_path(None, kwargs["pairs"])
_clean_flat_path(flat)
project = _project_from_app(kwargs["app"])
database = None
if "database" in kwargs:
database = kwargs["database"]
self._key = _key_module.Key(
*flat,
project=project,
namespace=kwargs["namespace"],
database=database,
)
self._reference = None
def __getnewargs__(self):
"""Private API used to specify ``__new__`` arguments when unpickling.
.. note::
This method is provided for backwards compatibility, though it
isn't needed.
Returns:
Tuple[Dict[str, Any]]: A tuple containing a single dictionary of
state to pickle. The dictionary has four keys: ``pairs``, ``app``,
``database`` and ``namespace``.
"""
return (
{
"pairs": self.pairs(),
"app": self.app(),
"namespace": self.namespace(),
"database": self.database() if self.database() is not None else None,
},
)
def parent(self):
"""Parent key constructed from all but the last ``(kind, id)`` pairs.
If there is only one ``(kind, id)`` pair, return :data:`None`.
.. doctest:: key-parent
>>> key = ndb.Key(
... pairs=[
... ("Purchase", "Food"),
... ("Type", "Drink"),
... ("Coffee", 11),
... ]
... )
>>> parent = key.parent()
>>> parent
Key('Purchase', 'Food', 'Type', 'Drink')
>>>
>>> grandparent = parent.parent()
>>> grandparent
Key('Purchase', 'Food')
>>>
>>> grandparent.parent() is None
True
"""
if self._key.parent is None:
return None
return Key._from_ds_key(self._key.parent)
def root(self):
"""The root key.
This is either the current key or the highest parent.
.. doctest:: key-root
>>> key = ndb.Key("a", 1, "steak", "sauce")
>>> root_key = key.root()
>>> root_key
Key('a', 1)
>>> root_key.root() is root_key
True
"""
root_key = self._key
while root_key.parent is not None:
root_key = root_key.parent
if root_key is self._key:
return self
return Key._from_ds_key(root_key)
def namespace(self):
"""The namespace for the key, if set.
.. doctest:: key-namespace
>>> key = ndb.Key("A", "B")
>>> key.namespace() is None
True
>>>
>>> key = ndb.Key("A", "B", namespace="rock")
>>> key.namespace()
'rock'
"""
return self._key.namespace
def project(self):
"""The project ID for the key.
.. warning::
This **may** differ from the original ``app`` passed in to the
constructor. This is because prefixed application IDs like
``s~example`` are "legacy" identifiers from Google App Engine.
They have been replaced by equivalent project IDs, e.g. here it
would be ``example``.
.. doctest:: key-app
>>> key = ndb.Key("A", "B", project="s~example")
>>> key.project()
'example'
>>>
>>> key = ndb.Key("A", "B", project="example")
>>> key.project()
'example'
"""
return self._key.project
app = project
def database(self):
"""The database ID for the key.
.. doctest:: key-database
>>> key = ndb.Key("A", "B", database="mydb")
>>> key.database()
'mydb'
"""
return self._key.database
def id(self):
"""The string or integer ID in the last ``(kind, id)`` pair, if any.
.. doctest:: key-id
>>> key_int = ndb.Key("A", 37)
>>> key_int.id()
37
>>> key_str = ndb.Key("A", "B")
>>> key_str.id()
'B'
>>> key_partial = ndb.Key("A", None)
>>> key_partial.id() is None
True
"""
return self._key.id_or_name
def string_id(self):
"""The string ID in the last ``(kind, id)`` pair, if any.
.. doctest:: key-string-id
>>> key_int = ndb.Key("A", 37)
>>> key_int.string_id() is None
True
>>> key_str = ndb.Key("A", "B")
>>> key_str.string_id()
'B'
>>> key_partial = ndb.Key("A", None)
>>> key_partial.string_id() is None
True
"""
return self._key.name
def integer_id(self):
"""The integer ID in the last ``(kind, id)`` pair, if any.
.. doctest:: key-integer-id
>>> key_int = ndb.Key("A", 37)
>>> key_int.integer_id()
37
>>> key_str = ndb.Key("A", "B")
>>> key_str.integer_id() is None
True
>>> key_partial = ndb.Key("A", None)
>>> key_partial.integer_id() is None
True
"""
return self._key.id
def pairs(self):
"""The ``(kind, id)`` pairs for the key.
.. doctest:: key-pairs
>>> key = ndb.Key("Satellite", "Moon", "Space", "Dust")
>>> key.pairs()
(('Satellite', 'Moon'), ('Space', 'Dust'))
>>>
>>> partial_key = ndb.Key("Known", None)
>>> partial_key.pairs()
(('Known', None),)
"""
flat = self.flat()
pairs = []
for i in range(0, len(flat), 2):
pairs.append(flat[i : i + 2]) # noqa: E203
return tuple(pairs)
def flat(self):
"""The flat path for the key.
.. doctest:: key-flat
>>> key = ndb.Key("Satellite", "Moon", "Space", "Dust")
>>> key.flat()
('Satellite', 'Moon', 'Space', 'Dust')
>>>
>>> partial_key = ndb.Key("Known", None)
>>> partial_key.flat()
('Known', None)
"""
flat_path = self._key.flat_path
if len(flat_path) % 2 == 1:
flat_path += (None,)
return flat_path
def kind(self):
"""The kind of the entity referenced.
This comes from the last ``(kind, id)`` pair.
.. doctest:: key-kind
>>> key = ndb.Key("Satellite", "Moon", "Space", "Dust")
>>> key.kind()
'Space'
>>>
>>> partial_key = ndb.Key("Known", None)
>>> partial_key.kind()
'Known'
"""
return self._key.kind
def reference(self):
"""The ``Reference`` protobuf object for this key.
The return value will be stored on the current key, so the caller
promises not to mutate it.
.. doctest:: key-reference
>>> key = ndb.Key("Trampoline", 88, project="xy", database="wv", namespace="zt")
>>> key.reference()
app: "xy"
name_space: "zt"
path {
element {
type: "Trampoline"
id: 88
}
}
database_id: "wv"
<BLANKLINE>
"""
if self._reference is None:
if self._key.database:
self._reference = _app_engine_key_pb2.Reference(
app=self._key.project,
path=_to_legacy_path(self._key.path),
database_id=self._key.database,
name_space=self._key.namespace,
)
else:
self._reference = _app_engine_key_pb2.Reference(
app=self._key.project,
path=_to_legacy_path(self._key.path),
name_space=self._key.namespace,
)
return self._reference
def serialized(self):
"""A ``Reference`` protobuf serialized to bytes.
.. doctest:: key-serialized
>>> key = ndb.Key("Kind", 1337, project="example", database="example-db")
>>> key.serialized()
b'j\\x07exampler\\x0b\\x0b\\x12\\x04Kind\\x18\\xb9\\n\\x0c\\xba\\x01\\nexample-db'
"""
reference = self.reference()
return reference.SerializeToString()
def urlsafe(self):
"""A ``Reference`` protobuf serialized and encoded as urlsafe base 64.
.. doctest:: key-urlsafe
>>> key = ndb.Key("Kind", 1337, project="example")
>>> key.urlsafe()
b'agdleGFtcGxlcgsLEgRLaW5kGLkKDA'
"""
raw_bytes = self.serialized()
return base64.urlsafe_b64encode(raw_bytes).strip(b"=")
def to_legacy_urlsafe(self, location_prefix):
"""
A urlsafe serialized ``Reference`` protobuf with an App Engine prefix.
This will produce a urlsafe string which includes an App Engine
location prefix ("partition"), compatible with the Google Datastore
admin console.
This only supports the default database. For a named database,
please use urlsafe() instead.
Arguments:
location_prefix (str): A location prefix ("partition") to be
prepended to the key's `project` when serializing the key. A
typical value is "s~", but "e~" or other partitions are
possible depending on the project's region and other factors.
.. doctest:: key-legacy-urlsafe
>>> key = ndb.Key("Kind", 1337, project="example")
>>> key.to_legacy_urlsafe("s~")
b'aglzfmV4YW1wbGVyCwsSBEtpbmQYuQoM'
"""
if self._key.database:
raise ValueError("to_legacy_urlsafe only supports the default database")
return google.cloud.datastore.Key(
*self.flat(),
**{"namespace": self._key.namespace, "project": self._key.project},
).to_legacy_urlsafe(location_prefix=location_prefix)
@_options.ReadOptions.options
@utils.positional(1)
def get(
self,
read_consistency=None,
read_policy=None,
transaction=None,
retries=None,
timeout=None,
deadline=None,
use_cache=None,
use_global_cache=None,
use_datastore=None,
global_cache_timeout=None,
use_memcache=None,
memcache_timeout=None,
max_memcache_items=None,
force_writes=None,
_options=None,
):
"""Synchronously get the entity for this key.
Returns the retrieved :class:`.Model` or :data:`None` if there is no
such entity.
Args:
read_consistency: Set this to ``ndb.EVENTUAL`` if, instead of
waiting for the Datastore to finish applying changes to all
returned results, you wish to get possibly-not-current results
faster. You can't do this if using a transaction.
transaction (bytes): Any results returned will be consistent with
the Datastore state represented by this transaction id.
Defaults to the currently running transaction. Cannot be used
with ``read_consistency=ndb.EVENTUAL``.
retries (int): Number of times to retry this operation in the case
of transient server errors. Operation will potentially be tried
up to ``retries`` + 1 times. Set to ``0`` to try operation only
once, with no retries.
timeout (float): Override the gRPC timeout, in seconds.
deadline (float): DEPRECATED: Synonym for ``timeout``.
use_cache (bool): Specifies whether to store entities in in-process
cache; overrides in-process cache policy for this operation.
use_global_cache (bool): Specifies whether to store entities in
global cache; overrides global cache policy for this operation.
use_datastore (bool): Specifies whether to store entities in
Datastore; overrides Datastore policy for this operation.
global_cache_timeout (int): Maximum lifetime for entities in global
cache; overrides global cache timeout policy for this
operation.
use_memcache (bool): DEPRECATED: Synonym for ``use_global_cache``.
memcache_timeout (int): DEPRECATED: Synonym for
``global_cache_timeout``.
max_memcache_items (int): No longer supported.
read_policy: DEPRECATED: Synonym for ``read_consistency``.
force_writes (bool): No longer supported.
Returns:
Union[:class:`.Model`, :data:`None`]
"""
return self.get_async(_options=_options).result()
@_options.ReadOptions.options
@utils.positional(1)
def get_async(
self,
read_consistency=None,
read_policy=None,
transaction=None,
retries=None,
timeout=None,
deadline=None,
use_cache=None,
use_global_cache=None,
use_datastore=None,
global_cache_timeout=None,
use_memcache=None,
memcache_timeout=None,
max_memcache_items=None,
force_writes=None,
_options=None,
):
"""Asynchronously get the entity for this key.
The result for the returned future will either be the retrieved
:class:`.Model` or :data:`None` if there is no such entity.
Args:
read_consistency: Set this to ``ndb.EVENTUAL`` if, instead of
waiting for the Datastore to finish applying changes to all
returned results, you wish to get possibly-not-current results
faster. You can't do this if using a transaction.
transaction (bytes): Any results returned will be consistent with
the Datastore state represented by this transaction id.
Defaults to the currently running transaction. Cannot be used
with ``read_consistency=ndb.EVENTUAL``.
retries (int): Number of times to retry this operation in the case
of transient server errors. Operation will potentially be tried
up to ``retries`` + 1 times. Set to ``0`` to try operation only
once, with no retries.
timeout (float): Override the gRPC timeout, in seconds.
deadline (float): DEPRECATED: Synonym for ``timeout``.
use_cache (bool): Specifies whether to store entities in in-process
cache; overrides in-process cache policy for this operation.
use_global_cache (bool): Specifies whether to store entities in
global cache; overrides global cache policy for this operation.
use_datastore (bool): Specifies whether to store entities in
Datastore; overrides Datastore policy for this operation.
global_cache_timeout (int): Maximum lifetime for entities in global
cache; overrides global cache timeout policy for this
operation.
use_memcache (bool): DEPRECATED: Synonym for ``use_global_cache``.
memcache_timeout (int): DEPRECATED: Synonym for
``global_cache_timeout``.
max_memcache_items (int): No longer supported.
read_policy: DEPRECATED: Synonym for ``read_consistency``.
force_writes (bool): No longer supported.
Returns:
:class:`~google.cloud.ndb.tasklets.Future`
"""
# Avoid circular import in Python 2.7
from google.cloud.ndb import model
from google.cloud.ndb import context as context_module
from google.cloud.ndb import _datastore_api
cls = model.Model._kind_map.get(self.kind())
if cls:
cls._pre_get_hook(self)
@tasklets.tasklet
def get():
context = context_module.get_context()
use_cache = context._use_cache(self, _options)
if use_cache:
try:
# This result may be None, if None is cached for this key.
result = context.cache.get_and_validate(self)
except KeyError:
pass
else:
raise tasklets.Return(result)
entity_pb = yield _datastore_api.lookup(self._key, _options)
if entity_pb is not _datastore_api._NOT_FOUND:
result = model._entity_from_protobuf(entity_pb)
else:
result = None
if use_cache:
context.cache[self] = result
raise tasklets.Return(result)
future = get()
if cls:
future.add_done_callback(functools.partial(cls._post_get_hook, self))
return future
@_options.Options.options
@utils.positional(1)
def delete(
self,
retries=None,
timeout=None,
deadline=None,
use_cache=None,
use_global_cache=None,
use_datastore=None,
global_cache_timeout=None,
use_memcache=None,
memcache_timeout=None,
max_memcache_items=None,
force_writes=None,
_options=None,
):
"""Synchronously delete the entity for this key.
This is a no-op if no such entity exists.
Note:
If in a transaction, the entity can only be deleted at transaction
commit time. In that case, this function will schedule the entity
to be deleted as part of the transaction and will return
immediately, which is effectively the same as calling
:meth:`delete_async` and ignoring the returned future. If not in a
transaction, this function will block synchronously until the
entity is deleted, as one would expect.
Args:
timeout (float): Override the gRPC timeout, in seconds.
deadline (float): DEPRECATED: Synonym for ``timeout``.
use_cache (bool): Specifies whether to store entities in in-process
cache; overrides in-process cache policy for this operation.
use_global_cache (bool): Specifies whether to store entities in
global cache; overrides global cache policy for this operation.
use_datastore (bool): Specifies whether to store entities in
Datastore; overrides Datastore policy for this operation.
global_cache_timeout (int): Maximum lifetime for entities in global
cache; overrides global cache timeout policy for this
operation.