• Django + Redis实现页面缓存


    目的:把从数据库读出的数据存入的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())
  • 相关阅读:
    erlang遍历目录
    C/C++ makefile自动生成工具(comake2,autotools,linux),希望能为开源做点微薄的贡献!
    shell 文件操作
    互联网分享知识(一)
    分页查询,你真的懂吗?
    awk神器
    Unicode编码解码在线转换工具
    awk 留底
    软件开发真的这么简单吗?
    php性能优化
  • 原文地址:https://www.cnblogs.com/xcsg/p/10587097.html
Copyright © 2020-2023  润新知