Created
August 1, 2013 08:10
-
-
Save KunihikoKido/6129406 to your computer and use it in GitHub Desktop.
Django キャッシュサーバーへ、Python オブジェクトをキャッシュ
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
# -*- coding: utf-8 -*- | |
import hashlib | |
try: | |
import cPickle as pickle | |
except ImportError: | |
import pickle | |
class PythonObjectCache(object): | |
@classmethod | |
def to_python(cls, value): | |
return pickle.loads(str(value)) | |
@classmethod | |
def serialize(cls, obj): | |
return pickle.dumps(obj) | |
@classmethod | |
def set(cls, key, obj, timeout=0): | |
from django.core.cache import cache | |
serialized = cls.serialize(obj) | |
cache.set(key, serialized, timeout) | |
@classmethod | |
def get(cls, key, default=None): | |
from django.core.cache import cache | |
value = cache.get(key, default) | |
if value: | |
return cls.to_python(value) | |
return default |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment