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())