Django 缓存原理

原理流程

#新建立 应用 stu
#修改settings.py,增加缓存配置
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'stu'
]
#末尾增加(内存缓存):

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
    }
}
CACHE_MIDDLEWARE_KEY_PREFIX = ''
CACHE_MIDDLEWARE_SECONDS = 600
CACHE_MIDDLEWARE_ALIAS = 'default'


#修改urls.py
url(r'^class/',include('stu.urls'))

#修改 
stu/urls.py

#coding=utf-8

from django.conf.urls import url
import views
urlpatterns = [
    url(r'^$',views.index_view)
]

#增加models.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models

# Create your models here.

class Clazz(models.Model):
    cname = models.CharField(max_length=30,unique=True)

    def __unicode__(self):
        return u'Clazz:%s'%self.cname

#数据库新添两条数据
#修改 views.py

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.http import HttpResponse
from django.shortcuts import render
from .models import *
#导入 django 缓存包
from django.core.cache import caches

# Create your views here.
#获取缓存对象
cacheobj = caches['default']

def cache_view(fund):
    def _wur(request,*args,**kwargs):
        #path 为键,get 键后为内容 value
        data = cacheobj.get(request.path)
        if data:
            print '读取缓存数据'
            return HttpResponse(data)
        else:
            print '准备获取数据库数据'
            response = fund(request,*args,**kwargs)
            print '进行缓存数据'
            cacheobj.set(request.path,response.content)
            return response
    return _wur

#添加装饰器
@cache_view
def index_view(request):
    postList = Clazz.objects.all()
    return render(request,'index.html',{'postList':postList})

#模板文件  index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{% for i in postList %}
    {{ i.cname }}<br>
{% endfor %}

</body>
</html>

效果如下: 访问 http://127.0.0.1:8000/class/,查看控制台

Django 缓存原理

上一篇:Kali Linux的安装和使用


下一篇:【tools】为Jupyter Notebook添加目录