Django缓存原理

  1. 查看global_settings下的CACHES
    CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        }
    }
    1. 模仿底层实现获取某表中的所有数据
  2. 配置URL
    from django.conf.urls import url, include
    from django.contrib import admin
    
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^student/',include('student.urls'))
    ]
    
    
    #coding=utf-8
    
    from django.conf.urls import url
    import views
    
    urlpatterns=[
        url(r'^$',views.index_view)
    ]
    

     

  3. 创建视图

    # -*- coding: utf-8 -*-
    from __future__ import unicode_literals
    
    from django.http import HttpResponse, HttpResponseRedirect
    from django.shortcuts import render
    from .models import *
    
    from django.core.cache import caches
    #获取缓存对象
    cache = caches['default']
    print cache
    
    def cache_view(func):
        def _wrapper(request,*args,**kwargs):
            data = cache.get(request.path)
            if data:
                print '读取缓存数据'
                return HttpResponse(data)
            print '准备获取数据库数据'
            response = func(request,*args,**kwargs)
            print '进行缓存数据'
            cache.set(request.path,response.content)
            return response
        return _wrapper
    
    # Create your views here.
    
    @cache_view
    def index_view(request):
        stus = Stu.objects.all()
    
        return render(request,'index.html',{'stus':stus})
    
    
            
            

     

  4. 创建模板

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <ul>
        {% for stu in stus %}
            <li>{{ stu.sname }}</li>
        {% endfor %}
        </ul>
    
    </body>
    </html>

     

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值