缓存
我们的缓存有三个粒度级别在django里面
第一级别是全站的缓存,一旦涉及到全站就会联想到中间件,没错,就是在中间件里面加上配置.

我们只需要在setting文件里面把中间件配置好,就可以正常写view视图和HTML前端模板了,这样就达到了全站缓存的效果,我们的CACHE_MIDDLEWARE_SECONDS=5这个参数是缓存时间的设置,以秒为单位.
示例代码如下:
url路由配置:
url(r'^index/', views.index),
view视图函数:
def index(request): t = time.time() return render(request, "index.html", locals())
HTML前端模板:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Title</title> </head> <body> <h3>缓存时间:{{ t }}</h3> <h2>当前时间:{{ t }}</h2> </body> </html>
还有就是视图级别的缓存,给某一个视图来设置缓存,只有该视图所对应的HTML才会有缓存,其余并不会有
那么,setting文件里面就不需要加上中间件参数配置了,恢复到初始状态即可
还是以上面例子来做更改:
setting恢复初始状态,然后url路由不变
from django.views.decorators.cache import cache_page 导入缓存模块 @cache_page(9) # 这里是基于视图的缓存,在这里使用装饰器把缓存设置好之后就不需要再模板语言里面进行设置了 def index(request): t = time.time() return render(request, "index.html", locals())
再就是HTML前端模板级别的局部缓存,也就是在我们的HTML模板里面把部分标签进行缓存,
中间件部分就恢复到初始状态,然后url路由不变,
视图:
def index(request): t = time.time() return render(request, "index.html", locals())
HTML前端模板:
{% load cache %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
</head>
<body>
{% cache 10 "time_cache" %}
{# 这里被cache包裹住的部分就是模板语言里面的局部缓存,把要缓存的部分裹起来,然后在cache后面的10就是缓存时间,以秒为单位#}
<h3>缓存时间:{{ t }}</h3>
{% endcache %}
{#我们实现全站缓存,使用中间件的时候,就不需要在模板语言里面进行设置了#}
<h2>当前时间:{{ t }}</h2>
</body>
</html>
后期会有memcache补充.....

浙公网安备 33010602011771号