-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
fields.py
2675 lines (2149 loc) · 89.6 KB
/
fields.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
import datetime
import decimal
import inspect
import itertools
import re
import socket
import time
import uuid
from io import BytesIO
from operator import itemgetter
import gridfs
import pymongo
from bson import SON, Binary, DBRef, ObjectId
from bson.decimal128 import Decimal128, create_decimal128_context
from bson.int64 import Int64
from pymongo import ReturnDocument
try:
import dateutil
except ImportError:
dateutil = None
else:
import dateutil.parser
from mongoengine.base import (
BaseDocument,
BaseField,
ComplexBaseField,
GeoJsonBaseField,
LazyReference,
ObjectIdField,
get_document,
)
from mongoengine.base.utils import LazyRegexCompiler
from mongoengine.common import _import_class
from mongoengine.connection import DEFAULT_CONNECTION_NAME, get_db
from mongoengine.document import Document, EmbeddedDocument
from mongoengine.errors import (
DoesNotExist,
InvalidQueryError,
ValidationError,
)
from mongoengine.queryset import DO_NOTHING
from mongoengine.queryset.base import BaseQuerySet
from mongoengine.queryset.transform import STRING_OPERATORS
try:
from PIL import Image, ImageOps
LANCZOS = Image.LANCZOS if hasattr(Image, "LANCZOS") else Image.ANTIALIAS
except ImportError:
Image = None
ImageOps = None
__all__ = (
"StringField",
"URLField",
"EmailField",
"IntField",
"LongField",
"FloatField",
"DecimalField",
"BooleanField",
"DateTimeField",
"DateField",
"ComplexDateTimeField",
"EmbeddedDocumentField",
"ObjectIdField",
"GenericEmbeddedDocumentField",
"DynamicField",
"ListField",
"SortedListField",
"EmbeddedDocumentListField",
"DictField",
"MapField",
"ReferenceField",
"CachedReferenceField",
"LazyReferenceField",
"GenericLazyReferenceField",
"GenericReferenceField",
"BinaryField",
"GridFSError",
"GridFSProxy",
"FileField",
"ImageGridFsProxy",
"ImproperlyConfigured",
"ImageField",
"GeoPointField",
"PointField",
"LineStringField",
"PolygonField",
"SequenceField",
"UUIDField",
"EnumField",
"MultiPointField",
"MultiLineStringField",
"MultiPolygonField",
"GeoJsonBaseField",
"Decimal128Field",
)
RECURSIVE_REFERENCE_CONSTANT = "self"
class StringField(BaseField):
"""A unicode string field."""
def __init__(self, regex=None, max_length=None, min_length=None, **kwargs):
"""
:param regex: (optional) A string pattern that will be applied during validation
:param max_length: (optional) A max length that will be applied during validation
:param min_length: (optional) A min length that will be applied during validation
:param kwargs: Keyword arguments passed into the parent :class:`~mongoengine.BaseField`
"""
self.regex = re.compile(regex) if regex else None
self.max_length = max_length
self.min_length = min_length
super().__init__(**kwargs)
def to_python(self, value):
if isinstance(value, str):
return value
try:
value = value.decode("utf-8")
except Exception:
pass
return value
def validate(self, value):
if not isinstance(value, str):
self.error("StringField only accepts string values")
if self.max_length is not None and len(value) > self.max_length:
self.error("String value is too long")
if self.min_length is not None and len(value) < self.min_length:
self.error("String value is too short")
if self.regex is not None and self.regex.match(value) is None:
self.error("String value did not match validation regex")
def lookup_member(self, member_name):
return None
def prepare_query_value(self, op, value):
if not isinstance(op, str):
return value
if op in STRING_OPERATORS:
case_insensitive = op.startswith("i")
op = op.lstrip("i")
flags = re.IGNORECASE if case_insensitive else 0
regex = r"%s"
if op == "startswith":
regex = r"^%s"
elif op == "endswith":
regex = r"%s$"
elif op == "exact":
regex = r"^%s$"
elif op == "wholeword":
regex = r"\b%s\b"
elif op == "regex":
regex = value
if op == "regex":
value = re.compile(regex, flags)
else:
# escape unsafe characters which could lead to a re.error
value = re.escape(value)
value = re.compile(regex % value, flags)
return super().prepare_query_value(op, value)
class URLField(StringField):
"""A field that validates input as an URL."""
_URL_REGEX = LazyRegexCompiler(
r"^(?:[a-z0-9\.\-]*)://" # scheme is validated separately
r"(?:(?:[A-Z0-9](?:[A-Z0-9-_]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}(?<!-)\.?)|" # domain...
r"localhost|" # localhost...
r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|" # ...or ipv4
r"\[?[A-F0-9]*:[A-F0-9:]+\]?)" # ...or ipv6
r"(?::\d+)?" # optional port
r"(?:/?|[/?]\S+)$",
re.IGNORECASE,
)
_URL_SCHEMES = ["http", "https", "ftp", "ftps"]
def __init__(self, url_regex=None, schemes=None, **kwargs):
"""
:param url_regex: (optional) Overwrite the default regex used for validation
:param schemes: (optional) Overwrite the default URL schemes that are allowed
:param kwargs: Keyword arguments passed into the parent :class:`~mongoengine.StringField`
"""
self.url_regex = url_regex or self._URL_REGEX
self.schemes = schemes or self._URL_SCHEMES
super().__init__(**kwargs)
def validate(self, value):
# Check first if the scheme is valid
scheme = value.split("://")[0].lower()
if scheme not in self.schemes:
self.error(f"Invalid scheme {scheme} in URL: {value}")
# Then check full URL
if not self.url_regex.match(value):
self.error(f"Invalid URL: {value}")
class EmailField(StringField):
"""A field that validates input as an email address."""
USER_REGEX = LazyRegexCompiler(
# `dot-atom` defined in RFC 5322 Section 3.2.3.
r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*\Z"
# `quoted-string` defined in RFC 5322 Section 3.2.4.
r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])*"\Z)',
re.IGNORECASE,
)
UTF8_USER_REGEX = LazyRegexCompiler(
(
# RFC 6531 Section 3.3 extends `atext` (used by dot-atom) to
# include `UTF8-non-ascii`.
r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z\u0080-\U0010FFFF]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z\u0080-\U0010FFFF]+)*\Z"
# `quoted-string`
r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])*"\Z)'
),
re.IGNORECASE | re.UNICODE,
)
DOMAIN_REGEX = LazyRegexCompiler(
r"((?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+)(?:[A-Z0-9-]{2,63}(?<!-))\Z",
re.IGNORECASE,
)
error_msg = "Invalid email address: %s"
def __init__(
self,
domain_whitelist=None,
allow_utf8_user=False,
allow_ip_domain=False,
*args,
**kwargs,
):
"""
:param domain_whitelist: (optional) list of valid domain names applied during validation
:param allow_utf8_user: Allow user part of the email to contain utf8 char
:param allow_ip_domain: Allow domain part of the email to be an IPv4 or IPv6 address
:param kwargs: Keyword arguments passed into the parent :class:`~mongoengine.StringField`
"""
self.domain_whitelist = domain_whitelist or []
self.allow_utf8_user = allow_utf8_user
self.allow_ip_domain = allow_ip_domain
super().__init__(*args, **kwargs)
def validate_user_part(self, user_part):
"""Validate the user part of the email address. Return True if
valid and False otherwise.
"""
if self.allow_utf8_user:
return self.UTF8_USER_REGEX.match(user_part)
return self.USER_REGEX.match(user_part)
def validate_domain_part(self, domain_part):
"""Validate the domain part of the email address. Return True if
valid and False otherwise.
"""
# Skip domain validation if it's in the whitelist.
if domain_part in self.domain_whitelist:
return True
if self.DOMAIN_REGEX.match(domain_part):
return True
# Validate IPv4/IPv6, e.g. user@[192.168.0.1]
if self.allow_ip_domain and domain_part[0] == "[" and domain_part[-1] == "]":
for addr_family in (socket.AF_INET, socket.AF_INET6):
try:
socket.inet_pton(addr_family, domain_part[1:-1])
return True
except (OSError, UnicodeEncodeError):
pass
return False
def validate(self, value):
super().validate(value)
if "@" not in value:
self.error(self.error_msg % value)
user_part, domain_part = value.rsplit("@", 1)
# Validate the user part.
if not self.validate_user_part(user_part):
self.error(self.error_msg % value)
# Validate the domain and, if invalid, see if it's IDN-encoded.
if not self.validate_domain_part(domain_part):
try:
domain_part = domain_part.encode("idna").decode("ascii")
except UnicodeError:
self.error(
"{} {}".format(
self.error_msg % value, "(domain failed IDN encoding)"
)
)
else:
if not self.validate_domain_part(domain_part):
self.error(
"{} {}".format(
self.error_msg % value, "(domain validation failed)"
)
)
class IntField(BaseField):
"""32-bit integer field."""
def __init__(self, min_value=None, max_value=None, **kwargs):
"""
:param min_value: (optional) A min value that will be applied during validation
:param max_value: (optional) A max value that will be applied during validation
:param kwargs: Keyword arguments passed into the parent :class:`~mongoengine.BaseField`
"""
self.min_value, self.max_value = min_value, max_value
super().__init__(**kwargs)
def to_python(self, value):
try:
value = int(value)
except (TypeError, ValueError):
pass
return value
def validate(self, value):
try:
value = int(value)
except (TypeError, ValueError):
self.error("%s could not be converted to int" % value)
if self.min_value is not None and value < self.min_value:
self.error("Integer value is too small")
if self.max_value is not None and value > self.max_value:
self.error("Integer value is too large")
def prepare_query_value(self, op, value):
if value is None:
return value
return super().prepare_query_value(op, int(value))
class LongField(IntField):
"""64-bit integer field. (Equivalent to IntField since the support to Python2 was dropped)"""
def to_mongo(self, value):
return Int64(value)
class FloatField(BaseField):
"""Floating point number field."""
def __init__(self, min_value=None, max_value=None, **kwargs):
"""
:param min_value: (optional) A min value that will be applied during validation
:param max_value: (optional) A max value that will be applied during validation
:param kwargs: Keyword arguments passed into the parent :class:`~mongoengine.BaseField`
"""
self.min_value, self.max_value = min_value, max_value
super().__init__(**kwargs)
def to_python(self, value):
try:
value = float(value)
except ValueError:
pass
return value
def validate(self, value):
if isinstance(value, int):
try:
value = float(value)
except OverflowError:
self.error("The value is too large to be converted to float")
if not isinstance(value, float):
self.error("FloatField only accepts float and integer values")
if self.min_value is not None and value < self.min_value:
self.error("Float value is too small")
if self.max_value is not None and value > self.max_value:
self.error("Float value is too large")
def prepare_query_value(self, op, value):
if value is None:
return value
return super().prepare_query_value(op, float(value))
class DecimalField(BaseField):
"""Disclaimer: This field is kept for historical reason but since it converts the values to float, it
is not suitable for true decimal storage. Consider using :class:`~mongoengine.fields.Decimal128Field`.
Fixed-point decimal number field. Stores the value as a float by default unless `force_string` is used.
If using floats, beware of Decimal to float conversion (potential precision loss)
"""
def __init__(
self,
min_value=None,
max_value=None,
force_string=False,
precision=2,
rounding=decimal.ROUND_HALF_UP,
**kwargs,
):
"""
:param min_value: (optional) A min value that will be applied during validation
:param max_value: (optional) A max value that will be applied during validation
:param force_string: Store the value as a string (instead of a float).
Be aware that this affects query sorting and operation like lte, gte (as string comparison is applied)
and some query operator won't work (e.g. inc, dec)
:param precision: Number of decimal places to store.
:param rounding: The rounding rule from the python decimal library:
- decimal.ROUND_CEILING (towards Infinity)
- decimal.ROUND_DOWN (towards zero)
- decimal.ROUND_FLOOR (towards -Infinity)
- decimal.ROUND_HALF_DOWN (to nearest with ties going towards zero)
- decimal.ROUND_HALF_EVEN (to nearest with ties going to nearest even integer)
- decimal.ROUND_HALF_UP (to nearest with ties going away from zero)
- decimal.ROUND_UP (away from zero)
- decimal.ROUND_05UP (away from zero if last digit after rounding towards zero would have been 0 or 5; otherwise towards zero)
Defaults to: ``decimal.ROUND_HALF_UP``
:param kwargs: Keyword arguments passed into the parent :class:`~mongoengine.BaseField`
"""
self.min_value = min_value
self.max_value = max_value
self.force_string = force_string
if precision < 0 or not isinstance(precision, int):
self.error("precision must be a positive integer")
self.precision = precision
self.rounding = rounding
super().__init__(**kwargs)
def to_python(self, value):
# Convert to string for python 2.6 before casting to Decimal
try:
value = decimal.Decimal("%s" % value)
except (TypeError, ValueError, decimal.InvalidOperation):
return value
if self.precision > 0:
return value.quantize(
decimal.Decimal(".%s" % ("0" * self.precision)), rounding=self.rounding
)
else:
return value.quantize(decimal.Decimal(), rounding=self.rounding)
def to_mongo(self, value):
if self.force_string:
return str(self.to_python(value))
return float(self.to_python(value))
def validate(self, value):
if not isinstance(value, decimal.Decimal):
if not isinstance(value, str):
value = str(value)
try:
value = decimal.Decimal(value)
except (TypeError, ValueError, decimal.InvalidOperation) as exc:
self.error("Could not convert value to decimal: %s" % exc)
if self.min_value is not None and value < self.min_value:
self.error("Decimal value is too small")
if self.max_value is not None and value > self.max_value:
self.error("Decimal value is too large")
def prepare_query_value(self, op, value):
if value is None:
return value
return super().prepare_query_value(op, self.to_mongo(value))
class BooleanField(BaseField):
"""Boolean field type."""
def to_python(self, value):
try:
value = bool(value)
except (ValueError, TypeError):
pass
return value
def validate(self, value):
if not isinstance(value, bool):
self.error("BooleanField only accepts boolean values")
class DateTimeField(BaseField):
"""Datetime field.
Uses the python-dateutil library if available alternatively use time.strptime
to parse the dates. Note: python-dateutil's parser is fully featured and when
installed you can utilise it to convert varying types of date formats into valid
python datetime objects.
Note: To default the field to the current datetime, use: DateTimeField(default=datetime.utcnow)
Note: Microseconds are rounded to the nearest millisecond.
Pre UTC microsecond support is effectively broken.
Use :class:`~mongoengine.fields.ComplexDateTimeField` if you
need accurate microsecond support.
"""
def validate(self, value):
new_value = self.to_mongo(value)
if not isinstance(new_value, (datetime.datetime, datetime.date)):
self.error('cannot parse date "%s"' % value)
def to_mongo(self, value):
if value is None:
return value
if isinstance(value, datetime.datetime):
return value
if isinstance(value, datetime.date):
return datetime.datetime(value.year, value.month, value.day)
if callable(value):
return value()
if isinstance(value, str):
return self._parse_datetime(value)
else:
return None
@staticmethod
def _parse_datetime(value):
# Attempt to parse a datetime from a string
value = value.strip()
if not value:
return None
if dateutil:
try:
return dateutil.parser.parse(value)
except (TypeError, ValueError, OverflowError):
return None
# split usecs, because they are not recognized by strptime.
if "." in value:
try:
value, usecs = value.split(".")
usecs = int(usecs)
except ValueError:
return None
else:
usecs = 0
kwargs = {"microsecond": usecs}
try: # Seconds are optional, so try converting seconds first.
return datetime.datetime(
*time.strptime(value, "%Y-%m-%d %H:%M:%S")[:6], **kwargs
)
except ValueError:
try: # Try without seconds.
return datetime.datetime(
*time.strptime(value, "%Y-%m-%d %H:%M")[:5], **kwargs
)
except ValueError: # Try without hour/minutes/seconds.
try:
return datetime.datetime(
*time.strptime(value, "%Y-%m-%d")[:3], **kwargs
)
except ValueError:
return None
def prepare_query_value(self, op, value):
return super().prepare_query_value(op, self.to_mongo(value))
class DateField(DateTimeField):
def to_mongo(self, value):
value = super().to_mongo(value)
# drop hours, minutes, seconds
if isinstance(value, datetime.datetime):
value = datetime.datetime(value.year, value.month, value.day)
return value
def to_python(self, value):
value = super().to_python(value)
# convert datetime to date
if isinstance(value, datetime.datetime):
value = datetime.date(value.year, value.month, value.day)
return value
class ComplexDateTimeField(StringField):
"""
ComplexDateTimeField handles microseconds exactly instead of rounding
like DateTimeField does.
Derives from a StringField so you can do `gte` and `lte` filtering by
using lexicographical comparison when filtering / sorting strings.
The stored string has the following format:
YYYY,MM,DD,HH,MM,SS,NNNNNN
Where NNNNNN is the number of microseconds of the represented `datetime`.
The `,` as the separator can be easily modified by passing the `separator`
keyword when initializing the field.
Note: To default the field to the current datetime, use: DateTimeField(default=datetime.utcnow)
"""
def __init__(self, separator=",", **kwargs):
"""
:param separator: Allows to customize the separator used for storage (default ``,``)
:param kwargs: Keyword arguments passed into the parent :class:`~mongoengine.StringField`
"""
self.separator = separator
self.format = separator.join(["%Y", "%m", "%d", "%H", "%M", "%S", "%f"])
super().__init__(**kwargs)
def _convert_from_datetime(self, val):
"""
Convert a `datetime` object to a string representation (which will be
stored in MongoDB). This is the reverse function of
`_convert_from_string`.
>>> a = datetime(2011, 6, 8, 20, 26, 24, 92284)
>>> ComplexDateTimeField()._convert_from_datetime(a)
'2011,06,08,20,26,24,092284'
"""
return val.strftime(self.format)
def _convert_from_string(self, data):
"""
Convert a string representation to a `datetime` object (the object you
will manipulate). This is the reverse function of
`_convert_from_datetime`.
>>> a = '2011,06,08,20,26,24,092284'
>>> ComplexDateTimeField()._convert_from_string(a)
datetime.datetime(2011, 6, 8, 20, 26, 24, 92284)
"""
values = [int(d) for d in data.split(self.separator)]
return datetime.datetime(*values)
def __get__(self, instance, owner):
if instance is None:
return self
data = super().__get__(instance, owner)
if isinstance(data, datetime.datetime) or data is None:
return data
return self._convert_from_string(data)
def __set__(self, instance, value):
super().__set__(instance, value)
value = instance._data[self.name]
if value is not None:
if isinstance(value, datetime.datetime):
instance._data[self.name] = self._convert_from_datetime(value)
else:
instance._data[self.name] = value
def validate(self, value):
value = self.to_python(value)
if not isinstance(value, datetime.datetime):
self.error("Only datetime objects may used in a ComplexDateTimeField")
def to_python(self, value):
original_value = value
try:
return self._convert_from_string(value)
except Exception:
return original_value
def to_mongo(self, value):
value = self.to_python(value)
return self._convert_from_datetime(value)
def prepare_query_value(self, op, value):
if value is None:
return value
return super().prepare_query_value(op, self._convert_from_datetime(value))
class EmbeddedDocumentField(BaseField):
"""An embedded document field - with a declared document_type.
Only valid values are subclasses of :class:`~mongoengine.EmbeddedDocument`.
"""
def __init__(self, document_type, **kwargs):
# XXX ValidationError raised outside of the "validate" method.
if not (
isinstance(document_type, str)
or issubclass(document_type, EmbeddedDocument)
):
self.error(
"Invalid embedded document class provided to an "
"EmbeddedDocumentField"
)
self.document_type_obj = document_type
super().__init__(**kwargs)
@property
def document_type(self):
if isinstance(self.document_type_obj, str):
if self.document_type_obj == RECURSIVE_REFERENCE_CONSTANT:
resolved_document_type = self.owner_document
else:
resolved_document_type = get_document(self.document_type_obj)
if not issubclass(resolved_document_type, EmbeddedDocument):
# Due to the late resolution of the document_type
# There is a chance that it won't be an EmbeddedDocument (#1661)
self.error(
"Invalid embedded document class provided to an "
"EmbeddedDocumentField"
)
self.document_type_obj = resolved_document_type
return self.document_type_obj
def to_python(self, value):
if not isinstance(value, self.document_type):
return self.document_type._from_son(
value, _auto_dereference=self._auto_dereference
)
return value
def to_mongo(self, value, use_db_field=True, fields=None):
if not isinstance(value, self.document_type):
return value
return self.document_type.to_mongo(value, use_db_field, fields)
def validate(self, value, clean=True):
"""Make sure that the document instance is an instance of the
EmbeddedDocument subclass provided when the document was defined.
"""
# Using isinstance also works for subclasses of self.document
if not isinstance(value, self.document_type):
self.error(
"Invalid embedded document instance provided to an "
"EmbeddedDocumentField"
)
value.validate(clean=clean)
def lookup_member(self, member_name):
doc_and_subclasses = [self.document_type] + self.document_type.__subclasses__()
for doc_type in doc_and_subclasses:
field = doc_type._fields.get(member_name)
if field:
return field
def prepare_query_value(self, op, value):
if value is not None and not isinstance(value, self.document_type):
# Short circuit for special operators, returning them as is
if isinstance(value, dict) and all(k.startswith("$") for k in value.keys()):
return value
try:
value = self.document_type._from_son(value)
except ValueError:
raise InvalidQueryError(
"Querying the embedded document '%s' failed, due to an invalid query value"
% (self.document_type._class_name,)
)
super().prepare_query_value(op, value)
return self.to_mongo(value)
class GenericEmbeddedDocumentField(BaseField):
"""A generic embedded document field - allows any
:class:`~mongoengine.EmbeddedDocument` to be stored.
Only valid values are subclasses of :class:`~mongoengine.EmbeddedDocument`.
.. note ::
You can use the choices param to limit the acceptable
EmbeddedDocument types
"""
def prepare_query_value(self, op, value):
return super().prepare_query_value(op, self.to_mongo(value))
def to_python(self, value):
if isinstance(value, dict):
doc_cls = get_document(value["_cls"])
value = doc_cls._from_son(value)
return value
def validate(self, value, clean=True):
if self.choices and isinstance(value, SON):
for choice in self.choices:
if value["_cls"] == choice._class_name:
return True
if not isinstance(value, EmbeddedDocument):
self.error(
"Invalid embedded document instance provided to an "
"GenericEmbeddedDocumentField"
)
value.validate(clean=clean)
def lookup_member(self, member_name):
document_choices = self.choices or []
for document_choice in document_choices:
doc_and_subclasses = [document_choice] + document_choice.__subclasses__()
for doc_type in doc_and_subclasses:
field = doc_type._fields.get(member_name)
if field:
return field
def to_mongo(self, document, use_db_field=True, fields=None):
if document is None:
return None
data = document.to_mongo(use_db_field, fields)
if "_cls" not in data:
data["_cls"] = document._class_name
return data
class DynamicField(BaseField):
"""A truly dynamic field type capable of handling different and varying
types of data.
Used by :class:`~mongoengine.DynamicDocument` to handle dynamic data"""
def to_mongo(self, value, use_db_field=True, fields=None):
"""Convert a Python type to a MongoDB compatible type."""
if isinstance(value, str):
return value
if hasattr(value, "to_mongo"):
cls = value.__class__
val = value.to_mongo(use_db_field, fields)
# If we its a document thats not inherited add _cls
if isinstance(value, Document):
val = {"_ref": value.to_dbref(), "_cls": cls.__name__}
if isinstance(value, EmbeddedDocument):
val["_cls"] = cls.__name__
return val
if not isinstance(value, (dict, list, tuple)):
return value
is_list = False
if not hasattr(value, "items"):
is_list = True
value = {k: v for k, v in enumerate(value)}
data = {}
for k, v in value.items():
data[k] = self.to_mongo(v, use_db_field, fields)
value = data
if is_list: # Convert back to a list
value = [v for k, v in sorted(data.items(), key=itemgetter(0))]
return value
def to_python(self, value):
if isinstance(value, dict) and "_cls" in value:
doc_cls = get_document(value["_cls"])
if "_ref" in value:
value = doc_cls._get_db().dereference(value["_ref"])
return doc_cls._from_son(value)
return super().to_python(value)
def lookup_member(self, member_name):
return member_name
def prepare_query_value(self, op, value):
if isinstance(value, str):
return StringField().prepare_query_value(op, value)
return super().prepare_query_value(op, self.to_mongo(value))
def validate(self, value, clean=True):
if hasattr(value, "validate"):
value.validate(clean=clean)
class ListField(ComplexBaseField):
"""A list field that wraps a standard field, allowing multiple instances
of the field to be used as a list in the database.
If using with ReferenceFields see: :ref:`many-to-many-with-listfields`
.. note::
Required means it cannot be empty - as the default for ListFields is []
"""
def __init__(self, field=None, max_length=None, **kwargs):
self.max_length = max_length
kwargs.setdefault("default", lambda: [])
super().__init__(field=field, **kwargs)
def __get__(self, instance, owner):
if instance is None:
# Document class being used rather than a document object
return self
value = instance._data.get(self.name)
LazyReferenceField = _import_class("LazyReferenceField")
GenericLazyReferenceField = _import_class("GenericLazyReferenceField")
if (
isinstance(self.field, (LazyReferenceField, GenericLazyReferenceField))
and value
):
instance._data[self.name] = [self.field.build_lazyref(x) for x in value]
return super().__get__(instance, owner)
def validate(self, value):
"""Make sure that a list of valid fields is being used."""
if not isinstance(value, (list, tuple, BaseQuerySet)):
self.error("Only lists and tuples may be used in a list field")
# Validate that max_length is not exceeded.
# NOTE It's still possible to bypass this enforcement by using $push.
# However, if the document is reloaded after $push and then re-saved,
# the validation error will be raised.
if self.max_length is not None and len(value) > self.max_length:
self.error("List is too long")
super().validate(value)
def prepare_query_value(self, op, value):
# Validate that the `set` operator doesn't contain more items than `max_length`.
if op == "set" and self.max_length is not None and len(value) > self.max_length:
self.error("List is too long")
if self.field:
# If the value is iterable and it's not a string nor a
# BaseDocument, call prepare_query_value for each of its items.
if (
op in ("set", "unset", None)
and hasattr(value, "__iter__")
and not isinstance(value, str)
and not isinstance(value, BaseDocument)
):
return [self.field.prepare_query_value(op, v) for v in value]
return self.field.prepare_query_value(op, value)
return super().prepare_query_value(op, value)
class EmbeddedDocumentListField(ListField):
"""A :class:`~mongoengine.ListField` designed specially to hold a list of
embedded documents to provide additional query helpers.
.. note::
The only valid list values are subclasses of
:class:`~mongoengine.EmbeddedDocument`.
"""
def __init__(self, document_type, **kwargs):
"""
:param document_type: The type of
:class:`~mongoengine.EmbeddedDocument` the list will hold.
:param kwargs: Keyword arguments passed into the parent :class:`~mongoengine.ListField`
"""
super().__init__(field=EmbeddedDocumentField(document_type), **kwargs)
class SortedListField(ListField):
"""A ListField that sorts the contents of its list before writing to
the database in order to ensure that a sorted list is always
retrieved.
.. warning::
There is a potential race condition when handling lists. If you set /
save the whole list then other processes trying to save the whole list
as well could overwrite changes. The safest way to append to a list is
to perform a push operation.
"""
def __init__(self, field, **kwargs):
self._ordering = kwargs.pop("ordering", None)
self._order_reverse = kwargs.pop("reverse", False)
super().__init__(field, **kwargs)