PageRenderTime 25ms CodeModel.GetById 17ms app.highlight 5ms RepoModel.GetById 1ms app.codeStats 0ms

/johnny/middleware.py

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