Django如何使用redis作为缓存
已有Django项目,在其中设置以redis为缓存。
1、安装django-redis:
pipinstalldjango-redis
2、在settings里面配置cache设置:
CACHES={
"default":{
"BACKEND":"django_redis.cache.RedisCache",
"LOCATION":"redis://127.0.0.1:6379/1",#DB设为1
"TIMEOUT":None,#永久缓存,默认300秒
"OPTIONS":{
"CLIENT_CLASS":"django_redis.client.DefaultClient",
#"PASSWORD":"xxxxxx"#可能需要密码
}
}
}
3、设置好后可以在shell中测试一下:
(1)在终端中启动shell:
pythonmanage.pyshell
(2)在shell中输入,并查看结果,验证可读写Cache:
In[1]:fromdjango.core.cacheimportcache
In[2]:cache.set('mykey','haha,Igetit!')
Out[2]:True
In[3]:cache.get('mykey')
Out[3]:'haha,Igetit!'
(3)如果不能正常启动shell,可能是ipython版本过低,升级ipython即可:
pipinstallipython--upgrade
4、也可以新建test.py文件来验证,注意要导入settings并执行settings.configure():
fromdjango.confimportsettings
settings.configure()
fromdjango.core.cacheimportcache
cache.set('key1','goodday!')
cache.set('key2','otherday!')
print(cache.get('key1'))
print(cache.get('key2'))
能正常显示如下即可:
goodday!
otherday!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。