python3 之 天天生鮮 專案 快取cache
阿新 • • 發佈:2020-10-26
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)
未完待續..............