zoukankan      html  css  js  c++  java
  • django-获取购物车商品数量-redis

    视图函数views.py中

    from django_redis import get_redis_connection  # 连接redis
    class 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_banners
                    type.title_banners = title_banners
    
                # 组织模板上下文
                context = {'types': types,
                           'goods_banners': goods_banners,
                           'promotion_banners': promotion_banners}
                # 设置缓存
                # key  value timeout
                cache.set('index_page_data', context, 3600)
    
            # 获取用户购物车中的商品数目
            # 获取用户登录信息
            user = request.user
            # 默认购物车数量为0
            cart_count = 0
            # 判断用户是否登录
            if user.is_authenticated():
                # 用户已登录
                conn = get_redis_connection('default')
                cart_key = 'cart_%d'%user.id
                cart_count = conn.hlen(cart_key)
            # 更新数据信息
            context.update(cart_count=cart_count)
            return render(request, 'index.html', context)

    模板文件index.html

     {# 购物车 #}
                <div class="guest_cart fr">
                    <a href="#" class="cart_name fl">我的购物车</a>
                    <div class="goods_count fl" id="show_count">{{ cart_count }}</div>
                </div>

     设置cart_key的数据

    hmset cart_2 1 3 2 5
  • 相关阅读:
    [原创]桓泽学音频编解码(13):AC3 位分配模块算法分析
    白话红黑树系列之一——初识红黑树
    白话红黑树系列之二——红黑树的构建
    数据驱动编程之表驱动法
    每周一算法之六——KMP字符串匹配算法
    HDOJ 1098 Ignatius's puzzle
    HDOJ 1097 A hard puzzle(循环问题)
    HDOJ 1019 Least Common Multiple(最小公倍数问题)
    辗转相除法_欧几里得算法_java的实现(求最大公约数)
    HDOJ 1020 Encoding
  • 原文地址:https://www.cnblogs.com/yifengs/p/11624485.html
Copyright © 2011-2022 走看看