Sapan Bhatia | 0235e98 | 2014-09-03 13:14:40 -0400 | [diff] [blame] | 1 | from django.db.models.signals import post_save |
| 2 | from django.dispatch import receiver |
| 3 | import pdb |
Sapan Bhatia | 3a5980e | 2014-09-15 03:48:11 -0400 | [diff] [blame] | 4 | from core.models import * |
Sapan Bhatia | 475c597 | 2014-11-05 10:32:41 -0500 | [diff] [blame] | 5 | from dependency_walker import * |
Sapan Bhatia | 3a5980e | 2014-09-15 03:48:11 -0400 | [diff] [blame] | 6 | import model_policies |
Tony Mack | a7dbd42 | 2015-01-05 22:48:11 -0500 | [diff] [blame] | 7 | from util.logger import logger |
Sapan Bhatia | 0235e98 | 2014-09-03 13:14:40 -0400 | [diff] [blame] | 8 | |
Scott Baker | 79eaac2 | 2014-10-21 15:05:29 -0700 | [diff] [blame] | 9 | modelPolicyEnabled = True |
| 10 | |
| 11 | def EnableModelPolicy(x): |
| 12 | global modelPolicyEnabled |
| 13 | modelPolicyEnabled = x |
| 14 | |
Sapan Bhatia | 475c597 | 2014-11-05 10:32:41 -0500 | [diff] [blame] | 15 | def update_dep(d, o): |
Sapan Bhatia | 142314e | 2014-12-21 02:32:50 -0500 | [diff] [blame] | 16 | 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 Bhatia | 475c597 | 2014-11-05 10:32:41 -0500 | [diff] [blame] | 22 | |
| 23 | def delete_if_inactive(d, o): |
| 24 | #print "Deleting %s (%s)"%(d,d.__class__.__name__) |
| 25 | d.delete() |
| 26 | return |
| 27 | |
Sapan Bhatia | 0235e98 | 2014-09-03 13:14:40 -0400 | [diff] [blame] | 28 | @receiver(post_save) |
Scott Baker | d56ccd7 | 2014-09-30 14:53:45 -0700 | [diff] [blame] | 29 | def post_save_handler(sender, instance, **kwargs): |
Scott Baker | 79eaac2 | 2014-10-21 15:05:29 -0700 | [diff] [blame] | 30 | if not modelPolicyEnabled: |
| 31 | return |
Sapan Bhatia | 475c597 | 2014-11-05 10:32:41 -0500 | [diff] [blame] | 32 | |
| 33 | sender_name = sender.__name__ |
| 34 | policy_name = 'model_policy_%s'%sender_name |
Sapan Bhatia | 640f2b7 | 2014-09-15 04:04:32 -0400 | [diff] [blame] | 35 | |
| 36 | if (not kwargs['update_fields']): |
Sapan Bhatia | 475c597 | 2014-11-05 10:32:41 -0500 | [diff] [blame] | 37 | # Automatic dirtying |
| 38 | walk_inv_deps(update_dep, instance) |
| 39 | |
Sapan Bhatia | 640f2b7 | 2014-09-15 04:04:32 -0400 | [diff] [blame] | 40 | try: |
Scott Baker | c1f9cce | 2014-10-09 12:03:22 -0700 | [diff] [blame] | 41 | policy_handler = getattr(model_policies, policy_name, None) |
| 42 | if policy_handler is not None: |
| 43 | policy_handler.handle(instance) |
Sapan Bhatia | 640f2b7 | 2014-09-15 04:04:32 -0400 | [diff] [blame] | 44 | except: |
Tony Mack | a7dbd42 | 2015-01-05 22:48:11 -0500 | [diff] [blame] | 45 | logger.log_exc("Model Policy Error:") |
Sapan Bhatia | 475c597 | 2014-11-05 10:32:41 -0500 | [diff] [blame] | 46 | elif 'deleted' in kwargs['update_fields']: |
| 47 | walk_inv_deps(delete_if_inactive, instance) |
| 48 | |