2014-07-21 12:20:04 +00:00
|
|
|
from threading import currentThread
|
|
|
|
|
2014-09-16 14:35:00 +00:00
|
|
|
from django.core.cache.backends.dummy import DummyCache
|
2014-07-21 12:20:04 +00:00
|
|
|
from django.core.cache.backends.locmem import LocMemCache
|
|
|
|
|
|
|
|
|
|
|
|
_request_cache = {}
|
|
|
|
|
|
|
|
|
|
|
|
class RequestCache(LocMemCache):
|
|
|
|
""" LocMemCache is a threadsafe local memory cache """
|
|
|
|
def __init__(self):
|
|
|
|
name = 'locmemcache@%i' % hash(currentThread())
|
|
|
|
super(RequestCache, self).__init__(name, {})
|
|
|
|
|
|
|
|
|
|
|
|
def get_request_cache():
|
|
|
|
"""
|
|
|
|
Returns per-request cache when running RequestCacheMiddleware otherwise a
|
2014-09-16 14:35:00 +00:00
|
|
|
DummyCache instance (when running periodic tasks, tests or shell)
|
2014-07-21 12:20:04 +00:00
|
|
|
"""
|
|
|
|
try:
|
|
|
|
return _request_cache[currentThread()]
|
|
|
|
except KeyError:
|
2014-09-16 14:35:00 +00:00
|
|
|
return DummyCache('dummy', {})
|
2014-07-21 12:20:04 +00:00
|
|
|
|
|
|
|
|
|
|
|
class RequestCacheMiddleware(object):
|
|
|
|
def process_request(self, request):
|
2015-05-12 14:04:20 +00:00
|
|
|
cache = _request_cache.get(currentThread()) or RequestCache()
|
2014-07-21 12:20:04 +00:00
|
|
|
_request_cache[currentThread()] = cache
|
|
|
|
cache.clear()
|
|
|
|
|
|
|
|
def process_response(self, request, response):
|
|
|
|
if currentThread() in _request_cache:
|
|
|
|
_request_cache[currentThread()].clear()
|
|
|
|
return response
|