首页 > 其他 > 详细

Django + Redis实现页面缓存

时间:2019-03-24 10:38:26      阅读:120      评论:0      收藏:0      [点我收藏+]

目的:把从数据库读出的数据存入的redis 中既提高了效率,又减少了对数据库的读写,提高用户体验。

例如:

1,同一页面局部缓存,局部动态

from django.views import View
from myapp.models import Student
#导入缓存库
from django.core.cache import cache
#导入页面缓存
from django.views.decorators.cache import cache_page
from django.utils.decorators import method_decorator

class Stulist(View):
    def get(self,request,id):
        #判断缓存内是否有数据
        result = cache.get("res",0)
        if result == 0:
            res = Student.objects.filter(id=id)
            cache.set("res",res,100)
            result =cache.get("res")
        # ret = Student.objects.all()
        # ret = [i.name for i in list(ret)]
        # random_name = random.sample(ret,3)
        #随机取一条 select * from student where id in(2,3) order by rand limit 1
       #取非当前数据外三条数据随机展示
        random_name = Student.objects.exclude(id__in=[id]).order_by("?")[0:3]
        return render(request,stulist.html,locals())

2,页面缓存

@cache_page(60)
def page_cache(request):
    res = Student.objects.all()

    return render(request,pagecache.html,locals())

@method_decorator(cache_page(60),name="get")
class PageCache(View):
   
    def get(self,request):
        res = Student.objects.all()

        return render(request,pagecache.html,locals())

 

Django + Redis实现页面缓存

原文:https://www.cnblogs.com/xcsg/p/10587097.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!