Django 缓存原理 与添加 redis 缓存

原理流程

#新建立 应用 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/,查看控制台

redis 缓存

# 修改settings.py 增加redis 缓存配置 ,127.0.0.1:6379/0 代表 redis 本地地址, 0 表示使用redis 0号库
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
    },
    'redis':{
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/0",
    }

}
CACHE_MIDDLEWARE_KEY_PREFIX = ''
CACHE_MIDDLEWARE_SECONDS = 600
CACHE_MIDDLEWARE_ALIAS = 'redis'

# 修改views.py  将 default 本地缓存改为 redis 缓存   cacheobj = caches['redis']

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

from django.http import HttpResponse
from django.shortcuts import render
from .models import *
from django.core.cache import caches

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

def cache_view(fund):
    def _wur(request,*args,**kwargs):
        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()
    print request.path
    print request.method

    return render(request,'index.html',{'postList':postList})


# 同样通过访问 http://127.0.0.1:8000/class/  已经把 /class/ 以及页面结果插入到 redis 库中,截图显示, treenms是用来查看 redis 中 value 的软件


posted @ 2020-12-21 16:57  lixinliang  阅读(235)  评论(0编辑  收藏  举报