blob: de6f73d49cf84db4a751a2e3d9eb65855c2511aa [file] [log] [blame]
Sapan Bhatia0235e982014-09-03 13:14:40 -04001from django.db.models.signals import post_save
2from django.dispatch import receiver
3import pdb
Sapan Bhatia3a5980e2014-09-15 03:48:11 -04004from core.models import *
Sapan Bhatia475c5972014-11-05 10:32:41 -05005from dependency_walker import *
Sapan Bhatia3a5980e2014-09-15 03:48:11 -04006import model_policies
Sapan Bhatia0235e982014-09-03 13:14:40 -04007
Scott Baker79eaac22014-10-21 15:05:29 -07008modelPolicyEnabled = True
9
10def EnableModelPolicy(x):
11 global modelPolicyEnabled
12 modelPolicyEnabled = x
13
Sapan Bhatia475c5972014-11-05 10:32:41 -050014def update_dep(d, o):
Sapan Bhatia142314e2014-12-21 02:32:50 -050015 try:
16 if (d.updated < o.updated):
17 d.save(update_fields=['updated'])
18 except AttributeError,e:
19 pdb.set_trace()
20 raise e
Sapan Bhatia475c5972014-11-05 10:32:41 -050021
22def delete_if_inactive(d, o):
23 #print "Deleting %s (%s)"%(d,d.__class__.__name__)
24 d.delete()
25 return
26
Sapan Bhatia0235e982014-09-03 13:14:40 -040027@receiver(post_save)
Scott Bakerd56ccd72014-09-30 14:53:45 -070028def post_save_handler(sender, instance, **kwargs):
Scott Baker79eaac22014-10-21 15:05:29 -070029 if not modelPolicyEnabled:
30 return
Sapan Bhatia475c5972014-11-05 10:32:41 -050031
32 sender_name = sender.__name__
33 policy_name = 'model_policy_%s'%sender_name
Sapan Bhatia640f2b72014-09-15 04:04:32 -040034
35 if (not kwargs['update_fields']):
Sapan Bhatia475c5972014-11-05 10:32:41 -050036 # Automatic dirtying
37 walk_inv_deps(update_dep, instance)
38
Sapan Bhatia640f2b72014-09-15 04:04:32 -040039 try:
Scott Bakerc1f9cce2014-10-09 12:03:22 -070040 policy_handler = getattr(model_policies, policy_name, None)
41 if policy_handler is not None:
42 policy_handler.handle(instance)
Sapan Bhatia640f2b72014-09-15 04:04:32 -040043 except:
44 pass
Sapan Bhatia475c5972014-11-05 10:32:41 -050045 elif 'deleted' in kwargs['update_fields']:
46 walk_inv_deps(delete_if_inactive, instance)
47