如何将Django与Redis结合实现高效缓存?

2026-05-25 00:101阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计353个文字,预计阅读时间需要2分钟。

如何将Django与Redis结合实现高效缓存?

已有Django项目,其中已设置以redis为缓存。安装django-redis:pip install django-redis。在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!

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

如何将Django与Redis结合实现高效缓存?

本文共计353个文字,预计阅读时间需要2分钟。

如何将Django与Redis结合实现高效缓存?

已有Django项目,其中已设置以redis为缓存。安装django-redis:pip install django-redis。在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!

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

如何将Django与Redis结合实现高效缓存?