-
Notifications
You must be signed in to change notification settings - Fork 1
/
model.py
2834 lines (2402 loc) · 107 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
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Hive Flask Quorum
# Copyright (c) 2008-2019 Hive Solutions Lda.
#
# This file is part of Hive Flask Quorum.
#
# Hive Flask Quorum is free software: you can redistribute it and/or modify
# it under the terms of the Apache License as published by the Apache
# Foundation, either version 2.0 of the License, or (at your option) any
# later version.
#
# Hive Flask Quorum is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# Apache License for more details.
#
# You should have received a copy of the Apache License along with
# Hive Flask Quorum. If not, see <http://www.apache.org/licenses/>.
__author__ = "João Magalhães <joamag@hive.pt>"
""" The author(s) of the module """
__version__ = "1.0.0"
""" The version of the module """
__revision__ = "$LastChangedRevision$"
""" The revision number of the module """
__date__ = "$LastChangedDate$"
""" The last change date of the module """
__copyright__ = "Copyright (c) 2008-2019 Hive Solutions Lda."
""" The copyright for the module """
__license__ = "Apache License, Version 2.0"
""" The license for the module """
import re
import copy
import math
import json
import types
import flask
import inspect
import datetime
from . import util
from . import meta
from . import common
from . import legacy
from . import typesf
from . import observer
from . import validation
from . import exceptions
ITERABLES = tuple(list(legacy.STRINGS) + [dict])
""" The sequence defining the complete set of valid types
for direct evaluation, instead of indirect (recursive)
evaluation, this is required to avoid miss behavior """
RE = lambda v: [i for i in v if not i == ""]
""" Simple lambda function that removes any
empty element from the provided list values """
BUILDERS = {
legacy.UNICODE : lambda v: v.decode("utf-8") if\
isinstance(v, legacy.BYTES) else legacy.UNICODE(v),
list : lambda v: RE(v) if isinstance(v, list) else\
(json.loads(v) if isinstance(v, legacy.UNICODE) else RE([v])),
dict : lambda v: json.loads(v) if isinstance(v, legacy.UNICODE) else dict(v),
bool : lambda v: v if isinstance(v, bool) else\
not v in ("", "0", "false", "False")
}
""" The map associating the various types with the
custom builder functions to be used when applying
the types function, this is relevant for the built-in
types that are meant to avoid using the default constructor """
BUILDERS_META = dict(
text = BUILDERS[legacy.UNICODE],
country = BUILDERS[legacy.UNICODE],
longtext = BUILDERS[legacy.UNICODE],
map = BUILDERS[dict],
longmap = BUILDERS[dict],
date = lambda v: float(v),
datetetime = lambda v: float(v),
file = None
)
""" Map equivalent to the builders map but appliable
for meta based type naming, this map should be used as
an extension to the base builder map """
METAS = dict(
text = lambda v, d, c = None: v,
enum = lambda v, d, c = None: d["enum"].get(v, None),
list = lambda v, d, c = None:\
json.dumps(v, ensure_ascii = False, cls = c._encoder() if c else None),
map = lambda v, d, c = None:\
json.dumps(v, ensure_ascii = False, cls = c._encoder() if c else None),
longmap = lambda v, d, c = None:\
json.dumps(v, ensure_ascii = False, cls = c._encoder() if c else None),
date = lambda v, d, c = None:\
datetime.datetime.utcfromtimestamp(float(v)).strftime("%d %b %Y"),
datetime = lambda v, d, c = None:\
datetime.datetime.utcfromtimestamp(float(v)).strftime("%d %b %Y %H:%M:%S")
)
""" The map that contains the various mapping functions
for the meta types that may be described for a field under
the current model specification, the resulting value for
each of these functions should preferably be a string """
TYPE_DEFAULTS = {
legacy.BYTES : None,
legacy.UNICODE : None,
int : None,
float : None,
bool : False,
list : lambda: [],
dict : lambda: {}
}
""" The default values to be set when a type
conversion fails for the provided string value
the resulting value may be returned when a validation
fails an so it must be used carefully """
TYPE_META = {
typesf.File : "file",
typesf.Files : "files",
typesf.Reference : "reference",
typesf.References : "references",
legacy.BYTES : "string",
legacy.UNICODE : "string",
int : "number",
float : "float",
bool: "bool",
list : "list",
dict : "map"
}
""" Dictionary that defines the default mapping for each
of the base data types against the associated default meta
values for each for them, these meta type values are going
to be used mostly for presentation purposes """
TYPE_REFERENCES = (
typesf.Reference,
typesf.References
)
""" The various data types that are considered to be references
so that they are lazy loaded from the data source, these kind
of types should be compliant to a common interface so that they
may be used "blindly" from an external entity """
REVERSE = dict(
descending = "ascending",
ascending = "descending",
)
""" The reverse order dictionary that maps a certain
order direction (as a string) with the opposite one
this may be used to "calculate" the reverse value """
DIRTY_PARAMS = (
"map",
"rules",
"meta",
"build",
"skip",
"limit",
"sort",
"raise_e"
)
""" The set containing the complete set of parameter names for
the parameters that are considered to be dirty and that should
be cleaned from any query operation on the data source, otherwise
serious consequences may occur """
OPERATORS = {
"eq" : None,
"equals" : None,
"ne" : "$ne",
"not_equals" : "$ne",
"in" : "$in",
"nin" : "$nin",
"not_in" : "$nin",
"like" : "$regex",
"likei" : "$regex",
"llike" : "$regex",
"llikei" : "$regex",
"rlike" : "$regex",
"rlikei" : "$regex",
"gt" : "$gt",
"greater" : "$gt",
"gte" : "$gte",
"greater_equal" : "$gte",
"lt" : "$lt",
"lesser" : "$lt",
"lte" : "$lte",
"lesser_equal" : "$lte",
"null" : None,
"is_null" : None,
"not_null" : "$ne",
"is_not_null" : "$ne",
"contains" : "$all"
}
""" The map containing the mapping association between the
normalized version of the operators and the infra-structure
specific value for each of this operations, note that some
of the values don't have a valid mapping for this operations
the operator must be ignored and not used explicitly """
VALUE_METHODS = {
"in" : lambda v, t: [t(v) for v in v.split(";")],
"not_in" : lambda v, t: [t(v) for v in v.split(";")],
"like" : lambda v, t: "^.*" + legacy.UNICODE(re.escape(v)) + ".*$",
"likei" : lambda v, t: "^.*" + legacy.UNICODE(re.escape(v)) + ".*$",
"llike" : lambda v, t: "^.*" + legacy.UNICODE(re.escape(v)) + "$",
"llikei" : lambda v, t: "^.*" + legacy.UNICODE(re.escape(v)) + "$",
"rlike" : lambda v, t: "^" + legacy.UNICODE(re.escape(v)) + ".*$",
"rlikei" : lambda v, t: "^" + legacy.UNICODE(re.escape(v)) + ".*$",
"null" : lambda v, t: None,
"is_null" : lambda v, t: None,
"not_null" : lambda v, t: None,
"is_not_null" : lambda v, t: None,
"contains" : lambda v, t: [v for v in v.split(";")]
}
""" Map that associates each of the normalized operations with
an inline function that together with the data type maps the
the base string based value into the target normalized value """
INSENSITIVE = {
"likei" : True,
"llikei" : True,
"rlikei" : True,
}
""" The map that associates the various operators with the boolean
values that define if an insensitive base search should be used
instead of the "typical" sensitive search """
BUILDERS.update(BUILDERS_META)
class Model(legacy.with_meta(meta.Ordered, observer.Observable)):
"""
Abstract model class from which all the models should
directly or indirectly inherit. Should provide the
basic infra-structure for the persistence of data using
a plain key value storage engine.
The data should always be store in a dictionary oriented
structure while it's not persisted in the database.
"""
def __init__(self, model = None, **kwargs):
fill = kwargs.pop("fill", True)
model = model or {}
if fill: model = self.__class__.fill(model)
self.__dict__["_events"] = {}
self.__dict__["_extras"] = []
self.__dict__["model"] = model
self.__dict__["ref"] = kwargs.pop("ref", None)
for name, value in kwargs.items(): setattr(self, name, value)
observer.Observable.__init__(self)
def __str__(self):
cls = self.__class__
default = cls.default()
if not default: return cls._name()
if not default in self.model: return cls._name()
value = self.model[default]
if value == None: value = ""
is_string = legacy.is_str(value)
return value if is_string else str(value)
def __unicode__(self):
cls = self.__class__
default = cls.default()
if not default: return cls._name()
value = self.model[default]
if value == None: value = ""
is_unicode = legacy.is_unicode(value)
return value if is_unicode else legacy.UNICODE(value)
def __getattribute__(self, name):
try:
model = object.__getattribute__(self, "model")
if name in model: return model[name]
except AttributeError: pass
cls = object.__getattribute__(self, "__class__")
definition = cls.definition()
if name in definition: raise AttributeError(
"attribute '%s' is not set" % name
)
return object.__getattribute__(self, name)
def __setattr__(self, name, value):
is_base = name in self.__dict__
if is_base: self.__dict__[name] = value
else: self.model[name] = value
def __delattr__(self, name):
try:
model = object.__getattribute__(self, "model")
if name in model: del model[name]
except AttributeError: pass
def __len__(self):
return self.model.__len__()
def __getitem__(self, key):
return self.model.__getitem__(key)
def __setitem__(self, key, value):
self.model.__setitem__(key, value)
def __delitem__(self, key):
self.model.__delitem__(key)
def __contains__(self, item):
return self.model.__contains__(item)
def __nonzero__(self):
return len(self.model) > 0
def __bool__(self):
return len(self.model) > 0
@classmethod
def new(
cls,
model = None,
form = True,
safe = True,
build = False,
fill = True,
new = True,
**kwargs
):
"""
Creates a new instance of the model applying the provided model
map to it after the instantiation of the class.
The optional form flag controls if the form context data should be
used in the case of an invalid/unset model value. This is considered
unsafe in many contexts.
The optional safe flag makes sure that the model attributes marked
as safe are going to be removed and are not valid for apply.
The optional build flag may be used to define if the build operations
that may be defined by the user on override should be called for
this instance of entity (should be used only on retrieval).
The optional fill flag allows control on whenever the model should be
filled with default values before the apply operation is performed.
In order to make sure the resulting instance is safe for creation only
the new flag may be used as this will make sure that the proper identifier
attributes are not set in the instance after the apply operation is done.
:type model: Dictionary
:param model: The map containing the model that is going to be applied
to the new instance to be created.
:type form: bool
:param form: If in case the provided model is not valid (unset) the model
should be retrieved from the current model in context, this is an unsafe
operation as it may create unwanted behavior (use it carefully).
:type safe: bool
:param safe: If the attributes marked as safe in the model definition
should be removed from the instance after the apply operation.
:type build: bool
:param build: If the "custom" build operation should be performed after
the apply operation is performed so that new custom attributes may be
injected into the resulting instance.
:type fill: bool
:param fill: If the various attributes of the model should be "filled"
with default values (avoiding empty values).
:type new: bool
:param new: In case this value is valid the resulting instance is expected
to be considered as new meaning that no identifier attributes are set.
:rtype: Model
:return: The new model instance resulting from the apply of the provided
model and after the proper validations are performed on it.
"""
if model == None: model = util.get_object() if form else dict(kwargs)
if fill: model = cls.fill(model, safe = not new)
instance = cls(fill = False)
instance.apply(model, form = form, safe_a = safe)
build and cls.build(instance.model, map = False)
new and instance.assert_is_new()
return instance
@classmethod
def old(cls, model = None, form = True, safe = True, build = False):
return cls.new(
model = model,
form = form,
safe = safe,
build = build,
new = False
)
@classmethod
def wrap(cls, models, build = True, handler = None, **kwargs):
"""
"Wraps" the provided sequence (or single set) of model based data into a
sequence of models (or a single model) so that proper business logic may
be used for operations on top of that data.
In case the extra handler argument is passed it's going to be called for
each model that is going to be "wrapped" allowing an extra "layer" for
the transformation of the model.
The additional named arguments parameters allows extensibility to set
extra value in the creation of the wrapped object.
This operation is specially useful for API based environments where client
side business logic is meant to be added to the static data.
:type models: List
:param models: Sequence (or single) set of models that are going to be wrapped
around instances of the current class.
:type build: bool
:param build: If the "custom" build operation should be performed after
the wrap operation is performed so that new custom attributes may be
injected into the resulting instance.
:type handler: Function
:param handler: Handler function that is going to be called for each of the
models after the build process has been performed, allows an extra transform
operation to be performed at runtime.
:rtype: List
:return: The sequence of models (or single model) representing the provided
set of dictionary models that were sent as arguments.
"""
is_sequence = isinstance(models, (list, tuple))
if not is_sequence: models = [models]
wrapping = []
for model in models:
if not isinstance(model, dict): continue
_model = cls(model = model, **kwargs)
handler and handler(_model.model)
build and cls.build(_model.model, map = False)
wrapping.append(_model)
if is_sequence: return wrapping
else: return wrapping[0] if wrapping else None
@classmethod
def singleton(
cls,
model = None,
form = True,
safe = True,
build = False,
*args,
**kwargs
):
instance = cls.get(raise_e = False, *args, **kwargs)
if instance:
instance.apply(model, form = form, safe_a = safe)
else:
instance = cls.old(
model = model,
form = form,
safe = safe,
build = build
)
return instance
@classmethod
def get(cls, *args, **kwargs):
fields, eager, eager_l, map, rules, meta, build, fill, skip, limit, sort, raise_e = cls._get_attrs(kwargs, (
("fields", None),
("eager", None),
("eager_l", None),
("map", False),
("rules", True),
("meta", False),
("build", True),
("fill", True),
("skip", 0),
("limit", 0),
("sort", None),
("raise_e", True)
))
if eager_l == None: eager_l = map
if eager_l: eager = cls._eager_b(eager)
fields = cls._sniff(fields, rules = rules)
collection = cls._collection()
model = collection.find_one(
kwargs,
fields,
skip = skip,
limit = limit,
sort = sort
)
if not model and raise_e:
is_devel = common.is_devel()
if is_devel: message = "%s not found for %s" % (cls.__name__, str(kwargs))
else: message = "%s not found" % cls.__name__
raise exceptions.NotFoundError(message)
if not model and not raise_e: return model
cls.types(model)
if fill: cls.fill(model, safe = True)
if build: cls.build(model, map = map, rules = rules, meta = meta)
if eager: model = cls._eager(model, eager)
if map: model = cls._resolve_all(model, resolve = False)
return model if map else cls.old(model = model, safe = False)
@classmethod
def find(cls, *args, **kwargs):
fields, eager, eager_l, map, rules, meta, build, fill, skip, limit, sort, raise_e = cls._get_attrs(kwargs, (
("fields", None),
("eager", None),
("eager_l", False),
("map", False),
("rules", True),
("meta", False),
("build", True),
("fill", True),
("skip", 0),
("limit", 0),
("sort", None),
("raise_e", False)
))
if eager_l: eager = cls._eager_b(eager)
cls._find_s(kwargs)
cls._find_d(kwargs)
fields = cls._sniff(fields, rules = rules)
collection = cls._collection()
models = collection.find(
kwargs,
fields,
skip = skip,
limit = limit,
sort = sort
)
if not models and raise_e:
is_devel = common.is_devel()
if is_devel: message = "%s not found for %s" % (cls.__name__, str(kwargs))
else: message = "%s not found" % cls.__name__
raise exceptions.NotFoundError(message)
models = [cls.types(model) for model in models]
if fill: models = [cls.fill(model, safe = True) for model in models]
if build: [cls.build(model, map = map, rules = rules, meta = meta) for model in models]
if eager: models = cls._eager(models, eager)
if map: models = [cls._resolve_all(model, resolve = False) for model in models]
models = models if map else [cls.old(model = model, safe = False) for model in models]
return models
@classmethod
def count(cls, *args, **kwargs):
cls._clean_attrs(kwargs)
collection = cls._collection()
if kwargs:
result = collection.find(kwargs)
result = result.count()
else:
result = collection.count()
return result
@classmethod
def paginate(cls, skip = 0, limit = 1, *args, **kwargs):
# counts the total number of references according to the
# current filter value and then uses this value together
# with the skip value to calculate both the number of pages
# available for the current filter and the current page index
# (note that the index is one index based)
total = cls.count(*args, **kwargs)
count = total / float(limit)
count = math.ceil(count)
count = int(count)
index = skip / float(limit)
index = math.floor(index)
index = int(index) + 1
# calculates the proper size of the current page being requested
# taking into account the total number of values and the limit
size = total % limit if index == count else limit
if size == 0 and total > 0: size = limit
if total == 0: size = 0
# creates the base structure for the page populating with the
# base values that may be used for display of the page
page = dict(
count = count,
index = index,
start = skip + 1,
end = skip + limit,
size = size,
total = total,
sorter = flask.request.args_s.get("sorter", None),
direction = flask.request.args_s.get("direction", "descending")
)
def generate(**kwargs):
# creates the linear parameters list that is going to hold multiple
# key and value tuple representing the multiple parameters
params_l = []
# creates a copy of the current definition of the parameters and for each
# of the exclusion parameters removes it from the current structure
params = dict(flask.request.args_s)
if "async" in params: del params["async"]
# retrieves the "special" sorter keyword based argument and the equivalent
# values for the current page in handling, this values are going to be used
# for the calculus of the direction value (in case it's required)
sorter = kwargs.get("sorter", None)
_sorter = page["sorter"]
direction = page["direction"]
reverse = REVERSE.get(direction, "descending")
# verifies if the sorter value is defined in the arguments and if that's
# the case verifies if it's the same as the current one if that the case
# the direction must be reversed otherwise the default direction is set
if sorter and sorter == _sorter: params["direction"] = reverse
elif sorter: params["direction"] = "descending"
# "copies" the complete set of values from the provided keyword
# based arguments into the parameters map, properly converting them
# into the proper string value (avoiding possible problems)
for key, value in kwargs.items(): params[key] = str(value)
# iterates over the complete set of parameters to be sent to linearize
# them into a sequence of tuples ready to be converted into quoted string
for key, value in params.items():
is_list = isinstance(value, (list, tuple))
if not is_list: value = [value]
for _value in value: params_l.append((key, _value))
# converts the multiple parameters to be used into a linear
# quoted manner so they they may be used as query string values
query = [util.quote(key) + "=" + util.quote(value) for key, value in params_l]
query = "&".join(query)
return "?" + query if query else query
# updates the current page structure so that the (query) generation
# method is exposed in order to modify the current query
page["query"] = generate
return page
@classmethod
def delete_c(cls, *args, **kwargs):
collection = cls._collection()
collection.remove(kwargs)
@classmethod
def ordered(cls, filter = dict):
is_sequence = isinstance(filter, (list, tuple))
if not is_sequence: filter = (filter,)
ordered = list(cls._ordered)
for name, value in cls.__dict__.items():
if name.startswith("_"): continue
if not name == name.lower(): continue
if not isinstance(value, filter): continue
if name in ordered: continue
ordered.append(name)
return ordered
@classmethod
def methods(cls):
# in case the methods are already "cached" in the current
# class (fast retrieval) returns immediately
if "_methods" in cls.__dict__: return cls._methods
# starts the list that will hold the various method names
# for the class, note that this value will be ordered
# according to the class level and the definition order
methods = []
# retrieves the complete model hierarchy for the current model
# and it's going to be used to iterated through the class levels
# in a top to bottom approach strategy
hierarchy = cls.hierarchy()
# iterates over the complete model hierarchy and retrieves the
# ordered set of attributes from it extending the retrieved methods
# list with the value for each of the model levels
for _cls in hierarchy:
ordered = _cls.ordered(
filter = (
types.FunctionType,
classmethod
)
)
methods.extend(ordered)
# saves the retrieved set of methods in the current model definition
# and then returns the value to the caller method as requested
cls._methods = methods
return methods
@classmethod
def fields(cls):
# in case the fields are already "cached" in the current
# class (fast retrieval) returns immediately
if "_fields" in cls.__dict__: return cls._fields
# starts the list that will hold the various field names
# for the class, note that this value will be ordered
# according to the class level and the definition order
fields = []
# retrieves the complete model hierarchy for the current model
# and it's going to be used to iterated through the class levels
# in a top to bottom approach strategy
hierarchy = cls.hierarchy()
# iterates over the complete model hierarchy and retrieves the
# ordered set of attributes from it extending the retrieved fields
# list with the value for each of the model levels
for _cls in hierarchy:
ordered = _cls.ordered()
fields.extend(ordered)
# saves the retrieved set of fields in the current model definition
# and then returns the value to the caller method as requested
cls._fields = fields
return fields
@classmethod
def definition(cls):
# in case the definition is already "cached" in the current
# class (fast retrieval) returns immediately
if "_definition" in cls.__dict__: return cls._definition
# creates the map that will hold the complete definition of
# the current model
definition = {}
# retrieves the complete model hierarchy for the current model
# this should allow the method to retrieve the complete set
# of fields for the current model
hierarchy = cls.hierarchy()
# iterates over all the classes in the hierarchy to creates the
# map that will contain the various names of the current model
# associated with its definition map
for _cls in hierarchy:
for name, value in _cls.__dict__.items():
if name.startswith("_"): continue
if not name == name.lower(): continue
if not isinstance(value, dict): continue
if name in definition: raise exceptions.OperationalError(
"Duplicated attribute '%s' in '%s' hierarchy" % (name, _cls.__name__)
)
definition[name] = value
# sets the "default" definition for the based identifier
# (underlying identifier attribute)
definition["_id"] = dict()
# saves the currently generated definition under the current
# class and then returns the contents of it to the caller method
cls._definition = definition
return definition
@classmethod
def definition_extended(cls):
# in case the definition extended is already "cached" in the current
# class (fast retrieval) returns immediately
if "_definition_extended" in cls.__dict__: return cls._definition_extended
# retrieves the base definition dictionary and duplicated it adding
# the element present in the set of extra definition (overridable on
# a per model basis, providing extension)
definition_extended = dict(cls.definition())
definition_extended.update(cls.extra_definition())
# saves the currently generated definition extended under the current
# class and then returns the contents of it to the caller method
cls._definition_extended = definition_extended
return definition_extended
@classmethod
def links(cls):
# in case the links are already "cached" in the current
# class (fast retrieval) returns immediately
if "_links" in cls.__dict__: return cls._links
# creates the list that will hold the complete set of method
# names for links type methods
links = []
# retrieves the complete set of method names for the current
# class this is going to be used to determine the ones that
# are considered to be link oriented
methods = cls.methods()
# iterates over the complete set of method names for the current
# class hierarchy to determine the ones that are links
for name in methods:
method = getattr(cls, name)
if not hasattr(method, "_link"): continue
reference = hasattr(method, "__self__") and method.__self__
is_instance = False if reference else True
method._link["instance"] = is_instance
links.append(method._link)
# sorts the various links taking into account the name of
# the link, this is considered the pre-defined order
links.sort(key = lambda item: item["name"])
# saves the list of link method names defined under the current
# class and then returns the contents of it to the caller method
cls._links = links
return links
@classmethod
def links_m(cls):
# in case the links are already "cached" in the current
# class (fast retrieval) returns immediately
if "_links_m" in cls.__dict__: return cls._links_m
# creates the map that will hold the complete set of method
# names for links type methods
links_m = dict()
# retrieves the complete set of method names for the current
# class this is going to be used to determine the ones that
# are considered to be link oriented
methods = cls.methods()
# iterates over the complete set of method names for the current
# class hierarchy to determine the ones that are links
for name in methods:
method = getattr(cls, name)
if not hasattr(method, "_link"): continue
links_m[method.__name__] = method._link
# saves the map of link method names defined under the current
# class and then returns the contents of it to the caller method
cls._links_m = links_m
return links_m
@classmethod
def link(cls, name):
links_m = cls.links_m()
return links_m.get(name, None)
@classmethod
def operations(cls):
# in case the operations are already "cached" in the current
# class (fast retrieval) returns immediately
if "_operations" in cls.__dict__: return cls._operations
# creates the list that will hold the complete set of method
# names for operations type methods
operations = []
# retrieves the complete set of method names for the current
# class this is going to be used to determine the ones that
# are considered to be operation oriented
methods = cls.methods()
# iterates over the complete set of method names for the current
# class hierarchy to determine the ones that are operations
for name in methods:
method = getattr(cls, name)
if not hasattr(method, "_operation"): continue
reference = hasattr(method, "__self__") and method.__self__
is_instance = False if reference else True
method._operation["instance"] = is_instance
operations.append(method._operation)
# sorts the various operations taking into account the name of
# the operation, this is considered the pre-defined order
operations.sort(key = lambda item: item["name"])
# saves the list of operation method names defined under the current
# class and then returns the contents of it to the caller method
cls._operations = operations
return operations
@classmethod
def operations_m(cls):
# in case the operations are already "cached" in the current
# class (fast retrieval) returns immediately
if "_operations_m" in cls.__dict__: return cls._operations_m
# creates the map that will hold the complete set of method
# names for operations type methods
operations_m = dict()
# retrieves the complete set of method names for the current
# class this is going to be used to determine the ones that
# are considered to be operation oriented
methods = cls.methods()
# iterates over the complete set of method names for the current
# class hierarchy to determine the ones that are operations
for name in methods:
method = getattr(cls, name)
if not hasattr(method, "_operation"): continue
operations_m[method.__name__] = method._operation
# saves the map of operation method names defined under the current
# class and then returns the contents of it to the caller method
cls._operations_m = operations_m
return operations_m
@classmethod
def operation(cls, name):
operations_m = cls.operations_m()
return operations_m.get(name, None)
@classmethod
def views(cls):
# in case the views are already "cached" in the current
# class (fast retrieval) returns immediately
if "_views" in cls.__dict__: return cls._views
# creates the list that will hold the complete set of method
# names for views type methods
views = []
# retrieves the complete set of method names for the current
# class this is going to be used to determine the ones that
# are considered to be view oriented
methods = cls.methods()
# iterates over the complete set of method names for the current
# class hierarchy to determine the ones that are views
for name in methods:
method = getattr(cls, name)
if not hasattr(method, "_view"): continue
reference = hasattr(method, "__self__") and method.__self__
is_instance = False if reference else True
method._view["instance"] = is_instance
views.append(method._view)
# sorts the various views taking into account the name of
# the view, this is considered the pre-defined order
views.sort(key = lambda item: item["name"])
# saves the list of view method names defined under the current
# class and then returns the contents of it to the caller method
cls._views = views
return views
@classmethod
def views_m(cls):
# in case the views are already "cached" in the current
# class (fast retrieval) returns immediately
if "_views_m" in cls.__dict__: return cls._views_m
# creates the map that will hold the complete set of method
# names for views type methods
views_m = dict()
# retrieves the complete set of method names for the current
# class this is going to be used to determine the ones that
# are considered to be view oriented
methods = cls.methods()
# iterates over the complete set of method names for the current
# class hierarchy to determine the ones that are views
for name in methods:
method = getattr(cls, name)
if not hasattr(method, "_view"): continue
views_m[method.__name__] = method._view
# saves the map of view method names defined under the current
# class and then returns the contents of it to the caller method
cls._views_m = views_m
return views_m
@classmethod
def view(cls, name):
views_m = cls.views_m()
return views_m.get(name, None)
@classmethod
def definition_n(cls, name):
definition = cls.definition_extended()
if not name in definition: return {}
return definition[name]
@classmethod
def register(cls, lazy = False):
if lazy: return
cls.setup()
@classmethod
def unregister(cls, lazy = False):
if lazy: return
cls.teardown()
@classmethod
def setup(cls):
cls._build_indexes()
@classmethod