日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪(fǎng)問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

Django项目--静态首页的数据缓存(设置、获取、更新)

發(fā)布時(shí)間:2023/12/20 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Django项目--静态首页的数据缓存(设置、获取、更新) 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

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

context = {'types': types,'goods_banners': goods_banners,'promotion_banners': promotion_banners}

注意,獲取用戶(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)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。