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 | fe9bc89 | 2014-09-15 03:48:11 -0400 | [diff] [blame] | 4 | from core.models import * |
Sapan Bhatia | 14356b7 | 2014-11-05 10:32:41 -0500 | [diff] [blame] | 5 | from dependency_walker import * |
Sapan Bhatia | fe9bc89 | 2014-09-15 03:48:11 -0400 | [diff] [blame] | 6 | import model_policies |
Sapan Bhatia | 0235e98 | 2014-09-03 13:14:40 -0400 | [diff] [blame] | 7 | |
Scott Baker | f342870 | 2014-10-21 15:05:29 -0700 | [diff] [blame] | 8 | modelPolicyEnabled = True |
| 9 | |
| 10 | def EnableModelPolicy(x): |
| 11 | global modelPolicyEnabled |
| 12 | modelPolicyEnabled = x |
| 13 | |
Sapan Bhatia | 14356b7 | 2014-11-05 10:32:41 -0500 | [diff] [blame] | 14 | def update_dep(d, o): |
Sapan Bhatia | 6d1241c | 2014-12-21 02:32:50 -0500 | [diff] [blame] | 15 | 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 Bhatia | 14356b7 | 2014-11-05 10:32:41 -0500 | [diff] [blame] | 21 | |
| 22 | def delete_if_inactive(d, o): |
| 23 | #print "Deleting %s (%s)"%(d,d.__class__.__name__) |
| 24 | d.delete() |
| 25 | return |
| 26 | |
Sapan Bhatia | 0235e98 | 2014-09-03 13:14:40 -0400 | [diff] [blame] | 27 | @receiver(post_save) |
Scott Baker | 2ba3485 | 2014-09-30 14:53:45 -0700 | [diff] [blame] | 28 | def post_save_handler(sender, instance, **kwargs): |
Scott Baker | f342870 | 2014-10-21 15:05:29 -0700 | [diff] [blame] | 29 | if not modelPolicyEnabled: |
| 30 | return |
Sapan Bhatia | 14356b7 | 2014-11-05 10:32:41 -0500 | [diff] [blame] | 31 | |
| 32 | sender_name = sender.__name__ |
| 33 | policy_name = 'model_policy_%s'%sender_name |
Sapan Bhatia | 9a3af23 | 2014-09-15 04:04:32 -0400 | [diff] [blame] | 34 | |
| 35 | if (not kwargs['update_fields']): |
Sapan Bhatia | 14356b7 | 2014-11-05 10:32:41 -0500 | [diff] [blame] | 36 | # Automatic dirtying |
| 37 | walk_inv_deps(update_dep, instance) |
| 38 | |
Sapan Bhatia | 9a3af23 | 2014-09-15 04:04:32 -0400 | [diff] [blame] | 39 | try: |
Scott Baker | 6021fa8 | 2014-10-09 12:03:22 -0700 | [diff] [blame] | 40 | policy_handler = getattr(model_policies, policy_name, None) |
| 41 | if policy_handler is not None: |
| 42 | policy_handler.handle(instance) |
Sapan Bhatia | 9a3af23 | 2014-09-15 04:04:32 -0400 | [diff] [blame] | 43 | except: |
| 44 | pass |
Sapan Bhatia | 14356b7 | 2014-11-05 10:32:41 -0500 | [diff] [blame] | 45 | elif 'deleted' in kwargs['update_fields']: |
| 46 | walk_inv_deps(delete_if_inactive, instance) |
| 47 | |