/johnny/middleware.py

https://bitbucket.org/jmoiron/johnny-cache/ · Python · 64 lines · 31 code · 11 blank · 22 comment · 3 complexity · a2ea8771098837b865e92cc00dcd8c7e MD5 · raw file

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """Middleware classes for johnny cache."""
  4. from django.middleware import transaction as trans_middleware
  5. from django.db import transaction
  6. from johnny import cache, settings
  7. class QueryCacheMiddleware(object):
  8. """
  9. This middleware class monkey-patches django's ORM to maintain
  10. generational info on each table (model) and to automatically cache all
  11. querysets created via the ORM. This should be the first middleware
  12. in your middleware stack.
  13. """
  14. __state = {} # Alex Martelli's borg pattern
  15. def __init__(self):
  16. self.__dict__ = self.__state
  17. self.disabled = settings.DISABLE_QUERYSET_CACHE
  18. self.installed = getattr(self, 'installed', False)
  19. if not self.installed and not self.disabled:
  20. # when we install, lets refresh the blacklist, just in case johnny
  21. # was loaded before the setting exists somehow...
  22. cache.blacklist = settings.BLACKLIST
  23. self.query_cache_backend = cache.get_backend()
  24. self.query_cache_backend.patch()
  25. self.installed = True
  26. def unpatch(self):
  27. self.query_cache_backend.unpatch()
  28. self.query_cache_backend.flush_query_cache()
  29. self.installed = False
  30. class LocalStoreClearMiddleware(object):
  31. """
  32. This middleware clears the localstore cache in `johnny.cache.local`
  33. at the end of every request.
  34. """
  35. def process_exception(self, *args, **kwargs):
  36. cache.local.clear()
  37. raise
  38. def process_response(self, req, resp):
  39. cache.local.clear()
  40. return resp
  41. class CommittingTransactionMiddleware(trans_middleware.TransactionMiddleware):
  42. """
  43. A version of the built in TransactionMiddleware that always commits its
  44. transactions, even if they aren't dirty.
  45. """
  46. def process_response(self, request, response):
  47. if transaction.is_managed():
  48. try:
  49. transaction.commit()
  50. except:
  51. pass
  52. transaction.leave_transaction_management()
  53. return response