对于一些计算量比较大值,可能希望缓存在内存里边。。。
先安装
#sudo aptitude install redis-server
#pip install django-redis
django的setting.py里面
"""
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
"""
CACHES = {
'default':{
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': '127.0.0.1:6379',
'OPTIONS': {
'CLIENT_CLASS': 'redis_cache.client.DefaultClient',
},
},
}
REDIS_TIMEOUT = 7 * 24 * 60 * 60
CUBES_REDIS_TIMEOUT = 60 * 60
NEVER_REDIS_TIMEOUT = 365 * 24 * 60 * 60
然后,写个redis_cache.py
#/usr/bin/env python
# encoding:utf-8
import json
from django.conf import settings
from django.core.cache import cache
def read_from_cache(self, user_name):
key = 'user_id_of_'+ user_name
value = cache.get(key)
if value == None:
data = None
else:
data = json.loads(value)
return data
def write_to_cache(self, user_name):
key = 'user_id_of_' + user_name
cache.set(key, json.dumps(user_name), settings.NEVER_REDIS_TIMEOUT)
好了,然后,在需要的地发调用read or write 需要cache的key,value就可以了