-
Notifications
You must be signed in to change notification settings - Fork 64
/
model.py
6627 lines (5418 loc) · 237 KB
/
model.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.
"""Model classes for datastore objects and properties for models.
.. testsetup:: *
from unittest import mock
from google.cloud import ndb
from google.cloud.ndb import context as context_module
client = mock.Mock(
project="testing",
database=None,
namespace=None,
stub=mock.Mock(spec=()),
spec=("project", "namespace", "database", "stub"),
)
context = context_module.Context(client).use()
context.__enter__()
.. testcleanup:: *
context.__exit__(None, None, None)
A model class represents the structure of entities stored in the datastore.
Applications define model classes to indicate the structure of their entities,
then instantiate those model classes to create entities.
All model classes must inherit (directly or indirectly) from Model. Through
the magic of metaclasses, straightforward assignments in the model class
definition can be used to declare the model's structure::
class Person(Model):
name = StringProperty()
age = IntegerProperty()
We can now create a Person entity and write it to Cloud Datastore::
person = Person(name='Arthur Dent', age=42)
key = person.put()
The return value from put() is a Key (see the documentation for
``ndb/key.py``), which can be used to retrieve the same entity later::
person2 = key.get()
person2 == person # Returns True
To update an entity, simply change its attributes and write it back (note that
this doesn't change the key)::
person2.name = 'Arthur Philip Dent'
person2.put()
We can also delete an entity (by using the key)::
key.delete()
The property definitions in the class body tell the system the names and the
types of the fields to be stored in Cloud Datastore, whether they must be
indexed, their default value, and more.
Many different Property types exist. Most are indexed by default, the
exceptions are indicated in the list below:
- :class:`StringProperty`: a short text string, limited to at most 1500 bytes
(when UTF-8 encoded from :class:`str` to bytes).
- :class:`TextProperty`: an unlimited text string; unindexed.
- :class:`BlobProperty`: an unlimited byte string; unindexed.
- :class:`IntegerProperty`: a 64-bit signed integer.
- :class:`FloatProperty`: a double precision floating point number.
- :class:`BooleanProperty`: a bool value.
- :class:`DateTimeProperty`: a datetime object. Note: Datastore always uses
UTC as the timezone.
- :class:`DateProperty`: a date object.
- :class:`TimeProperty`: a time object.
- :class:`GeoPtProperty`: a geographical location, i.e. (latitude, longitude).
- :class:`KeyProperty`: a Cloud Datastore Key value, optionally constrained to
referring to a specific kind.
- :class:`UserProperty`: a User object (for backwards compatibility only)
- :class:`StructuredProperty`: a field that is itself structured like an
entity; see below for more details.
- :class:`LocalStructuredProperty`: like StructuredProperty but the on-disk
representation is an opaque blob; unindexed.
- :class:`ComputedProperty`: a property whose value is computed from other
properties by a user-defined function. The property value is written to Cloud
Datastore so that it can be used in queries, but the value from Cloud
Datastore is not used when the entity is read back.
- :class:`GenericProperty`: a property whose type is not constrained; mostly
used by the Expando class (see below) but also usable explicitly.
- :class:`JsonProperty`: a property whose value is any object that can be
serialized using JSON; the value written to Cloud Datastore is a JSON
representation of that object.
- :class:`PickleProperty`: a property whose value is any object that can be
serialized using Python's pickle protocol; the value written to the Cloud
Datastore is the pickled representation of that object, using the highest
available pickle protocol
Most Property classes have similar constructor signatures. They
accept several optional keyword arguments:
- name=<string>: the name used to store the property value in the datastore.
Unlike the following options, this may also be given as a positional
argument.
- indexed=<bool>: indicates whether the property should be indexed (allowing
queries on this property's value).
- repeated=<bool>: indicates that this property can have multiple values in
the same entity.
- write_empty_list<bool>: For repeated value properties, controls whether
properties with no elements (the empty list) is written to Datastore. If
true, written, if false, then nothing is written to Datastore.
- required=<bool>: indicates that this property must be given a value.
- default=<value>: a default value if no explicit value is given.
- choices=<list of values>: a list or tuple of allowable values.
- validator=<function>: a general-purpose validation function. It will be
called with two arguments (prop, value) and should either return the
validated value or raise an exception. It is also allowed for the function
to modify the value, but the function should be idempotent. For example: a
validator that returns value.strip() or value.lower() is fine, but one that
returns value + '$' is not).
- verbose_name=<value>: A human readable name for this property. This human
readable name can be used for html form labels.
The repeated and required/default options are mutually exclusive: a repeated
property cannot be required nor can it specify a default value (the default is
always an empty list and an empty list is always an allowed value), but a
required property can have a default.
Some property types have additional arguments. Some property types do not
support all options.
Repeated properties are always represented as Python lists; if there is only
one value, the list has only one element. When a new list is assigned to a
repeated property, all elements of the list are validated. Since it is also
possible to mutate lists in place, repeated properties are re-validated before
they are written to the datastore.
No validation happens when an entity is read from Cloud Datastore; however
property values read that have the wrong type (e.g. a string value for an
IntegerProperty) are ignored.
For non-repeated properties, None is always a possible value, and no validation
is called when the value is set to None. However for required properties,
writing the entity to Cloud Datastore requires the value to be something other
than None (and valid).
The StructuredProperty is different from most other properties; it lets you
define a sub-structure for your entities. The substructure itself is defined
using a model class, and the attribute value is an instance of that model
class. However, it is not stored in the datastore as a separate entity;
instead, its attribute values are included in the parent entity using a naming
convention (the name of the structured attribute followed by a dot followed by
the name of the subattribute). For example::
class Address(Model):
street = StringProperty()
city = StringProperty()
class Person(Model):
name = StringProperty()
address = StructuredProperty(Address)
p = Person(name='Harry Potter',
address=Address(street='4 Privet Drive',
city='Little Whinging'))
k = p.put()
This would write a single 'Person' entity with three attributes (as you could
verify using the Datastore Viewer in the Admin Console)::
name = 'Harry Potter'
address.street = '4 Privet Drive'
address.city = 'Little Whinging'
Structured property types can be nested arbitrarily deep, but in a hierarchy of
nested structured property types, only one level can have the repeated flag
set. It is fine to have multiple structured properties referencing the same
model class.
It is also fine to use the same model class both as a top-level entity class
and as for a structured property; however, queries for the model class will
only return the top-level entities.
The LocalStructuredProperty works similar to StructuredProperty on the Python
side. For example::
class Address(Model):
street = StringProperty()
city = StringProperty()
class Person(Model):
name = StringProperty()
address = LocalStructuredProperty(Address)
p = Person(name='Harry Potter',
address=Address(street='4 Privet Drive',
city='Little Whinging'))
k = p.put()
However, the data written to Cloud Datastore is different; it writes a 'Person'
entity with a 'name' attribute as before and a single 'address' attribute
whose value is a blob which encodes the Address value (using the standard
"protocol buffer" encoding).
The Model class offers basic query support. You can create a Query object by
calling the query() class method. Iterating over a Query object returns the
entities matching the query one at a time. Query objects are fully described
in the documentation for query, but there is one handy shortcut that is only
available through Model.query(): positional arguments are interpreted as filter
expressions which are combined through an AND operator. For example::
Person.query(Person.name == 'Harry Potter', Person.age >= 11)
is equivalent to::
Person.query().filter(Person.name == 'Harry Potter', Person.age >= 11)
Keyword arguments passed to .query() are passed along to the Query()
constructor.
It is possible to query for field values of structured properties. For
example::
qry = Person.query(Person.address.city == 'London')
A number of top-level functions also live in this module:
- :func:`get_multi` reads multiple entities at once.
- :func:`put_multi` writes multiple entities at once.
- :func:`delete_multi` deletes multiple entities at once.
All these have a corresponding ``*_async()`` variant as well. The
``*_multi_async()`` functions return a list of Futures.
There are many other interesting features. For example, Model subclasses may
define pre-call and post-call hooks for most operations (get, put, delete,
allocate_ids), and Property classes may be subclassed to suit various needs.
Documentation for writing a Property subclass is in the docs for the
:class:`Property` class.
"""
import copy
import datetime
import functools
import inspect
import json
import pickle
import six
import zlib
import pytz
from google.cloud.datastore import entity as ds_entity_module
from google.cloud.datastore import helpers
from google.cloud.datastore_v1.types import entity as entity_pb2
from google.cloud.ndb import _legacy_entity_pb
from google.cloud.ndb import _datastore_types
from google.cloud.ndb import exceptions
from google.cloud.ndb import key as key_module
from google.cloud.ndb import _options as options_module
from google.cloud.ndb import query as query_module
from google.cloud.ndb import _transaction
from google.cloud.ndb import tasklets
from google.cloud.ndb import utils
__all__ = [
"Key",
"BlobKey",
"GeoPt",
"Rollback",
"KindError",
"InvalidPropertyError",
"BadProjectionError",
"UnprojectedPropertyError",
"ReadonlyPropertyError",
"ComputedPropertyError",
"UserNotFoundError",
"IndexProperty",
"Index",
"IndexState",
"ModelAdapter",
"make_connection",
"ModelAttribute",
"Property",
"ModelKey",
"BooleanProperty",
"IntegerProperty",
"FloatProperty",
"BlobProperty",
"CompressedTextProperty",
"TextProperty",
"StringProperty",
"GeoPtProperty",
"PickleProperty",
"JsonProperty",
"User",
"UserProperty",
"KeyProperty",
"BlobKeyProperty",
"DateTimeProperty",
"DateProperty",
"TimeProperty",
"StructuredProperty",
"LocalStructuredProperty",
"GenericProperty",
"ComputedProperty",
"MetaModel",
"Model",
"Expando",
"get_multi_async",
"get_multi",
"put_multi_async",
"put_multi",
"delete_multi_async",
"delete_multi",
"get_indexes_async",
"get_indexes",
]
_MEANING_PREDEFINED_ENTITY_USER = 20
_MEANING_COMPRESSED = 22
_ZLIB_COMPRESSION_MARKERS = (
# As produced by zlib. Indicates compressed byte sequence using DEFLATE at
# default compression level, with a 32K window size.
# From https://github.com/madler/zlib/blob/master/doc/rfc1950.txt
b"x\x9c",
# Other compression levels produce the following marker.
b"x^",
)
_MAX_STRING_LENGTH = 1500
Key = key_module.Key
BlobKey = _datastore_types.BlobKey
GeoPt = helpers.GeoPoint
Rollback = exceptions.Rollback
_getfullargspec = inspect.getfullargspec
class KindError(exceptions.BadValueError):
"""Raised when an implementation for a kind can't be found.
May also be raised when the kind is not a byte string.
"""
class InvalidPropertyError(exceptions.Error):
"""Raised when a property is not applicable to a given use.
For example, a property must exist and be indexed to be used in a query's
projection or group by clause.
"""
BadProjectionError = InvalidPropertyError
"""This alias for :class:`InvalidPropertyError` is for legacy support."""
class UnprojectedPropertyError(exceptions.Error):
"""Raised when getting a property value that's not in the projection."""
class ReadonlyPropertyError(exceptions.Error):
"""Raised when attempting to set a property value that is read-only."""
class ComputedPropertyError(ReadonlyPropertyError):
"""Raised when attempting to set or delete a computed property."""
class UserNotFoundError(exceptions.Error):
"""No email argument was specified, and no user is logged in."""
class _NotEqualMixin(object):
"""Mix-in class that implements __ne__ in terms of __eq__."""
def __ne__(self, other):
"""Implement self != other as not(self == other)."""
eq = self.__eq__(other)
if eq is NotImplemented:
return NotImplemented
return not eq
class IndexProperty(_NotEqualMixin):
"""Immutable object representing a single property in an index."""
@utils.positional(1)
def __new__(cls, name, direction):
instance = super(IndexProperty, cls).__new__(cls)
instance._name = name
instance._direction = direction
return instance
@property
def name(self):
"""str: The property name being indexed."""
return self._name
@property
def direction(self):
"""str: The direction in the index, ``asc`` or ``desc``."""
return self._direction
def __repr__(self):
"""Return a string representation."""
return "{}(name={!r}, direction={!r})".format(
type(self).__name__, self.name, self.direction
)
def __eq__(self, other):
"""Compare two index properties for equality."""
if not isinstance(other, IndexProperty):
return NotImplemented
return self.name == other.name and self.direction == other.direction
def __hash__(self):
return hash((self.name, self.direction))
class Index(_NotEqualMixin):
"""Immutable object representing an index."""
@utils.positional(1)
def __new__(cls, kind, properties, ancestor):
instance = super(Index, cls).__new__(cls)
instance._kind = kind
instance._properties = properties
instance._ancestor = ancestor
return instance
@property
def kind(self):
"""str: The kind being indexed."""
return self._kind
@property
def properties(self):
"""List[IndexProperty]: The properties being indexed."""
return self._properties
@property
def ancestor(self):
"""bool: Indicates if this is an ancestor index."""
return self._ancestor
def __repr__(self):
"""Return a string representation."""
return "{}(kind={!r}, properties={!r}, ancestor={})".format(
type(self).__name__, self.kind, self.properties, self.ancestor
)
def __eq__(self, other):
"""Compare two indexes."""
if not isinstance(other, Index):
return NotImplemented
return (
self.kind == other.kind
and self.properties == other.properties
and self.ancestor == other.ancestor
)
def __hash__(self):
return hash((self.kind, self.properties, self.ancestor))
class IndexState(_NotEqualMixin):
"""Immutable object representing an index and its state."""
@utils.positional(1)
def __new__(cls, definition, state, id):
instance = super(IndexState, cls).__new__(cls)
instance._definition = definition
instance._state = state
instance._id = id
return instance
@property
def definition(self):
"""Index: The index corresponding to the tracked state."""
return self._definition
@property
def state(self):
"""str: The index state.
Possible values are ``error``, ``deleting``, ``serving`` or
``building``.
"""
return self._state
@property
def id(self):
"""int: The index ID."""
return self._id
def __repr__(self):
"""Return a string representation."""
return "{}(definition={!r}, state={!r}, id={:d})".format(
type(self).__name__, self.definition, self.state, self.id
)
def __eq__(self, other):
"""Compare two index states."""
if not isinstance(other, IndexState):
return NotImplemented
return (
self.definition == other.definition
and self.state == other.state
and self.id == other.id
)
def __hash__(self):
return hash((self.definition, self.state, self.id))
class ModelAdapter(object):
def __new__(self, *args, **kwargs):
raise exceptions.NoLongerImplementedError()
def _entity_from_ds_entity(ds_entity, model_class=None):
"""Create an entity from a datastore entity.
Args:
ds_entity (google.cloud.datastore_v1.types.Entity): An entity to be
deserialized.
model_class (class): Optional; ndb Model class type.
Returns:
.Model: The deserialized entity.
"""
class_key = ds_entity.get("class")
if class_key:
# If this is a projection query, we'll get multiple entities with
# scalar values rather than single entities with array values.
# It's weird:
# https://cloud.google.com/datastore/docs/concepts/queries#datastore-datastore-array-value-python
if not isinstance(class_key, list):
kind = class_key
else:
kind = class_key[-1]
else:
kind = ds_entity.kind
model_class = model_class or Model._lookup_model(kind)
entity = model_class()
if ds_entity.key:
entity._key = key_module.Key._from_ds_key(ds_entity.key)
for name, value in ds_entity.items():
# If ``name`` was used to define the property, ds_entity name will not
# match model property name.
name = model_class._code_name_from_stored_name(name)
prop = getattr(model_class, name, None)
# Backwards compatibility shim. NDB previously stored structured
# properties as sets of dotted name properties. Datastore now has
# native support for embedded entities and NDB now uses that, by
# default. This handles the case of reading structured properties from
# older NDB datastore instances.
#
# Turns out this is also useful when doing projection queries with
# repeated structured properties, in which case, due to oddities with
# how Datastore handles these things, we'll get a scalar value for the
# subvalue, instead of an array, like you'd expect when just
# marshalling the entity normally (instead of in a projection query).
#
def new_entity(key):
return _BaseValue(ds_entity_module.Entity(key))
if prop is None and "." in name:
supername, subname = name.split(".", 1)
# Code name for structured property could be different than stored
# name if ``name`` was set when defined.
supername = model_class._code_name_from_stored_name(supername)
structprop = getattr(model_class, supername, None)
if isinstance(structprop, StructuredProperty):
subvalue = value
value = structprop._get_base_value(entity)
if value in (None, []): # empty list for repeated props
kind = structprop._model_class._get_kind()
key = key_module.Key(kind, None)
if structprop._repeated:
if isinstance(subvalue, list):
# Not a projection
value = [new_entity(key._key) for _ in subvalue]
else:
# Is a projection, so subvalue is scalar. Only need
# one subentity.
value = [new_entity(key._key)]
else:
value = new_entity(key._key)
structprop._store_value(entity, value)
if structprop._repeated:
if isinstance(subvalue, list):
# Not a projection
# In the rare case of using a repeated
# StructuredProperty where the sub-model is an Expando,
# legacy NDB could write repeated properties of
# different lengths for the subproperties, which was a
# bug. We work around this when reading out such values
# by making sure our repeated property is the same
# length as the longest subproperty.
# Make sure to create a key of the same kind as
# the other entries in the value list
while len(subvalue) > len(value):
# Need to make some more subentities
expando_kind = structprop._model_class._get_kind()
expando_key = key_module.Key(expando_kind, None)
value.append(new_entity(expando_key._key))
# Branch coverage bug,
# See: https://github.com/nedbat/coveragepy/issues/817
for subentity, subsubvalue in zip( # pragma no branch
value, subvalue
):
subentity.b_val.update({subname: subsubvalue})
else:
# Is a projection, so subvalue is scalar and we only
# have one subentity.
value[0].b_val.update({subname: subvalue})
else:
value.b_val.update({subname: subvalue})
continue
if prop is None and kind is not None and kind != model_class.__name__:
# kind and model_class name do not match, so this is probably a
# polymodel. We need to check if the prop belongs to the subclass.
model_subclass = Model._lookup_model(kind)
prop = getattr(model_subclass, name, None)
def base_value_or_none(value):
return None if value is None else _BaseValue(value)
if not (prop is not None and isinstance(prop, Property)):
if value is not None and isinstance(entity, Expando): # pragma: NO BRANCH
if isinstance(value, list):
value = [base_value_or_none(sub_value) for sub_value in value]
else:
value = _BaseValue(value)
setattr(entity, name, value)
continue # pragma: NO COVER
if value is not None:
if prop._repeated:
# A repeated property will have a scalar value if this is a
# projection query.
if isinstance(value, list):
# Not a projection
value = [base_value_or_none(sub_value) for sub_value in value]
else:
# Projection
value = [_BaseValue(value)]
else:
value = _BaseValue(value)
value = prop._from_datastore(ds_entity, value)
prop._store_value(entity, value)
return entity
def _entity_from_protobuf(protobuf):
"""Deserialize an entity from a protobuffer.
Args:
protobuf (google.cloud.datastore_v1.types.Entity): An entity protobuf
to be deserialized.
Returns:
.Model: The deserialized entity.
"""
ds_entity = helpers.entity_from_protobuf(protobuf)
return _entity_from_ds_entity(ds_entity)
def _properties_of(*entities):
"""Get the model properties for one or more entities.
After collecting any properties local to the given entities, will traverse the
entities' MRO (class hierarchy) up from the entities' class through all of its
ancestors, collecting any ``Property`` instances defined for those classes.
Args:
entities (Tuple[model.Model]): The entities to get properties for. All entities
are expected to be of the same class.
Returns:
Iterator[Property]: Iterator over the entities' properties.
"""
seen = set()
entity_type = type(entities[0]) # assume all entities are same type
for level in entities + tuple(entity_type.mro()):
if not hasattr(level, "_properties"):
continue
level_properties = getattr(level, "_properties", {})
for prop in level_properties.values():
if (
not isinstance(prop, Property)
or isinstance(prop, ModelKey)
or prop._name in seen
):
continue
seen.add(prop._name)
yield prop
def _entity_to_ds_entity(entity, set_key=True):
"""Convert an NDB entity to Datastore entity.
Args:
entity (Model): The entity to be converted.
Returns:
google.cloud.datastore.entity.Entity: The converted entity.
Raises:
ndb.exceptions.BadValueError: If entity has uninitialized properties.
"""
data = {"_exclude_from_indexes": []}
uninitialized = []
for prop in _properties_of(entity):
if not prop._is_initialized(entity):
uninitialized.append(prop._name)
prop._to_datastore(entity, data)
if uninitialized:
missing = ", ".join(uninitialized)
raise exceptions.BadValueError(
"Entity has uninitialized properties: {}".format(missing)
)
exclude_from_indexes = data.pop("_exclude_from_indexes")
ds_entity = None
if set_key:
key = entity._key
if key is None:
key = key_module.Key(entity._get_kind(), None)
ds_entity = ds_entity_module.Entity(
key._key, exclude_from_indexes=exclude_from_indexes
)
else:
ds_entity = ds_entity_module.Entity(exclude_from_indexes=exclude_from_indexes)
# Some properties may need to set meanings for backwards compatibility,
# so we look for them. They are set using the _to_datastore calls above.
meanings = data.pop("_meanings", None)
if meanings is not None:
ds_entity._meanings = meanings
ds_entity.update(data)
return ds_entity
def _entity_to_protobuf(entity, set_key=True):
"""Serialize an entity to a protocol buffer.
Args:
entity (Model): The entity to be serialized.
Returns:
google.cloud.datastore_v1.types.Entity: The protocol buffer
representation. Note that some methods are now only
accessible via the `_pb` property.
"""
ds_entity = _entity_to_ds_entity(entity, set_key=set_key)
return helpers.entity_to_protobuf(ds_entity)
def make_connection(*args, **kwargs):
raise exceptions.NoLongerImplementedError()
class ModelAttribute(object):
"""Base for classes that implement a ``_fix_up()`` method."""
def _fix_up(self, cls, code_name):
"""Fix-up property name. To be implemented by subclasses.
Args:
cls (type): The model class that owns the property.
code_name (str): The name of the :class:`Property` being fixed up.
"""
class _BaseValue(_NotEqualMixin):
"""A marker object wrapping a "base type" value.
This is used to be able to tell whether ``entity._values[name]`` is a
user value (i.e. of a type that the Python code understands) or a
base value (i.e of a type that serialization understands).
User values are unwrapped; base values are wrapped in a
:class:`_BaseValue` instance.
Args:
b_val (Any): The base value to be wrapped.
Raises:
TypeError: If ``b_val`` is :data:`None`.
TypeError: If ``b_val`` is a list.
"""
def __init__(self, b_val):
if b_val is None:
raise TypeError("Cannot wrap None")
if isinstance(b_val, list):
raise TypeError("Lists cannot be wrapped. Received", b_val)
self.b_val = b_val
def __repr__(self):
return "_BaseValue({!r})".format(self.b_val)
def __eq__(self, other):
"""Compare two :class:`_BaseValue` instances."""
if not isinstance(other, _BaseValue):
return NotImplemented
return self.b_val == other.b_val
def __hash__(self):
raise TypeError("_BaseValue is not immutable")
class Property(ModelAttribute):
"""A class describing a typed, persisted attribute of an entity.
.. warning::
This is not to be confused with Python's ``@property`` built-in.
.. note::
This is just a base class; there are specific subclasses that
describe properties of various types (and :class:`GenericProperty`
which describes a dynamically typed property).
The :class:`Property` does not reserve any "public" names (i.e. names
that don't start with an underscore). This is intentional; the subclass
:class:`StructuredProperty` uses the public attribute namespace to refer to
nested property names (this is essential for specifying queries on
subproperties).
The :meth:`IN` attribute is provided as an alias for ``_IN``, but ``IN``
can be overridden if a subproperty has the same name.
The :class:`Property` class and its predefined subclasses allow easy
subclassing using composable (or stackable) validation and
conversion APIs. These require some terminology definitions:
* A **user value** is a value such as would be set and accessed by the
application code using standard attributes on the entity.
* A **base value** is a value such as would be serialized to
and deserialized from Cloud Datastore.
A property will be a member of a :class:`Model` and will be used to help
store values in an ``entity`` (i.e. instance of a model subclass). The
underlying stored values can be either user values or base values.
To interact with the composable conversion and validation API, a
:class:`Property` subclass can define
* ``_to_base_type()``
* ``_from_base_type()``
* ``_validate()``
These should **not** call their ``super()`` method, since the methods
are meant to be composed. For example with composable validation:
.. code-block:: python
class Positive(ndb.IntegerProperty):
def _validate(self, value):
if value < 1:
raise ndb.exceptions.BadValueError("Non-positive", value)
class SingleDigit(Positive):
def _validate(self, value):
if value > 9:
raise ndb.exceptions.BadValueError("Multi-digit", value)
neither ``_validate()`` method calls ``super()``. Instead, when a
``SingleDigit`` property validates a value, it composes all validation
calls in order:
* ``SingleDigit._validate``
* ``Positive._validate``
* ``IntegerProperty._validate``
The API supports "stacking" classes with ever more sophisticated
user / base conversions:
* the user to base conversion goes from more sophisticated to less
sophisticated
* the base to user conversion goes from less sophisticated to more
sophisticated
For example, see the relationship between :class:`BlobProperty`,
:class:`TextProperty` and :class:`StringProperty`.
The validation API distinguishes between "lax" and "strict" user values.
The set of lax values is a superset of the set of strict values. The
``_validate()`` method takes a lax value and if necessary converts it to
a strict value. For example, an integer (lax) can be converted to a
floating point (strict) value. This means that when setting the property
value, lax values are accepted, while when getting the property value, only
strict values will be returned. If no conversion is needed, ``_validate()``
may return :data:`None`. If the argument is outside the set of accepted lax
values, ``_validate()`` should raise an exception, preferably
:exc:`TypeError` or :exc:`.BadValueError`.
A class utilizing all three may resemble:
.. code-block:: python
class WidgetProperty(ndb.Property):
def _validate(self, value):
# Lax user value to strict user value.
if not isinstance(value, Widget):
raise ndb.exceptions.BadValueError(value)
def _to_base_type(self, value):
# (Strict) user value to base value.
if isinstance(value, Widget):
return value.to_internal()
def _from_base_type(self, value):
# Base value to (strict) user value.'
if not isinstance(value, _WidgetInternal):
return Widget(value)
There are some things that ``_validate()``, ``_to_base_type()`` and
``_from_base_type()`` do **not** need to handle:
* :data:`None`: They will not be called with :data:`None` (and if they
return :data:`None`, this means that the value does not need conversion).
* Repeated values: The infrastructure takes care of calling
``_from_base_type()`` or ``_to_base_type()`` for each list item in a
repeated value.
* Wrapping "base" values: The wrapping and unwrapping is taken care of by
the infrastructure that calls the composable APIs.
* Comparisons: The comparison operations call ``_to_base_type()`` on
their operand.
* Distinguishing between user and base values: the infrastructure
guarantees that ``_from_base_type()`` will be called with an
(unwrapped) base value, and that ``_to_base_type()`` will be called
with a user value.
* Returning the original value: if any of these return :data:`None`, the
original value is kept. (Returning a different value not equal to
:data:`None` will substitute the different value.)
Additionally, :meth:`_prepare_for_put` can be used to integrate with
datastore save hooks used by :class:`Model` instances.
.. automethod:: _prepare_for_put
Args:
name (str): The name of the property.
indexed (bool): Indicates if the value should be indexed.
repeated (bool): Indicates if this property is repeated, i.e. contains
multiple values.
required (bool): Indicates if this property is required on the given
model type.
default (Any): The default value for this property.
choices (Iterable[Any]): A container of allowed values for this