当前位置 : 主页 > 编程语言 > python >

Django如何使用redis作为缓存

来源:互联网 收集:自由互联 发布时间:2021-04-09
已有Django项目,在其中设置以redis为缓存。 1、 安装django-redis: pip install django-redis 2、 在settings里面配置cache设置: CACHES = { "default":{ "BACKEND":"django_redis.cache.RedisCache", "LOCATION":"redis://12

已有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",  # DB设为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 cache

In [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 settings
settings.configure()
from django.core.cache import cache
cache.set('key1','good day!')
cache.set('key2','other day!')
print(cache.get('key1'))
print(cache.get('key2'))

能正常显示如下即可:

good day!

other day!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。

网友评论