Django缓存
介绍
由于Django构建的是动态网站,每次客户端请求都要严重依赖数据库,当程序访问量大时,耗时必然会更加明显,最简单解决方式是使用:缓存,缓存将一个某个views的返回值保存至内存或者memcache中,一段时间内再来访问时,则不去执行view中的操作,而是直接从内存、memcached 、Redis中将之前缓存的内容拿到,并返回。
6种缓存方式
- 开发调试缓存
- 内存缓存
- 文件缓存
- 数据库缓存
- Memcache缓存(使用python-memcached模块)
- Memcache缓存(使用pylibmc模块)
其中,最常使用的有文件缓存和Mencache缓存
6种缓存方式的settings配置
- 开发调试使用,实际上不执行任何操作
CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', # 缓存使用的引擎 'TIMEOUT': 300, # 缓存超时时间(默认300,None表示永不过期,0表示立即过期) 'OPTIONS': { 'MAX_ENTRIES': 300, # 最大缓存个数(默认300) 'CULL_FREQUENCY': 3, # 缓存到达最大个数之后,剔除缓存个数的比例,即:1/CULL_FREQUENCY(默认3) }, 'KEY_PREFIX': '', # 缓存key的前缀(默认空) 'VERSION': 1, # 缓存key的版本(默认1) 'KEY_FUNCTION' 函数名 # 生成key的函数(默认函数会生成为:前缀:版本:key) } } # 自定义key def default_key_func(key, key_prefix, version): """ Default function to generate keys. Constructs the key used by all other methods. By default it prepends the `key_prefix'. KEY_FUNCTION can be used to specify an alternate function with custom key making behavior. """ return '%s:%s:%s' % (key_prefix, version, key) def get_key_func(key_func): """ Function to decide which key function to use. Defaults to ``default_key_func``. """ if key_func is not None: if callable(key_func): return key_func else: return import_string(key_func) return default_key_func
- 内存缓存,将缓存保存至内存中的某处
CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', # 写在内存中的变量的唯一值 'TIMEOUT': 300, 'OPTIONS': { 'MAX_ENTRIES': 300, 'CULL_FREQUENCY': 3, } } }
- 文件缓存,将缓存保存至文件中(常用)
CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', # 指定缓存使用的引擎 'LOCATION': '/a/b/django_cache', # 指定缓存的路径 'TIMEOUT': 300, 'OPTIONS': { 'MAX_ENTRIES': 300, 'CULL_FREQUENCY': 3, } } }
- 数据库缓存,将数据保存到数据库中
CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', # 指定缓存使用的引擎 'LOCATION': 'cache_table', # 数据库表 'OPTIONS': { 'MAX_ENTRIES': 300, 'CULL_FREQUENCY': 3, } } } # 注:执行创建表命令 python manage.py createcachetable
- Memcache缓存,使用python-memcached模块连接memcache(常用)
- 注:Memcached是Django原生支持的缓存系统,要使用Memcached,需要下载Memcached的支持库python-memcached或pylibmc
CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', # 指定缓存使用的引擎 # 1 'LOCATION': '192.168.10.100:11211', # 指定Memcache缓存服务器的IP地址和端口 # 2 'LOCATION': 'unix:/tmp/memcached.sock', # 指定局域网内的主机名加socket套接字为Memcache缓存服务器 # 3 'LOCATION': [ '172.19.26.240:11211', '172.19.26.242:11211', ], # 指定一台或多台其他主机ip地址加端口为Memcache缓存服务器 'OPTIONS': { 'MAX_ENTRIES': 300, 'CULL_FREQUENCY': 3, } } }
- Memcache缓存,使用pylibmc模块连接memcache(常用)
- 注:Memcached是基于内存的缓存,数据存储在内存中,所以如果服务器死机的话,数据就会丢失,所以Memcached一般与其他缓存配合使用
CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache', # 指定缓存使用的引擎 # 1 'LOCATION': '192.168.10.100:11211', # 指定本机的11211端口为Memcache缓存服务器 # 2 'LOCATION': '/tmp/memcached.sock', # 指定某个路径为缓存目录 # 3 'LOCATION': [ '192.168.10.100:11211', '192.168.10.101:11211', '192.168.10.102:11211', ], # 分布式缓存,在多台服务器上运行Memcached进程,程序会把多台服务器当作一个单独的缓存,而不会在每台服务器上复制缓存值 'OPTIONS': { 'MAX_ENTRIES': 300, 'CULL_FREQUENCY': 3, }, } }
缓存应用
全站使用
使用Django的中间件,用户的请求通过中间件,经过一系列的认证等操作,如果请求的内容在缓存中存在,则使用FetchFromCacheMiddleware获取内容并返回给用户,再返回给用户之前,判断缓存中是否已经存在,不存在,则UpdateCacheMiddleware会将缓存保存至Django的缓存之中,以实现全站缓存
- 在 MIDDLEWARE_CLASSES 中加入 “update” 和 “fetch” 中间件
MIDDLEWARE_CLASSES = ( 'django.middleware.cache.UpdateCacheMiddleware', #响应HttpResponse中设置几个headers 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', #用来缓存通过GET和HEAD方法获取的状态码为200的响应 ) # “update” 必须配置在中间件的第一个 # “fetch” 必须配置在中间件的最后一个 # 加上缓存时间(s) CACHE_MIDDLEWARE_SECONDS = 10
单个视图使用
方法1: views.py 文件中设置 @cache_page(15)
from django.views.decorators.cache import cache_page import time from .models import Book @cache_page(15) #超时时间为15秒 def index(request): t=time.time() #获取当前时间 book_List=Book.objects.all() return render(request,"index.html",locals())
方法2: urls.py 文件中设置
from django.views.decorators.cache import cache_page
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/([0-9]{1,2})/$', cache_page(15)(views.index)),
]
局部视图使用
在 templates 文件夹的模板中设置(index.html)
{% load cache %}
{% cache 时间 缓存key %}
要缓存的内容
{% endcache %}
eg:
{% load cache %}
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>未缓存:{{ t }}</h3>
{% cache 2 'name' %}
<h3>已缓存:{{ t }}</h3>
{% endcache %}
</body>
</html>
本文来自博客园,仅供参考学习,如有不当之处还望不吝赐教,不胜感激!转载请注明原文链接:https://www.cnblogs.com/rong-z/articles/10168827.html
作者:cnblogs用户
浙公网安备 33010602011771号