blob: 7aef79307c59fcfa0bfea1959aae115710ac1d17 [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
Tony Macka7dbd422015-01-05 22:48:11 -05007from util.logger import logger
Sapan Bhatia0235e982014-09-03 13:14:40 -04008
Sapan Bhatiae2ace182015-01-16 22:17:42 +00009
Scott Baker79eaac22014-10-21 15:05:29 -070010modelPolicyEnabled = True
11
12def EnableModelPolicy(x):
13 global modelPolicyEnabled
14 modelPolicyEnabled = x
15
Sapan Bhatia475c5972014-11-05 10:32:41 -050016def update_dep(d, o):
Sapan Bhatia142314e2014-12-21 02:32:50 -050017 try:
18 if (d.updated < o.updated):
19 d.save(update_fields=['updated'])
20 except AttributeError,e:
Sapan Bhatia142314e2014-12-21 02:32:50 -050021 raise e
Sapan Bhatia475c5972014-11-05 10:32:41 -050022
23def delete_if_inactive(d, o):
24 #print "Deleting %s (%s)"%(d,d.__class__.__name__)
25 d.delete()
26 return
27
Sapan Bhatiae2ace182015-01-16 22:17:42 +000028def execute_model_policy(policy_name, instance, update_fields_empty, deleted):
29 if (update_fields_empty):
30 # Automatic dirtying
31 #walk_inv_deps(update_dep, instance)
32
33 try:
34 policy_handler = getattr(model_policies, policy_name, None)
35 logger.error("POLICY HANDLER: %s %s" % (policy_name, policy_handler))
36 if policy_handler is not None:
37 policy_handler.handle(instance)
38 except:
39 logger.log_exc("Model Policy Error:")
40 print "Policy Exceution Error"
41 elif deleted:
42 walk_inv_deps(delete_if_inactive, instance)
43
44
Sapan Bhatia0235e982014-09-03 13:14:40 -040045@receiver(post_save)
Scott Bakerd56ccd72014-09-30 14:53:45 -070046def post_save_handler(sender, instance, **kwargs):
Scott Baker79eaac22014-10-21 15:05:29 -070047 if not modelPolicyEnabled:
48 return
Sapan Bhatia475c5972014-11-05 10:32:41 -050049
50 sender_name = sender.__name__
51 policy_name = 'model_policy_%s'%sender_name
Sapan Bhatiae2ace182015-01-16 22:17:42 +000052 if (not kwargs['update_fields']):
53 noargs = True
54 deleted = False
55 else:
56 noargs = False
57 deleted = True
Sapan Bhatia475c5972014-11-05 10:32:41 -050058
Sapan Bhatiae2ace182015-01-16 22:17:42 +000059 execute_model_policy(policy_name, instance, noargs, deleted)
60
Sapan Bhatia475c5972014-11-05 10:32:41 -050061