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 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
Scott Baker79eaac22014-10-21 15:05:29 -07009modelPolicyEnabled = True
10
11def EnableModelPolicy(x):
12 global modelPolicyEnabled
13 modelPolicyEnabled = x
14
Sapan Bhatia475c5972014-11-05 10:32:41 -050015def update_dep(d, o):
Sapan Bhatia142314e2014-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 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 Bhatia0235e982014-09-03 13:14:40 -040028@receiver(post_save)
Scott Bakerd56ccd72014-09-30 14:53:45 -070029def post_save_handler(sender, instance, **kwargs):
Scott Baker79eaac22014-10-21 15:05:29 -070030 if not modelPolicyEnabled:
31 return
Sapan Bhatia475c5972014-11-05 10:32:41 -050032
33 sender_name = sender.__name__
34 policy_name = 'model_policy_%s'%sender_name
Sapan Bhatia640f2b72014-09-15 04:04:32 -040035
36 if (not kwargs['update_fields']):
Sapan Bhatia475c5972014-11-05 10:32:41 -050037 # Automatic dirtying
38 walk_inv_deps(update_dep, instance)
39
Sapan Bhatia640f2b72014-09-15 04:04:32 -040040 try:
Scott Bakerc1f9cce2014-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 Bhatia640f2b72014-09-15 04:04:32 -040044 except:
Tony Macka7dbd422015-01-05 22:48:11 -050045 logger.log_exc("Model Policy Error:")
Sapan Bhatia475c5972014-11-05 10:32:41 -050046 elif 'deleted' in kwargs['update_fields']:
47 walk_inv_deps(delete_if_inactive, instance)
48