Created
January 15, 2012 16:51
-
-
Save mattrobenolt/1616410 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.core.cache import cache | |
class CacheTransactionMiddleware(object): | |
"""Queues up set and delete calls so they can be executed in bulk. | |
This middleware queues up cache.set and cache.delete calls into | |
one big set_many or delete_many call at the end of the request | |
life cycle. This can drastically improve latency especially when | |
many many calls are executed in loops. | |
""" | |
def process_request(self, request): | |
if not hasattr(request, 'cache'): | |
request.cache = _CacheQueue() | |
def process_response(self, request, response): | |
request.cache.execute() | |
class _CacheQueue(object): | |
def __init__(self): | |
self.set_queue = {} | |
self.delete_queue = {} | |
def set(self, key, value, overwrite=False): | |
if not overwrite and key in self.set_queue: | |
raise ValueError("'%s' already queued to be set, and overwrite is set to False") | |
self.set_queue[key] = value | |
def delete(self, key, value, overwrite=False): | |
if not overwrite and key in self.delete_queue: | |
raise ValueError("'%s' already queued to be deleted, and overwrite is set to False") | |
self.delete_queue[key] = value | |
def execute(self): | |
if self.set_queue: | |
cache.set_many(self.set_queue) | |
self.set_queue = {} | |
if self.delete_queue: | |
cache.delete_many(self.delete_queue) | |
self.delete_queue = {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment