Django使用Redis进行缓存

Django中都支持什么样的缓存: 文件缓存 、 数据库缓存
同时从多张表查询得到数据——SQL消耗的资源较多
多张表查询到的数据,临时存储在一个缓存表中进行操作,如:视图view、软件缓存、memcache缓存、
redis缓存【**熟悉并掌握】、more…

redis缓存的操作

  • 准备软件:redis数据库、django-redis模块

  • 开始使用:

  • 安装:pip install django-redis

  • 配置:settings.py

    CACHES = {
        "default": {
            "BACKEND": "django_redis.cache.RedisCache",
            "LOCATION": "redis://127.0.0.1:6379/1",
            "OPTIONS": {
               "CLIENT_CLASS": "django_redis.client.DefaultClient",
            }
        }
    }
    
  • 使用:
    (1)处理session[非必要,除非服务器空间有非常大的限制]:配置settings.py

    SESSION_ENGINE = "django.contrib.sessions.backends.cache"
    SESSION_CACHE_ALIAS = "default"
    

(2)作为程序中数据的缓存使用

  from django.core.cache import cache
  # 缓存中存储数据
  cache.set(key, value, timeout=..)
  # 缓存中读取数据
  v = cache.get(key)

一个关于缓存的django-redis项目案例(django–>day06中使用)

 # 导入需要的模块
 from django.core.cache import cache
 from . import models

 def cache_index(change=False):
     print('从redis中查询数据')
     a_list = cache.get('article_list')
     if a_list is None or change == True:
         print('去数据库中查找数据')
         a_list = models.Article.objects.all()
         print('将查询到的数据加载到缓存中')
         cache.set('article_list', a_list)
         return a_list

猜你喜欢

转载自blog.csdn.net/wu0che28/article/details/81987449