Created
November 26, 2013 00:26
-
-
Save jvanasco/7651368 to your computer and use it in GitHub Desktop.
memory_pickle backend for dogpile.cache
This file contains 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
""" | |
Memory Backend | |
-------------- | |
Provides a simple dictionary-based backend. | |
""" | |
from dogpile.cache.api import CacheBackend, NO_VALUE | |
try: | |
import cPickle as pickle | |
except ImportError: | |
import pickle | |
class MemoryPickleBackend(CacheBackend): | |
"""A backend that uses a plain dictionary , but serializes and deserializes | |
the objects. This is done to achieve parity with other cache backends | |
where returned values are not the same object. | |
There is no size management, and values which | |
are placed into the dictionary will remain | |
until explicitly removed. Note that | |
Dogpile's expiration of items is based on | |
timestamps and does not remove them from | |
the cache. | |
E.g.:: | |
from dogpile.cache import make_region | |
region = make_region().configure( | |
'dogpile.cache.memory' | |
) | |
To use a Python dictionary of your choosing, | |
it can be passed in with the ``cache_dict`` | |
argument:: | |
my_dictionary = {} | |
region = make_region().configure( | |
'dogpile.cache.memory', | |
arguments={ | |
"cache_dict":my_dictionary | |
} | |
) | |
""" | |
def __init__(self, arguments): | |
self._cache = arguments.pop("cache_dict", {}) | |
def get(self, key): | |
value = self._cache.get(key, NO_VALUE) | |
if value is not NO_VALUE: | |
value = pickle.loads( value ) | |
return value | |
def get_multi(self, keys): | |
values = [] | |
for key in keys : | |
values.append( self.get( key ) ) | |
return values | |
def set(self, key, value): | |
pickled = pickle.dumps( value ) | |
self._cache[key] = pickled | |
def set_multi(self, mapping): | |
for key,value in mapping.items(): | |
pickled = pickle.dumps( value ) | |
self._cache[key] = pickled | |
def delete(self, key): | |
self._cache.pop(key, None) | |
def delete_multi(self, keys): | |
for key in keys: | |
self._cache.pop(key, None) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment