900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > Django项目--静态首页的数据缓存(设置 获取 更新)

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

时间:2019-07-17 09:59:47

相关推荐

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

0 前言

将处理计算的结果先临时保存起来,下次使用的时候可以先直接使用,如果没有这个备份的数据,重新进行计算处理。

将缓存数据保存在内存中 (本项目中保存在redis中)

cache注意事项:

1)如果修改了数据库的数据,直接删除缓存;

2)缓存要设置有效期。

相关django文档:Django缓存

1.设置缓存

# http://127.0.0.1:8000class IndexView(View):'''首页'''def get(self, request):'''显示首页'''# 尝试从缓存中获取数据context = cache.get('index_page_data')if context is None:print('设置缓存')# 缓存中没有数据# 获取商品的种类信息types = GoodsType.objects.all()# 获取首页轮播商品信息goods_banners = IndexGoodsBanner.objects.all().order_by('index')# 获取首页促销活动信息promotion_banners = IndexPromotionBanner.objects.all().order_by('index')# 获取首页分类商品展示信息for type in types: # GoodsType# 获取type种类首页分类商品的图片展示信息image_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=1).order_by('index')# 获取type种类首页分类商品的文字展示信息title_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=0).order_by('index')# 动态给type增加属性,分别保存首页分类商品的图片展示信息和文字展示信息type.image_banners = image_bannerstype.title_banners = title_bannerscontext = {'types': types,'goods_banners': goods_banners,'promotion_banners': promotion_banners}# 设置缓存# key value timeoutcache.set('index_page_data', context, 3600)# 获取用户购物车中商品的数目user = request.usercart_count = 0if user.is_authenticated():# 用户已登录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应用的view视图中,设置缓存。

缓存的键:index_page_data

缓存的值:context

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

注意,获取用户购物车中商品的数目cart_count并未加入缓存,因为购物车模块只有用户登录之后才会有!

2.获取缓存

settings.py中设置缓存

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

Redis数据库中查询缓存

3.更新缓存

如果管理员在后台对首页的商品数据进行更改,则需要在调用save_model和delete.model的同时,更新缓存。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。