- 内存缓存
- 数据库缓存
- 文件系统缓存
- 本地内存缓存
python manage.py shell < add.py
//add.py
from mysql_app.models import Mysql
tmp=['','1990-01-02',13312341234,'wuhan']
print('start')
for i in range(4000):
tmp[0] = 'tony'+str(i)
Mysql.objects.create(name=tmp[0], birthday=tmp[1], number=tmp[2], address=tmp[3])
i += 1
print('end')
//contact.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact</title>
</head>
<body>
<!--<form method="POST">
查找联系人:<input type="text" name="name" required="required"/>
<input type="submit" value="搜索"/>
</form>-->
{% if result %}
{% for var in result %}
<ul><li>{{var.name}} {{var.birthday}} {{var.number}} {{var.address}}</li></ul>
{% endfor %}
{% else %}
<!--{% if searchname %} -->
<!--<ul><li>未找到联系人:{{ searchname }}</li></ul>-->
<ul><li>联系人列表为空</li></ul>
<!--{% endif %}-->
{% endif %}
</body>
</html>
//views.py
from django.http import HttpResponse
from django.shortcuts import render
from django.template import loader,Context
from mysql_app.myform import ContactSearchForm
from mysql_app.models import Mysql
# Create your views here.
def contact(request):
t=loader.get_template("contact.html")
'''if request.method=="POST":
#实例化
form=ContactSearchForm(request.POST)
if form.is_valid():
temp=form.cleaned_data['name']
result=Mysql.objects.filter(name=temp)
return HttpResponse(t.render({'result':result,'searchname':temp}))
return HttpResponse(t.render({}))'''
result=Mysql.objects.all()
return HttpResponse(t.render({'result':result}))
没有利用缓存机制之前,所耗费的时间
1. 数据库缓存
python manage.py createcachetable [mysite_cache]
配置中间件
MIDDLEWARE = [
#"django.middleware.cache.UpdateCacheMiddleware",
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
#"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
#"django.middleware.cache.FetchFromCacheMiddleware",
]
2.视图级缓存
#视图级缓存
from django.views.decorators.cache import cache_page
@cache_page(60*30)
比较简单,在views.py里加入下面两行,关掉上面的数据库缓存
3. memcached缓存
1.4.5之后版本的memcached不能作为Windows服务来运行,必须使用Windows计划任务来运行它。要将memcached配置成当Windows启动时自动运行,在命令行运行下面的命令:
schtasks /create /sc onstart /tn memcached /tr "'D:\memcache\memcached-1.6.17\memcached.exe' -m 512"
通过下面的命令将memcached从Windows计划任务中移除:
schtasks /delete /tn memcached