-
Notifications
You must be signed in to change notification settings - Fork 44
/
mixins.py
1588 lines (1315 loc) · 56 KB
/
mixins.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
# -*- coding: utf-8 -*-
import logging
import pytz
from sqlalchemy import (Table, Column, String, Integer, ForeignKey, Interval,
Float, Enum)
from sqlalchemy.exc import UnboundExecutionError, OperationalError
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.orm import synonym, relationship, validates
from stalker.db.declarative import Base
from stalker.db.types import GenericDateTime
from stalker.log import logging_level
logger = logging.getLogger(__name__)
logger.setLevel(logging_level)
def create_secondary_table(
primary_cls_name,
secondary_cls_name,
primary_cls_table_name,
secondary_cls_table_name,
secondary_table_name=None):
"""creates any secondary table
"""
from stalker.models import make_plural
plural_secondary_cls_name = make_plural(secondary_cls_name)
# use the given class_name and the class_table
if not secondary_table_name:
secondary_table_name = '%s_%s' % (primary_cls_name,
plural_secondary_cls_name)
# check if the table is already defined
if secondary_table_name not in Base.metadata:
secondary_table = Table(
secondary_table_name, Base.metadata,
Column(
'%s_id' % primary_cls_name.lower(),
Integer,
ForeignKey('%s.id' % primary_cls_table_name),
primary_key=True,
),
Column(
'%s_id' % secondary_cls_name.lower(),
Integer,
ForeignKey('%s.id' % secondary_cls_table_name),
primary_key=True,
)
)
else:
secondary_table = Base.metadata.tables[secondary_table_name]
return secondary_table
class TargetEntityTypeMixin(object):
"""Adds target_entity_type attribute to mixed in class.
:param target_entity_type: The target entity type which this class is
designed for. Should be a class or a class name.
For example::
from stalker import SimpleEntity, TargetEntityTypeMixin, Project
class A(SimpleEntity, TargetEntityTypeMixin):
__tablename__ = "As"
__mapper_args__ = {"polymorphic_identity": "A"}
def __init__(self, **kwargs):
super(A, self).__init__(**kwargs)
TargetEntityTypeMixin.__init__(self, **kwargs)
a_obj = A(target_entity_type=Project)
The ``a_obj`` will only be accepted by
:class:`.Project` instances. You can not assign it to any other class
which accepts a :class:`.Type` instance.
To control the mixed-in class behaviour add these class variables to the
mixed in class:
__nullable_target__ : controls if the target_entity_type can be
nullable or not. Default is False.
__unique_target__ : controls if the target_entity_type should be
unique, so there is only one object for one type.
Default is False.
"""
__nullable_target__ = False
__unique_target__ = False
@declared_attr
def _target_entity_type(cls):
return Column(
"target_entity_type",
String(128),
nullable=cls.__nullable_target__,
unique=cls.__unique_target__
)
def __init__(self, target_entity_type=None, **kwargs):
self._target_entity_type = \
self._validate_target_entity_type(target_entity_type)
def _validate_target_entity_type(self, target_entity_type_in):
"""validates the given target_entity_type value
"""
# it can not be None
if target_entity_type_in is None:
raise TypeError(
"%s.target_entity_type can not be None" %
self.__class__.__name__
)
# check if it is a class
if isinstance(target_entity_type_in, type):
target_entity_type_in = target_entity_type_in.__name__
if target_entity_type_in == "":
raise ValueError(
"%s.target_entity_type can not be empty" %
self.__class__.__name__
)
return target_entity_type_in
def _target_entity_type_getter(self):
return self._target_entity_type
@declared_attr
def target_entity_type(cls):
return synonym(
"_target_entity_type",
descriptor=property(
fget=cls._target_entity_type_getter,
doc="""The entity type which this object is valid for.
Usually it is set to the TargetClass directly.
"""
)
)
class StatusMixin(object):
"""Makes the mixed in object statusable.
This mixin adds status and status_list attributes to the mixed in class.
Any object that needs a status and a corresponding status list can include
this mixin.
When mixed with a class which don't have an __init__ method, the mixin
supplies one, and in this case the parameters below must be defined.
:param status_list: this attribute holds a status list object, which shows
the possible statuses that this entity could be in. This attribute can
not be empty or None. Giving a StatusList object, the
StatusList.target_entity_type should match the current class.
.. versionadded:: 0.1.2.a4
The status_list argument now can be skipped or can be None if there
is an active database connection and there is a suitable
:class:`.StatusList` instance in the database whom
:attr:`.StatusList.target_entity_type` attribute is set to the current
mixed-in class name.
:param status: It is a :class:`.Status` instance which shows the current
status of the statusable object. Integer values are also accepted, which
shows the index of the desired status in the ``status_list`` attribute of
the current statusable object. If a :class:`.Status` instance is
supplied, it should also be present in the ``status_list`` attribute. If
set to None then the first :class:`.Status` instance in the
``status_list`` will be used.
.. versionadded:: 0.2.0
Status attribute as Status instance:
It is now possible to set the status of the instance by a
:class:`.Status` instance directly. And the :attr:`.StatusMixin.status`
will return a proper :class:`.Status` instance.
"""
def __init__(self, status=None, status_list=None, **kwargs):
self.status_list = status_list
self.status = status
@declared_attr
def status_id(cls):
return Column(
'status_id',
Integer,
ForeignKey('Statuses.id'),
nullable=False
# This is set to nullable=True but it is impossible to set the
# status to None by using this Declarative approach.
#
# This is done in that way cause SQLAlchemy was flushing the data
# (AutoFlush) preliminarily while checking if the given Status was
# in the related StatusList, and it was complaining about the
# status can not be null
)
@declared_attr
def status(cls):
return relationship(
'Status',
primaryjoin="%s.status_id==Status.status_id" % cls.__name__,
doc="""The current status of the object.
It is a :class:`.Status` instance which
is one of the Statuses stored in the ``status_list`` attribute
of this object.
"""
)
@declared_attr
def status_list_id(cls):
return Column(
'status_list_id',
Integer,
ForeignKey('StatusLists.id'),
nullable=False
)
@declared_attr
def status_list(cls):
return relationship(
"StatusList",
primaryjoin= \
"%s.status_list_id==StatusList.status_list_id" %
cls.__name__,
)
@validates("status_list")
def _validate_status_list(self, key, status_list):
"""validates the given status_list_in value
"""
from stalker.models.status import StatusList
if status_list is None:
# check if there is a db setup and try to get the appropriate
# StatusList from the database
# disable autoflush to prevent premature class initialization
from stalker.db.session import DBSession
with DBSession.no_autoflush:
try:
# try to get a StatusList with the target_entity_type is
# matching the class name
status_list = StatusList.query\
.filter_by(target_entity_type=self.__class__.__name__)\
.first()
except (UnboundExecutionError, OperationalError):
# it is not mapped just skip it
pass
# if it is still None
if status_list is None:
# there is no db so raise an error because there is no way
# to get an appropriate StatusList
raise TypeError(
"%s instances can not be initialized without a "
"stalker.models.status.StatusList instance, please pass a "
"suitable StatusList (StatusList.target_entity_type=%s) "
"with the 'status_list' argument" %
(self.__class__.__name__, self.__class__.__name__)
)
else:
# it is not an instance of status_list
if not isinstance(status_list, StatusList):
raise TypeError(
"%s.status_list should be an instance of "
"stalker.models.status.StatusList not %s" %
(self.__class__.__name__, status_list.__class__.__name__)
)
# check if the entity_type matches to the
# StatusList.target_entity_type
if self.__class__.__name__ != status_list.target_entity_type:
raise TypeError(
"The given StatusLists' target_entity_type is %s, "
"whereas the entity_type of this object is %s" %
(status_list.target_entity_type, self.__class__.__name__)
)
return status_list
@validates('status')
def _validate_status(self, key, status):
"""validates the given status value
"""
from stalker.models.status import Status
from stalker.db.session import DBSession
# it is set to None
if status is None:
with DBSession.no_autoflush:
status = self.status_list.statuses[0]
# it is not an instance of status or int
if not isinstance(status, (Status, int)):
raise TypeError(
"%(class)s.status must be an instance of "
"stalker.models.status.Status or an integer showing the index "
"of the Status object in the %(class)s.status_list, not "
"%(status)s" %
{
'class': self.__class__.__name__,
'status': status.__class__.__name__
}
)
if isinstance(status, int):
# if it is not in the correct range:
if status < 0:
raise ValueError(
"%s.status must be a non-negative integer" %
self.__class__.__name__
)
if status >= len(self.status_list.statuses):
raise ValueError(
"%s.status can not be bigger than the length of the "
"status_list" % self.__class__.__name__
)
# get the status instance out of the status_list instance
status = self.status_list[status]
# check if the given status is in the status_list
# logger.debug('self.status_list: %s' % self.status_list)
# logger.debug('given status: %s' % status)
if status not in self.status_list:
raise ValueError(
"The given Status instance for %s.status is not in the "
"%s.status_list, please supply a status from that list." %
(self.__class__.__name__, self.__class__.__name__)
)
return status
class DateRangeMixin(object):
"""Adds date range info to the mixed in class.
Adds date range information like ``start``, ``end`` and ``duration``. These
attributes will be used in TaskJuggler. Because ``effort`` is only
meaningful if there are some ``resources`` this attribute has been left
special for :class:`.Task` class. The ``length`` has not been implemented
because of its rare use.
The preceding order for the attributes is as follows::
start > end > duration
So if all of the parameters are given only the ``start`` and the ``end``
will be used and the ``duration`` will be calculated accordingly. In any
other conditions the missing parameter will be calculated from the
following table:
+-------+-----+----------+----------------------------------------+
| start | end | duration | DEFAULTS |
+=======+=====+==========+========================================+
| | | | start = datetime.datetime.now(pytz.utc)|
| | | | |
| | | | duration = datetime.timedelta(days=10) |
| | | | |
| | | | end = start + duration |
+-------+-----+----------+----------------------------------------+
| X | | | duration = datetime.timedelta(days=10) |
| | | | |
| | | | end = start + duration |
+-------+-----+----------+----------------------------------------+
| X | X | | duration = end - start |
+-------+-----+----------+----------------------------------------+
| X | | X | end = start + duration |
+-------+-----+----------+----------------------------------------+
| X | X | X | duration = end - start |
+-------+-----+----------+----------------------------------------+
| | X | X | start = end - duration |
+-------+-----+----------+----------------------------------------+
| | X | | duration = datetime.timedelta(days=10) |
| | | | |
| | | | start = end - duration |
+-------+-----+----------+----------------------------------------+
| | | X | start = datetime.datetime.now(pytz.utc)|
| | | | |
| | | | end = start + duration |
+-------+-----+----------+----------------------------------------+
Only the ``start``, ``end`` will be stored. The ``duration`` attribute is
the direct difference of the the ``start`` and ``end`` attributes, so there
is no need to store it. But if will be used in calculation of the start and
end values.
The start and end attributes have a ``computed`` companion. Which are the
return values from TaskJuggler. so for ``start`` there is the
``computed_start`` and for ``end`` there is the ``computed_end``
attributes.
The date attributes can be managed with timezones. Follow the Python idioms
shown in the `documentation of datetime`_
.. _documentation of datetime: https://docs.python.org/library/datetime.html
:param start: the start date of the entity, should be a datetime.datetime
instance, the start is the pin point for the date calculation. In
any condition if the start is available then the value will be
preserved. If start passes the end the end is also changed
to a date to keep the timedelta between dates. The default value is
datetime.datetime.now(pytz.utc)
:type start: :class:`datetime.datetime`
:param end: the end of the entity, should be a datetime.datetime instance,
when the start is changed to a date passing the end, then the end is also
changed to a later date so the timedelta between the dates is kept.
:type end: :class:`datetime.datetime` or :class:`datetime.timedelta`
:param duration: The duration of the entity. It is a
:class:`datetime.timedelta` instance. The default value is read from
the :class:`.Config` class. See the table above for the initialization
rules.
:type duration: :class:`datetime.timedelta`
"""
def __init__(
self,
start=None,
end=None,
duration=None,
**kwargs
):
self._start, self._end, self._duration = self._validate_dates(start, end, duration)
@declared_attr
def _end(cls):
return Column("end", GenericDateTime)
def _end_getter(self):
"""The date that the entity should be delivered.
The end can be set to a datetime.timedelta and in this case it will be
calculated as an offset from the start and converted to
datetime.datetime again. Setting the start to a date passing the end
will also set the end, so the timedelta between them is preserved,
default value is 10 days
"""
from stalker.db.session import DBSession
with DBSession.no_autoflush:
return self._end
def _end_setter(self, end_in):
self._start, self._end, self._duration = \
self._validate_dates(self.start, end_in, self.duration)
@declared_attr
def end(cls):
return synonym(
"_end",
descriptor=property(
cls._end_getter,
cls._end_setter
)
)
@declared_attr
def _start(cls):
return Column("start", GenericDateTime)
def _start_getter(self):
"""The date that this entity should start.
Also effects the :attr:`.DateRangeMixin.end` attribute value in certain
conditions, if the :attr:`.DateRangeMixin.start` is set to a time
passing the :attr:`.DateRangeMixin.end` it will also offset the
:attr:`.DateRangeMixin.end` to keep the
:attr:`.DateRangeMixin.duration` value fixed.
:attr:`.DateRangeMixin.start` should be an instance of
class:`datetime.datetime` and the default value is
:func:`datetime.datetime.now(pytz.utc)`
"""
from stalker.db.session import DBSession
with DBSession.no_autoflush:
return self._start
def _start_setter(self, start_in):
self._start, self._end, self._duration = \
self._validate_dates(start_in, self.end, self.duration)
@declared_attr
def start(cls):
return synonym(
"_start",
descriptor=property(
cls._start_getter,
cls._start_setter,
)
)
@declared_attr
def _duration(cls):
return Column('duration', Interval)
def _duration_getter(self):
from stalker.db.session import DBSession
with DBSession.no_autoflush:
return self._duration
def _duration_setter(self, duration_in):
if duration_in is not None:
import datetime
if isinstance(duration_in, datetime.timedelta):
# set the end to None
# to make it recalculated
self._start, self._end, self._duration = \
self._validate_dates(self.start, None, duration_in)
else:
# use the end
self._start, self._end, self._duration = \
self._validate_dates(self.start, self.end, duration_in)
else:
self._start, self._end, self._duration = \
self._validate_dates(self.start, self.end, duration_in)
@declared_attr
def duration(self):
return synonym(
'_duration',
descriptor=property(
self._duration_getter,
self._duration_setter,
doc="""Duration of the entity.
It is a datetime.timedelta instance. Showing the difference of
the :attr:`.start` and the :attr:`.end`. If edited it changes
the :attr:`.end` attribute value."""
)
)
def _validate_dates(self, start, end, duration):
"""updates the date values
"""
# logger.debug('start : %s' % start)
# logger.debug('end : %s' % end)
# logger.debug('duration : %s' % duration)
from stalker import defaults
import datetime
if not isinstance(start, datetime.datetime):
start = None
if not isinstance(end, datetime.datetime):
end = None
if not isinstance(duration, datetime.timedelta):
duration = None
# check start
if start is None:
# try to calculate the start from end and duration
if end is None:
# set the defaults
start = datetime.datetime.now(pytz.utc)
if duration is None:
# set the defaults
duration = defaults.timing_resolution
end = start + duration
else:
if duration is None:
duration = defaults.timing_resolution
# try:
start = end - duration
# except OverflowError: # end is datetime.datetime.min
# start = end
# check end
if end is None:
if duration is None:
duration = defaults.timing_resolution
end = start + duration
if end < start:
# check duration
if duration is None or duration < datetime.timedelta(1):
duration = datetime.timedelta(1)
# try:
end = start + duration
# except OverflowError: # start is datetime.datetime.max
# end = start
# round the dates to the timing_resolution
rounded_start = self.round_time(start)
rounded_end = self.round_time(end)
rounded_duration = rounded_end - rounded_start
if rounded_duration < defaults.timing_resolution:
rounded_duration = defaults.timing_resolution
rounded_end = rounded_start + rounded_duration
return rounded_start, rounded_end, rounded_duration
@declared_attr
def computed_start(cls):
return Column('computed_start', GenericDateTime)
@declared_attr
def computed_end(cls):
return Column('computed_end', GenericDateTime)
@property
def computed_duration(self):
"""returns the computed_duration as the difference of computed_start
and computed_end if there are computed_start and computed_end otherwise
returns None
"""
return self.computed_end - self.computed_start if self.computed_end and self.computed_start else None
@classmethod
def round_time(cls, dt):
"""Round the given datetime object to the defaults.timing_resolution.
Uses :class:`stalker.defaults.timing_resolution` as the closest number
of seconds to round to.
:param dt: datetime.datetime object, defaults to now.
:type dt: datetime.datetime
Based on Thierry Husson's answer in `Stackoverflow`_
_`Stackoverflow` : https://stackoverflow.com/a/10854034/1431079
"""
# to be compatible with python 2.6 use the following instead of
# total_seconds()
from stalker import defaults
timing_resolution = defaults.timing_resolution
trs = timing_resolution.days * 86400 + timing_resolution.seconds
# convert to seconds
import datetime
import pytz
epoch = datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)
diff = dt - epoch
diff_in_seconds = diff.days * 86400 + diff.seconds
return epoch + datetime.timedelta(
seconds=(diff_in_seconds + trs * 0.5) // trs * trs
)
@property
def total_seconds(self):
"""returns the duration as seconds
"""
return self.duration.days * 86400 + self.duration.seconds
@property
def computed_total_seconds(self):
"""returns the duration as seconds
"""
return self.computed_duration.days * 86400 + self.computed_duration.seconds
class ProjectMixin(object):
"""Allows connecting a :class:`.Project` to the mixed in object.
This also forces a ``all, delete-orphan`` cascade, so when a
:class:``.Project`` instance is deleted then all the class instances that
are inherited from ``ProjectMixin`` will also be deleted. Meaning that, a
class which also derives from ``ProjectMixin`` will not be able to exists
without a project (``delete-orphan`` case).
:param project: A :class:`.Project` instance holding the project which this
object is related to. It can not be None, or anything other than a
:class:`.Project` instance.
:type project: :class:`.Project`
"""
# # add this lines for Sphinx
# __tablename__ = "ProjectMixins"
@declared_attr
def project_id(cls):
return Column(
"project_id",
Integer,
ForeignKey("Projects.id"),
# cannot use nullable cause a Project object needs
# insert itself as the project and it needs post_update
# thus nullable should be True
)
@declared_attr
def project(cls):
from sqlalchemy.orm import backref
backref_table_name = cls.__tablename__.lower()
doc = """The :class:`.Project` instance that
this object belongs to.
"""
return relationship(
"Project",
primaryjoin="%s.c.project_id==Projects.c.id" % cls.__tablename__,
post_update=True, # for project itself
uselist=False,
backref=backref(
backref_table_name,
cascade='all, delete-orphan'
),
doc=doc
)
def __init__(self,
project=None,
**kwargs):
self.project = project
@validates("project")
def _validate_project(self, key, project):
"""validates the given project value
"""
from stalker.models.project import Project
if project is None:
raise TypeError(
"%s.project can not be None it must be an instance of "
"stalker.models.project.Project" % self.__class__.__name__
)
if not isinstance(project, Project):
raise TypeError(
"%s.project should be an instance of "
"stalker.models.project.Project instance not %s" %
(self.__class__.__name__, project.__class__.__name__)
)
return project
class ReferenceMixin(object):
"""Adds reference capabilities to the mixed in class.
References are :class:`stalker.models.link.Link` instances or anything
derived from it, which adds information to the attached objects. The aim of
the References are generally to give more info to direct the evolution of
the object.
:param references: A list of :class:`.Link` instances.
:type references: list of :class:`.Link` instances.
"""
# add this lines for Sphinx
# __tablename__ = "ReferenceMixins"
def __init__(self,
references=None,
**kwargs):
if references is None:
references = []
self.references = references
@declared_attr
def references(cls):
# get secondary table
secondary_table = create_secondary_table(
cls.__name__,
'Link',
cls.__tablename__,
'Links',
"%s_References" % cls.__name__
)
# return the relationship
return relationship(
"Link",
secondary=secondary_table,
doc="""A list of :class:`.Link` instances given as a reference for
this entity.
"""
)
@validates("references")
def _validate_references(self, key, reference):
"""validates the given reference
"""
from stalker.models.link import Link
# all the elements should be instance of stalker.models.entity.Entity
if not isinstance(reference, Link):
raise TypeError(
'All the elements in the %s.references should be '
'stalker.models.link.Link instances not %s' %
(self.__class__.__name__, reference.__class__.__name__)
)
return reference
class ACLMixin(object):
"""A Mixin for adding ACLs to mixed in class.
Access control lists or ACLs are used to determine if the given resource
has the permission to access the given data. It is based on Pyramids
Authorization system but organized to fit in Stalker style.
The ACLMixin adds an attribute called ``permissions`` and a
property called ``__acl__`` to be able to pass the permission data to
Pyramid framework.
"""
@declared_attr
def permissions(cls):
# get the secondary table
secondary_table = create_secondary_table(
cls.__name__, 'Permission', cls.__tablename__, 'Permissions'
)
return relationship('Permission', secondary=secondary_table)
@validates('permissions')
def _validate_permissions(self, key, permission):
"""validates the given permission value
"""
from stalker.models.auth import Permission
if not isinstance(permission, Permission):
raise TypeError(
"%s.permissions should be all instances of "
"stalker.models.auth.Permission not %s" %
(self.__class__.__name__, permission.__class__.__name__)
)
return permission
@property
def __acl__(self):
"""Returns Pyramid friendly ACL list composed by the:
* Permission.access (Ex: 'Allow' or 'Deny')
* The Mixed in class name and the object name (Ex: 'User:eoyilmaz')
* The Action and the target class name (Ex: 'Create_Asset')
Thus a list of tuple is returned as follows::
__acl__ = [
('Allow', 'User:eoyilmaz', 'Create_Asset'),
]
For the last example user eoyilmaz can grant access to views requiring
'Add_Project' permission.
"""
return [(perm.access,
'%s:%s' % (self.__class__.__name__, self.name),
'%s_%s' % (perm.action, perm.class_name))
for perm in self.permissions]
class CodeMixin(object):
"""Adds code info to the mixed in class.
.. versionadded:: 0.2.0
The code attribute of the SimpleEntity is now introduced as a separate
mixin. To let it be used by the classes it is really needed.
The CodeMixin just adds a new field called ``code``. It is a very simple
attribute and is used for simplifying long names (like Project.name etc.).
Contrary to previous implementations the code attribute is not formatted in
anyway, so care needs to be taken if the code attribute is going to be used
in filesystem as file and directory names.
:param str code: The code attribute is a string, can not be empty or can
not be None.
"""
def __init__(self, code=None, **kwargs):
logger.debug('code: %s' % code)
self.code = code
@declared_attr
def code(cls):
return Column(
'code',
String(256),
nullable=False,
doc="""The code name of this object.
It accepts strings. Can not be None."""
)
@validates('code')
def _validate_code(self, key, code):
"""validates the given code attribute
"""
logger.debug('validating code value of: %s' % code)
if code is None:
raise TypeError("%s.code cannot be None" % self.__class__.__name__)
from stalker import __string_types__
if not isinstance(code, __string_types__):
raise TypeError(
'%s.code should be a string not %s' %
(self.__class__.__name__, code.__class__.__name__)
)
if code == '':
raise ValueError(
'%s.code can not be an empty string' % self.__class__.__name__
)
return code
class WorkingHoursMixin(object):
"""Sets working hours for the mixed in class.
Generally is meaningful for users, departments and studio.
:param working_hours: A :class:`.WorkingHours` instance showing the working
hours settings.
"""
def __init__(self, working_hours=None, **kwargs):
self.working_hours = working_hours
@declared_attr
def working_hours_id(cls):
"""the id of the related working hours
"""
return Column(
'working_hours_id',
Integer,
ForeignKey('WorkingHours.id')
)
@declared_attr
def working_hours(cls):
return relationship(
'WorkingHours',
primaryjoin='%s.working_hours_id==WorkingHours.working_hours_id' %
cls.__name__
)
@validates('working_hours')
def _validate_working_hours(self, key, wh):
"""validates the given working hours value
"""
from stalker import WorkingHours
if wh is None:
wh = WorkingHours() # without any argument this will use the
# default.working_hours settings
elif not isinstance(wh, WorkingHours):
raise TypeError(
'%s.working_hours should be a '
'stalker.models.studio.WorkingHours instance, not %s' % (
self.__class__.__name__, wh.__class__.__name__
)
)
return wh
class ScheduleMixin(object):
"""Adds schedule info to the mixed in class.
Adds attributes like schedule_timing, schedule_unit and schedule_model
attributes to the mixed in class.
Use the ``__default_schedule_attr_name__`` attribute to customize the
column names.
"""
# some default values that can be overridden in Mixed in classes
from stalker import defaults
__default_schedule_attr_name__ = 'schedule'
__default_schedule_timing__ = defaults.timing_resolution.seconds / 60
__default_schedule_unit__ = 'h'
__default_schedule_models__ = defaults.task_schedule_models
def __init__(
self,
schedule_timing=None,
schedule_unit=None,
schedule_model=None,
schedule_constraint=0,
**kwargs
):
self.schedule_constraint = schedule_constraint
self.schedule_model = schedule_model