Django如何使⽤redis作为缓存
已有Django项⽬,在其中设置以redis为缓存。1、 安装django-redis:pip install django-redis
2、 在settings⾥⾯配置cache设置:
CACHES = { \"default\":{
\"BACKEND\":\"django_redis.cache.RedisCache\ \"LOCATION\":\"redis://127.0.0.1:6379/1\设为1 \"TIMEOUT\":None, # 永久缓存,默认300秒 \"OPTIONS\":{
\"CLIENT_CLASS\":\"django_redis.client.DefaultClient\ # \"PASSWORD\":\"xxxxxx\" # 可能需要密码 } }}
3、 设置好后可以在shell中测试⼀下:(1) 在终端中启动shell:python manage.py shell
(2) 在shell中输⼊,并查看结果,验证可读写Cache:
In [1]: from django.core.cache import cacheIn [2]: cache.set('mykey','haha,I get it!')Out[2]: True
In [3]: cache.get('mykey')Out[3]: 'haha,I get it!'
(3) 如果不能正常启动shell,可能是ipython版本过低,升级ipython即可:pip install ipython --upgrade
4、 也可以新建test.py⽂件来验证,注意要导⼊settings并执⾏settings.configure():
from django.conf import settingssettings.configure()
from django.core.cache import cachecache.set('key1','good day!')cache.set('key2','other day!')print(cache.get('key1'))print(cache.get('key2'))
能正常显⽰如下即可:
good day!other day!
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。