Django中的缓存

1、目的

使用缓存可以大大提高程序的响应速度,增强用户体验。

2、实现原理

将执行过的操作数据 存储下来,在一定时间内,再次获取数据的时候,直接从缓存中获取

比较理想的方案,缓存使用内存级缓存

①、客户端通过url访问服务端

②、服务端通过url来查找处理逻辑的视图函数

③、视图函数去缓存中查找数据

④、如果视图函数在缓存中查找到了数据,进行渲染,返回一个响应体给客户端

⑤、如果试图函数没有在缓存中查找到数据,则会通过models访问数据库,在数据库中查找数据

⑥、服务端将查找到的数据在缓存中存一份,同时进行渲染给客户端返回响应体

3、实现方式

(1)、数据库缓存

①创建缓存表

python manage.py createcachetable 自定义缓存表名称

②、在settings.py中设置缓存为数据库表

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        'LOCATION': '缓存表名称',
        'TIMEOUT': 60 * 5   # 缓存过期时间
            }
        }

(2)、redis缓存

①、安装Django中支持Redis缓存的库

pip install django-redis
pip install django-redis-cache

②、Redis缓存配置

CACHES = {
        'mysql_cache':{
            'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
            'LOCATION': 'mycache',
        },
        'redis_cache': {
            "BACKEND": "django_redis.cache.RedisCache",
            "LOCATION": "redis://127.0.0.1:6379/1",
            "OPTIONS": {
                "CLIENT_CLASS": "django_redis.client.DefaultClient",
            }
        }
    }

(3)、Memcached缓存

Memcached是一个基于内存的缓存框架(服务)

①、Windows版的Memcached

  安装:memcached -d install

  启动memcached服务:net start "Memcached Server"

  安装Python操作Memcached的绑定程序:pip install python-memcached

②、配置

CACHES = {
         'default': {
              'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
              'LOCATION': '127.0.0.1:11211',
        }
    }

(4)、文件

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
        'LOCATION': 'c:/foo/bar',
    }
}

4、程序层面操作缓存

(1)、装饰器

@cache_page

  timeout   有效时长

  cache  缓存到哪一个库中,针对于系统配置了多个缓存

@cache_page(timeout=60, cache='filecache')

  prefix  前缀

@cache_page(60, cache='redis_backend')
def jokes(request):

    sleep(5)

    return HttpResponse('JokeList')

(2)、原生cache

from django.core.cache import caches

def
news(request): cache = caches['redis_backend'] result = cache.get("news") if result: return HttpResponse(result) news_list = [] for i in range(10): news_list.append("最近贸易战又开始了%d" % i) sleep(5) data = { 'news_list': news_list } response = render(request, 'news.html', context=data) cache.set("news", response.content, timeout=60) return response

posted @ 2020-01-15 21:20  李大鹅  阅读(528)  评论(0编辑  收藏  举报