首页 > 其他 > 详细

Django中的缓存

时间:2020-01-15 22:50:56      阅读:72      评论:0      收藏:0      [点我收藏+]

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

Django中的缓存

原文:https://www.cnblogs.com/huiyichanmian/p/12189187.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!