middleware.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. from __future__ import unicode_literals
  2. from datetime import timedelta
  3. import random
  4. import threading
  5. import uuid
  6. from django.conf import settings
  7. from django.db.models.signals import post_delete, post_save
  8. from django.utils import timezone
  9. from .constants import OBJECTCHANGE_ACTION_CREATE, OBJECTCHANGE_ACTION_DELETE, OBJECTCHANGE_ACTION_UPDATE
  10. from .models import ObjectChange
  11. _thread_locals = threading.local()
  12. def mark_object_changed(instance, **kwargs):
  13. """
  14. Mark an object as having been created, saved, or updated. At the end of the request, this change will be recorded.
  15. We have to wait until the *end* of the request to the serialize the object, because related fields like tags and
  16. custom fields have not yet been updated when the post_save signal is emitted.
  17. """
  18. if not hasattr(instance, 'log_change'):
  19. return
  20. # Determine what action is being performed. The post_save signal sends a `created` boolean, whereas post_delete
  21. # does not.
  22. if 'created' in kwargs:
  23. action = OBJECTCHANGE_ACTION_CREATE if kwargs['created'] else OBJECTCHANGE_ACTION_UPDATE
  24. else:
  25. action = OBJECTCHANGE_ACTION_DELETE
  26. _thread_locals.changed_objects.append((instance, action))
  27. class ChangeLoggingMiddleware(object):
  28. def __init__(self, get_response):
  29. self.get_response = get_response
  30. def __call__(self, request):
  31. # Initialize the list of changed objects
  32. _thread_locals.changed_objects = []
  33. # Assign a random unique ID to the request. This will be used to associate multiple object changes made during
  34. # the same request.
  35. request.id = uuid.uuid4()
  36. # Connect mark_object_changed to the post_save and post_delete receivers
  37. post_save.connect(mark_object_changed, dispatch_uid='record_object_saved')
  38. post_delete.connect(mark_object_changed, dispatch_uid='record_object_deleted')
  39. # Process the request
  40. response = self.get_response(request)
  41. # Record object changes
  42. for obj, action in _thread_locals.changed_objects:
  43. if obj.pk:
  44. obj.log_change(request.user, request.id, action)
  45. # Housekeeping: 1% chance of clearing out expired ObjectChanges
  46. if _thread_locals.changed_objects and settings.CHANGELOG_RETENTION and random.randint(1, 100) == 1:
  47. cutoff = timezone.now() - timedelta(days=settings.CHANGELOG_RETENTION)
  48. purged_count, _ = ObjectChange.objects.filter(
  49. time__lt=cutoff
  50. ).delete()
  51. return response