1. 程式人生 > >Django + Redis實現頁面緩存

Django + Redis實現頁面緩存

request cor bject 提高 lec oca color sel import

目的:把從數據庫讀出的數據存入的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實現頁面緩存