Django学习笔记(四十三):使用redis进行页面数据缓存和更新缓存数据

Django学习笔记(四十三):使用redis进行页面数据缓存和更新缓存数据

在开发过程中会遇到一些页面的数据是很长时间才进行更新的,不使用缓存的情况下,用户每次访问这些都需要先去数据库中获取这些数据,当访问量较大时,这样获取数据的方式就会降低页面的访问速度,影响效率,这时就可以使用redis将这些数据保存起来,通过判断是否生成过获取以及是否更新过数据来生成新的缓存数据

具体操作如下:

在settings.py里添加缓存设置

Django的缓存配置
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/9",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}

在对应的app中的views.py文件中写视图逻辑和缓存操作

from django.core.cache import cache
from goods.models import GoodsType, GoodsSKU, IndexGoodsBanner,IndexPromotionBanner,IndexTypeGoodsBanner
 
# Create your views here.
 
 
class IndexView(View):
    def get(self,request):
        '''显示首页'''
        # 尝试从缓存中获取数据
        context = cache.get('index_page_data')
 
        if context is None:
            print('设置缓存')
            # 缓存中没有数据
            # 获取商品的种类信息
            types = GoodsType.objects.all()
            print(types)
 
            # 获取首页轮播商品信息
            goods_banners = IndexGoodsBanner.objects.all().order_by('index')
            print(goods_banners)
 
            # 获取首页促销活动信息
            promotion_banners = IndexPromotionBanner.objects.all().order_by('index')
            print(promotion_banners)
 
            # 获取首页分类商品展示信息
            for type in types: # GoodsType
                # 获取type种类首页分类商品的图片展示信息
                image_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=1).order_by('index')
                print(image_banners)
                # 获取type种类首页分类商品的文字展示信息
                title_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=0).order_by('index')
                print(title_banners)
 
                # 动态给type增加属性,分别保存首页分类商品的图片展示信息和文字展示信息
                type.image_banners = image_banners
                type.title_banners = title_banners
            context = {'types': types,
                       'goods_banners': goods_banners,
                       'promotion_banners': promotion_banners}
 
            # 设置redis缓存
            #  key value timeout
            cache.set('index_page_data', context, 3600)
        return render(request, 'index.html', context)
      ```
在对应的app中的admin.py文件中添加BaseModelAdmin,作用是当数据发生改变时,将之前的缓存删除,然后再通过视图逻辑生成新的缓存
```python
from django.contrib import admin
from django.core.cache import cache
from goods.models import GoodsType,IndexPromotionBanner,IndexGoodsBanner,IndexTypeGoodsBanner
# Register your models here.
 
 
class BaseModelAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        '''新增或更新表中的数据时调用'''
        super().save_model(request, obj, form, change)
 
        # 发出任务,让celery worker重新生成首页静态页
        from celery_tasks.tasks import generate_static_index_html
        generate_static_index_html.delay()
 
        # 清除首页的缓存数据
        cache.delete('index_page_data')
 
    def delete_model(self, request, obj):
        '''删除表中的数据时调用'''
        super().delete_model(request, obj)
        # 发出任务,让celery worker重新生成首页静态页
        from celery_tasks.tasks import generate_static_index_html
        generate_static_index_html.delay()
 
        # 清除首页的缓存数据
        cache.delete('index_page_data')
 
 
class GoodsTypeAdmin(BaseModelAdmin):
    pass
 
 
class IndexGoodsBannerAdmin(BaseModelAdmin):
    pass
 
 
class IndexTypeGoodsBannerAdmin(BaseModelAdmin):
    pass
 
 
class IndexPromotionBannerAdmin(BaseModelAdmin):
    pass
 
 
admin.site.register(GoodsType, GoodsTypeAdmin)
admin.site.register(IndexGoodsBanner, IndexGoodsBannerAdmin)
admin.site.register(IndexTypeGoodsBanner, IndexTypeGoodsBannerAdmin)
admin.site.register(IndexPromotionBanner, IndexPromotionBannerAdmin)
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值