Django项目--静态首页的数据缓存(设置、获取、更新)
0 前言
將處理計(jì)算的結(jié)果先臨時(shí)保存起來(lái),下次使用的時(shí)候可以先直接使用,如果沒(méi)有這個(gè)備份的數(shù)據(jù),重新進(jìn)行計(jì)算處理。
將緩存數(shù)據(jù)保存在內(nèi)存中 (本項(xiàng)目中保存在redis中)
cache注意事項(xiàng):
1)如果修改了數(shù)據(jù)庫(kù)的數(shù)據(jù),直接刪除緩存;
2)緩存要設(shè)置有效期。
相關(guān)django文檔:Django緩存
1.設(shè)置緩存
# http://127.0.0.1:8000 class IndexView(View):'''首頁(yè)'''def get(self, request):'''顯示首頁(yè)'''# 嘗試從緩存中獲取數(shù)據(jù)context = cache.get('index_page_data')if context is None:print('設(shè)置緩存')# 緩存中沒(méi)有數(shù)據(jù)# 獲取商品的種類(lèi)信息types = GoodsType.objects.all()# 獲取首頁(yè)輪播商品信息goods_banners = IndexGoodsBanner.objects.all().order_by('index')# 獲取首頁(yè)促銷(xiāo)活動(dòng)信息promotion_banners = IndexPromotionBanner.objects.all().order_by('index')# 獲取首頁(yè)分類(lèi)商品展示信息for type in types: # GoodsType# 獲取type種類(lèi)首頁(yè)分類(lèi)商品的圖片展示信息image_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=1).order_by('index')# 獲取type種類(lèi)首頁(yè)分類(lèi)商品的文字展示信息title_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=0).order_by('index')# 動(dòng)態(tài)給type增加屬性,分別保存首頁(yè)分類(lèi)商品的圖片展示信息和文字展示信息type.image_banners = image_bannerstype.title_banners = title_bannerscontext = {'types': types,'goods_banners': goods_banners,'promotion_banners': promotion_banners}# 設(shè)置緩存# key value timeoutcache.set('index_page_data', context, 3600)# 獲取用戶(hù)購(gòu)物車(chē)中商品的數(shù)目user = request.usercart_count = 0if user.is_authenticated():# 用戶(hù)已登錄conn = get_redis_connection('default')cart_key = 'cart_%d'%user.idcart_count = conn.hlen(cart_key)# 組織模板上下文,context中存在則更新,不存在則添加context.update(cart_count=cart_count)# 使用模板return render(request, 'index.html', context)在商品good應(yīng)用的view視圖中,設(shè)置緩存。
緩存的鍵:index_page_data
緩存的值:context
注意,獲取用戶(hù)購(gòu)物車(chē)中商品的數(shù)目cart_count并未加入緩存,因?yàn)橘?gòu)物車(chē)模塊只有用戶(hù)登錄之后才會(huì)有!
2.獲取緩存
settings.py中設(shè)置緩存
# Django的緩存配置 CACHES = {"default": {"BACKEND": "django_redis.cache.RedisCache","LOCATION": "redis://172.16.179.142:6379/9","OPTIONS": {"CLIENT_CLASS": "django_redis.client.DefaultClient",}} }Redis數(shù)據(jù)庫(kù)中查詢(xún)緩存
3.更新緩存
如果管理員在后臺(tái)對(duì)首頁(yè)的商品數(shù)據(jù)進(jìn)行更改,則需要在調(diào)用save_model和delete.model的同時(shí),更新緩存。
總結(jié)
以上是生活随笔為你收集整理的Django项目--静态首页的数据缓存(设置、获取、更新)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 正则表达式语法大全
- 下一篇: 毕业论文Word排版专题