Django - 缓存

概述

  • 对于中等流量的网站来说,尽可能的减少开销是非常必要的。缓存数据就是为了保存那些需要很多计算资源的结果,这样就不必在下次请求消耗计算资源
  • Django 自带了一个健壮的缓存系统来保存动态页面,避免对于每次请求都重新计算
  • Django 提供了不同级别的缓存维度,可以缓存特定视图的输出,还可以仅仅缓存那些很难生产出来的部分,或者可以缓存整个网站

设置缓存

  • 通过设置决定数据缓存在哪里,是数据库中、文件系统中还是内存中

  • 通过 settions.py 文件中的 CACHE 配置来实现(在 settings.py 末尾添加以下代码)

    1. 缓存到内存

      1
      2
      3
      4
      5
      6
      7
      # 缓存到内存
      CACHES = {
      'default': {
      'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
      'TIMEOUT': 60,
      }
      }

      TIMEOUT:缓存的过期时间,以秒为单位,默认值是 300。如果设置成 None 表示永不会过期,如果设置成 0 会造成缓存立即失效。

    2. 缓存到 Redis

      • 官方文档
      • 默认使用 1 数据库
      • 安装:
        1
        pip install django-redis-cache
      • 配置:
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        # 缓存到Redis
        CACHES = {
        'default': {
        'BACKEND': 'redis_cache.cache.RedisCache',
        'LOCATION': 'localhost:6379',
        'TIMEOUT': 60,
        'OPTIONS': {
        'PASSWORD': '密码',
        }
        }
        }
      • 启动 Redis:
        • select 1:选择 1 数据库
        • keys *:查看所有的 key

    缓存应用途径

    1. 单个 view 缓存

      1
      2
      3
      4
      5
      6
      from django.views.decorators.cache import cache_page


      @cache_page(60 * 10)
      def index(request):
      return HttpResponse('Redis cache!')
    2. 模板片段缓存

      • 使用 cache 标签进行模板片段缓存

        1
        2
        def index1(request):
        return render(request, 'myApp/index.html')
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        {% load cache %}
        <!DOCTYPE html>
        <html lang="en">
        <head>
        <meta charset="UTF-8">
        <title>缓存</title>
        </head>
        <body>
        <h1>Redis cache!</h1>
        {% cache 120 cache_name %}
        120:缓存时间 <br>
        cache_name:缓存的名字
        {% endcache %}
        </body>
        </html>

        参数 1:缓存时间
        参数 2:缓存名称

    3. 底层的缓存 API

      1
      2
      3
      4
      5
      from django.core.cache import cache


      cache.set('cache_name', 'good', 120)
      cache.get('cache_name')
      • 设置cache.set(键,值,有效时间)
      • 获取cache.get(键)
      • 删除cache.delete(键)
      • 清空cache.clear()
------------- 本文结束 感谢您的阅读 -------------
正在加载今日诗词....