settings
# 缓存 CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1/5", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } #默认 # SESSION_CACHE_ALIAS = "default"
首页设置缓存 redis数据库读写速度快
#首页 设置缓存 class Index(View): def get(self,request): #先获取缓存 cache_data = cache.get('index_page_data') #如果 没有缓存 if cache_data is None: #获取商品种类(所有对象) categorys = GoodsCategory.objects.all() #轮播信息 横幅 banners = IndexGoodsBanner.objects.all() #活动 促销 信息 promotions = IndexPromotionBanner.objects.all() # 商品列表 关联 for category in categorys: titles = IndexCategoryGoodsBanner.objects.filter(category=category,display_type=0) category.display_titles = titles #GoodsCategory类 category对象动态添加属性 dispiay_images = IndexCategoryGoodsBanner.objects.filter(category=category,display_type=1) category.display_images = dispiay_images #便于在 模板中调用 #上下文 context = { 'categorys':categorys,'banners':banners,'promotions':promotions } # 设置缓存key、内容、有效时间 cache.set('index_page_data',context,3600) #再次获取缓存 cache_data = cache.get('index_page_data')return render(request,'index.html',cache_data)
未完待续..............