blob: e12b15cb8bc61a1c876bce2c19ee409763c347da [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 Bhatiafe9bc892014-09-15 03:48:11 -04004from core.models import *
Sapan Bhatia14356b72014-11-05 10:32:41 -05005from dependency_walker import *
Sapan Bhatiafe9bc892014-09-15 03:48:11 -04006import model_policies
Tony Mack3066a952015-01-05 22:48:11 -05007from util.logger import logger
Sapan Bhatia0235e982014-09-03 13:14:40 -04008
Scott Bakerf3428702014-10-21 15:05:29 -07009modelPolicyEnabled = True
10
11def EnableModelPolicy(x):
12 global modelPolicyEnabled
13 modelPolicyEnabled = x
14
Sapan Bhatia14356b72014-11-05 10:32:41 -050015def update_dep(d, o):
Sapan Bhatia6d1241c2014-12-21 02:32:50 -050016 try:
17 if (d.updated < o.updated):
18 d.save(update_fields=['updated'])
19 except AttributeError,e:
20 pdb.set_trace()
21 raise e
Sapan Bhatia14356b72014-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 Bhatia0235e982014-09-03 13:14:40 -040028@receiver(post_save)
Scott Baker2ba34852014-09-30 14:53:45 -070029def post_save_handler(sender, instance, **kwargs):
Scott Bakerf3428702014-10-21 15:05:29 -070030 if not modelPolicyEnabled:
31 return
Sapan Bhatia14356b72014-11-05 10:32:41 -050032
33 sender_name = sender.__name__
34 policy_name = 'model_policy_%s'%sender_name
Sapan Bhatia9a3af232014-09-15 04:04:32 -040035
36 if (not kwargs['update_fields']):
Sapan Bhatia14356b72014-11-05 10:32:41 -050037 # Automatic dirtying
38 walk_inv_deps(update_dep, instance)
39
Sapan Bhatia9a3af232014-09-15 04:04:32 -040040 try:
Scott Baker6021fa82014-10-09 12:03:22 -070041 policy_handler = getattr(model_policies, policy_name, None)
42 if policy_handler is not None:
43 policy_handler.handle(instance)
Sapan Bhatia9a3af232014-09-15 04:04:32 -040044 except:
Tony Mack3066a952015-01-05 22:48:11 -050045 logger.log_exc("Model Policy Error:")
Sapan Bhatia14356b72014-11-05 10:32:41 -050046 elif 'deleted' in kwargs['update_fields']:
47 walk_inv_deps(delete_if_inactive, instance)
48