Exemple #1
0
    def get(self, pk):
        # 查询商品id是否存在
        # try:
        #     sku = GoodsSKU.objects.get(pk=pk)
        # except GoodsSKU.DoesNotExist:
        #     return redirect(reverse('goods:index'))
        sku = db.session.query(GoodsSKU).filter(GoodsSKU.id == pk).first()
        if not sku:
            return redirect(url_for('goods.index'))

        # # 获取商品的分类信息
        # types = GoodsType.objects.all()
        types = db.session.query(GoodsType).all()
        # # 获取商品的评论
        # sku_orders = OrderGoods.objects.filter(sku=sku).exclude(comment='')
        sku_orders = db.session.query(OrderGoods).filter(
            OrderGoods._sku == sku)
        # # 获取新品信息
        # new_skus = GoodsSKU.objects.filter(type=sku.type).order_by('-create_time')[0:2]
        new_skus = db.session.query(GoodsSKU).filter(
            GoodsSKU._goods_type == sku._goods_type).order_by(desc(
                GoodsSKU.id)).all()[0:2]
        #
        # 获取同一商品spu的其他规格商品
        # same_spu_skus = GoodsSKU.objects.filter(goods=sku.goods).exclude(pk=pk)
        same_spu_skus = db.session.query(GoodsSKU).filter(
            GoodsSKU._goods == sku._goods, GoodsSKU.id != pk)
        #
        # 获取购物车商品数量
        cart_count = 0
        if request.user.is_authenticated:
            coon = get_redis_connection()
            cart_key = 'cart_%d' % request.user.id
            cart_count = coon.hlen(cart_key)
            # 添加用户的历史浏览记录
            coon = get_redis_connection()
            history_key = 'history_%d' % request.user.id
            # 移除之前的该商品id
            coon.lrem(history_key, 0, pk)
            # 把goods_id左侧插入redis列表
            coon.lpush(history_key, pk)
            # 取用户保存的最新5条信息
            coon.ltrim(history_key, 0, 4)
            coon.close()
        #
        context = {
            'sku': sku,
            'types': types,
            'sku_order': sku_orders,
            'new_skus': new_skus,
            'cart_count': cart_count,
            'same_spu_skus': same_spu_skus,
            'user': request.user
        }

        return render_template('detail.html', **context)
Exemple #2
0
    def get(self):
        # 获取个人信息
        # address = Address.objects.get_default_address(request.user)
        address = db.session.query(Address).filter(
            Address.is_default == True, Address._user == request.user).first()
        # 获取浏览记录
        conn = get_redis_connection()

        history_key = 'history_%d' % request.user.id

        sku_ids = conn.lrange(history_key, 0, 4)

        goods_list = []

        # 历史浏览记录排序
        for sku_id in sku_ids:
            # goods = GoodsSKU.objects.get(pk=sku_id)
            goods = db.session.query(GoodsSKU).filter(
                GoodsSKU.id == sku_id).first()
            goods_list.append(goods)

        context = {
            'page': 'user',
            'address': address,
            'goods_list': goods_list,
            'user': request.user
        }
        conn.close()
        return render_template('user_center_info.html', **context)
Exemple #3
0
    def get(self, ):
        user = request.user
        # 获取购物车商品信息
        coon = get_redis_connection()
        cart_key = 'cart_%d' % user.id

        cart_dict = coon.hgetall(cart_key)

        skus = []
        total_count = 0
        total_price = 0
        for sku_id, count in cart_dict.items():
            sku = GoodsSKU.query.filter(GoodsSKU.id == sku_id).first()
            print(sku)
            print(dir(sku))
            amount = sku.price * int(count)
            sku.amount = amount
            sku.count = int(count)
            skus.append(sku)
            total_count += int(count)
            total_price += amount

        context = {
            'total_count': total_count,
            'total_price': total_price,
            'skus': skus,
            'user': user
        }
        coon.close()
        return render_template('cart.html', **context)
Exemple #4
0
    def post(self):
        user = request.user
        if not user.is_authenticated:
            return jsonify({'res': 0, 'errmsg': '请先登录'})

        sku_id = request.form.get('sku_id')

        if not sku_id:
            return jsonify({'res': 1, 'errmsg': '无效的商品id'})

        # try:
        #     GoodsSKU.objects.get(pk=sku_id)
        # except GoodsSKU.DoesNotExist:
        #     return jsonify({'res': 2, 'errmsg': '商品不存在!'})
        sku = GoodsSKU.query.filter(GoodsSKU.id == sku_id).first()
        if not sku:
            return jsonify({'res': 3, 'errmsg': '商品不存在'})

        coon = get_redis_connection()

        cart_key = 'cart_%d' % user.id

        coon.hdel(cart_key, sku_id)

        values = coon.hvals(cart_key)

        values = [int(value.decode()) for value in values]

        total_count = sum(values)

        return jsonify({
            'res': 3,
            'message': '删除成功!',
            'total_count': total_count
        })
Exemple #5
0
    def post(self):

        user = request.user

        sku_ids = request.form.getlist('sku_ids')

        if not sku_ids:
            return redirect(url_for('cart.show'))

        coon = get_redis_connection()

        cart_key = 'cart_%d' % user.id

        skus = []
        total_count = 0
        total_price = 0

        for sku_id in sku_ids:
            sku = GoodsSKU.query.filter(GoodsSKU.id == sku_id).first()
            # 获取商品的数量
            conut = coon.hget(cart_key, sku_id)
            amount = sku.price * int(conut)
            sku.count = int(conut.decode())
            sku.amount = amount
            skus.append(sku)
            total_count += int(conut)
            total_price += amount

        # 运费
        transit_price = 10  # 假数据, 写死
        # 实付费
        total_pay = total_price + transit_price

        # addrs = Address.objects.filter(user=user)
        addrs = Address.query.filter(Address._user == user)

        sku_ids = ",".join(sku_ids)

        # 组织上下文
        context = {
            'skus': skus,
            'total_count': total_count,
            'total_price': transit_price,
            'transit_price': transit_price,
            'total_pay': total_pay,
            'addrs': addrs,
            'sku_ids': sku_ids,
            'user': request.user
        }

        return render_template('place_order.html', **context)
Exemple #6
0
    def get(self):
        # 获取商品种类
        # types = GoodsType.objects.all()
        types = db.session.query(GoodsType).all()
        # 获取首页轮播商品信息
        # GoodsBanner = IndexGoodsBanner.objects.all().order_by('index')
        GoodsBanner = db.session.query(IndexGoodsBanner).order_by(
            'index').all()
        # 获取首页活动信息
        # PromotionBanner = IndexPromotionBanner.objects.all().order_by('index')
        PromotionBanner = db.session.query(IndexPromotionBanner).order_by(
            'index').all()
        # 获取首页分类商品展示信息
        for type in types:
            # print(type)
            # type.img_banner = IndexTypeGoodsBanner.objects.filter(type=type, display_type=1).order_by('index')
            type.img_banner = db.session.query(IndexTypeGoodsBanner).filter(
                IndexTypeGoodsBanner._type == type,
                IndexTypeGoodsBanner.display_type == 1).order_by(
                    'index').all()

            # type.tltle_banner = IndexTypeGoodsBanner.objects.filter(type=type, display_type=0).order_by('index')
            type.tltle_banner = db.session.query(IndexTypeGoodsBanner).filter(
                IndexTypeGoodsBanner._type == type,
                IndexTypeGoodsBanner.display_type == 0).order_by(
                    'index').all()

        # 获取购物车商品数量
        cart_count = 0
        if request.user.is_authenticated:
            coon = get_redis_connection()
            cart_key = 'cart_%d' % request.user.id
            cart_count = coon.hlen(cart_key)
            coon.close()
        # 模板上下文
        context = {
            'types': types,
            'GoodsBanner': GoodsBanner,
            'PromotionBanner': PromotionBanner,
            'cart_count': cart_count,
            'user': request.user
        }

        return render_template('index.html', **context)
Exemple #7
0
    def post(self):
        user = request.user
        if not user.is_authenticated:
            return jsonify({'res': 0, 'errmsg': '请先登录'})

        sku_id = request.form.get('sku_id')
        count = request.form.get('count')

        if not all([sku_id, count]):
            return jsonify({'res': 1, 'errmsg': '数据不完整!'})

        try:
            count = int(count)
        except Exception:
            return jsonify({'res': 2, 'errmsg': '商品数目错误'})

        # try:
        #     sku = GoodsSKU.objects.get(pk=sku_id)
        # except GoodsSKU.DoesNotExist:
        #     return JsonResponse({'res': 3, 'errmsg': '商品不存在'})
        sku = GoodsSKU.query.filter(GoodsSKU.id == sku_id).first()
        if not sku:
            return jsonify({'res': 3, 'errmsg': '商品不存在'})

        coon = get_redis_connection()

        cart_key = 'cart_%d' % user.id

        if count > sku.stock:
            return jsonify({'res': 4, 'errmsg': '存库不足!'})

        # 设置hash中sku对应得值
        coon.hset(cart_key, sku_id, count)

        values = coon.hvals(cart_key)

        total_count = sum(values)

        return jsonify({
            'res': 5,
            'message': '更新成功!',
            'total_count': total_count
        })
Exemple #8
0
    def post(self):

        user = request.user

        sku_id = request.form.get('sku_id')
        count = request.form.get('count')

        if not all([sku_id, count]):
            return jsonify({'res': 1, 'errmsg': '数据不完整!'})

        try:
            count = int(count)
        except Exception:
            return jsonify({'res': 2, 'errmsg': '商品数目错误'})

        sku = GoodsSKU.query.filter(GoodsSKU.id == sku_id).first()
        if not sku:
            return jsonify({'res': 3, 'errmsg': '商品不存在'})

        coon = get_redis_connection()

        cart_key = 'cart_%d' % user.id

        cart_count = coon.hget(cart_key, sku_id)

        if count > sku.stock:
            return jsonify({'res': 4, 'errmsg': '存库不足!'})

        if cart_count:
            count += int(cart_count)

        # 设置hash中sku对应得值
        coon.hset(cart_key, sku_id, count)

        total_count = coon.hlen(cart_key)
        coon.close()

        return jsonify({
            'res': 5,
            'message': '添加成功!',
            'total_count': total_count
        })
Exemple #9
0
    def post(self):
        user = request.user

        if not user.is_authenticated:
            return jsonify({'res': 0, 'errmsg': '用户未登录!'})

        addr_id = request.form.get('addr_id')
        pay_method = request.form.get('pay_method')
        sku_ids = request.form.get('sku_ids')

        if not all([addr_id, pay_method, sku_ids]):
            return jsonify({'res': 1, 'errmsg': '参数不完整!'})

        # todo 校验支付方式
        if pay_method not in OrderInfo.PAY_METHODS.keys():
            return jsonify({'res': 2, 'errmsg': '非法的支付方式!'})

        # try:
        #     addr = Address.objects.get(pk=addr_id)
        # except Address.DoesNotExist:
        #     return jsonify({'res': 3, 'errmsg': '地址非法'})
        addr = Address.query.filter(Address.id == addr_id).first()
        if not addr:
            return jsonify({'res': 3, 'errmsg': '地址非法'})

        # TODO: 创建订单
        order_id = datetime.now().strftime('%Y%m%d%H%M%S') + str(user.id)
        # 运费
        transit_price = 10  # 假数据, 写死
        total_count = 0
        total_price = 0
        coon = get_redis_connection()
        cart_key = 'cart_%d' % user.id
        # 设置保存点
        save_id = db.session.begin_nested()

        # TODO  想订单信息表中添加一条记录
        order = OrderInfo(
            id=order_id,
            _user=user,
            _addr=addr,
            pay_method=pay_method,
            total_count=total_count,
            total_price=total_price,
            transit_price=transit_price
        )
        db.session.add(order)
        db.session.commit()
        # todo 用户的订单中有几个商品就要添加几条记录
        sku_ids = sku_ids.split(',')
        for sku_id in sku_ids:
            sku = db.session.query(GoodsSKU).filter(GoodsSKU.id == sku_id).with_for_update(read=True).first()
            if not sku:
                db.session.rollback()
                return jsonify({'res': 4, 'errmsg': '商品不存在!'})

            # 获取商品的数目
            count = coon.hget(cart_key, sku_id)

            # todo 判断商品的库存
            if int(count) > sku.stock:
                db.session.rollback()
                return jsonify({'res': 6, 'errmsg': '商品库存不足'})

            # todo to订单信息表中添加一条记录
            order = OrderGoods(
                _order=order,
                _sku=sku,
                count=int(count),
                price=sku.price,
            )
            db.session.add(order)
            db.session.commit()
            # todo 更新商品的库存销量和库存
            sku.stock -= int(count)
            sku.sales += int(count)
            db.session.add(sku)
            db.session.commit()

            # todo 累加计算商品的订单的总数量和总价格
            amount = sku.price * int(count)
            total_count += int(count)
            total_price += amount

        # todo 更新订单信息表中的商品的总数量和价格
        order.total_count = total_count
        order.total_price = total_price
        db.session.add(order)
        db.session.commit()
        # except Exception:
        #     db.session.rollback()
        #     return jsonify({'res': 7, 'errmsg': '下单失败!'})
        # 提交
        db.session.commit()
        # todo 清楚用户的购物车记录
        coon.hdel(cart_key, *sku_ids)

        return jsonify({'res': 5, 'message': '创建成功!'})
Exemple #10
0
    def get(self, type_id, page):
        # 获取种类信息
        # try:
        #     type = GoodsType.objects.get(pk=type_id)
        # except GoodsType.DoesNotExist:
        #     return redirect(reverse('goods:index'))
        type = db.session.query(GoodsType).filter(
            GoodsType.id == type_id).first()
        if not type:
            return redirect(url_for('goods.index'))

        # types = GoodsType.objects.all()
        types = db.session.query(GoodsType).all()

        # sort = request.GET.get('sort', 'default')
        sort = request.args.get('sort', 'default')
        query = db.session.query(GoodsSKU).filter(GoodsSKU._goods_type == type)
        if sort == 'price':
            # skus = GoodsSKU.objects.filter(type=type).order_by('price')
            skus = query.order_by(GoodsSKU.price)
        elif sort == 'hot':
            # skus = GoodsSKU.objects.filter(type=type).order_by('sales')
            skus = query.order_by(GoodsSKU.sales)
        else:
            # skus = GoodsSKU.objects.filter(type=type).order_by('-id')
            skus = query.order_by(desc(GoodsSKU.id))

        # paginator = Paginator(skus, 8)

        # 对页码进行容错处理
        try:
            page = int(page)
        except Exception:
            page = 1

        paginator = skus.paginate(page, 8, False)

        # if page > paginator.num_pages:
        #     page = paginator.num_pages
        if page > paginator.pages:
            page = paginator.pages

        skus_page = paginator.items

        # todo 页码的控制
        # 1 当总页数小于5页,页面上显示所有页面
        # 2 如果当前页是前三页  显示前5页的页码
        # 3 如果当前页是后三页码  显示后5页
        # 4 其他情况  显示当前页的前两页  当前页  当前页的后两页
        num_pages = paginator.pages
        if num_pages < 5:
            pages = range(1, num_pages + 1)
        elif page <= 3:
            pages = range(1, 6)
        elif num_pages - page <= 2:
            pages = range(num_pages - 4, num_pages + 1)
        else:
            pages = range(page - 2, page + 3)

        # 获取新品信息
        # new_skus = GoodsSKU.objects.filter(
        #     type=type).order_by('-create_time')[0:2]
        new_skus = GoodsSKU.query.filter(
            GoodsSKU._goods_type == type).order_by(desc(GoodsSKU.id))[0:2]

        # 获取购物车商品数量
        cart_count = 0
        if request.user.is_authenticated:
            coon = get_redis_connection('default')
            cart_key = 'cart_%d' % request.user.id
            cart_count = coon.hlen(cart_key)

        context = {
            'type': type,
            'types': types,
            'skus_page': skus_page,
            'new_skus': new_skus,
            'cart_count': cart_count,
            'sort': sort,
            'pages': pages,
            'paginator': paginator,
            'user': request.user
        }

        return render_template('list.html', **context)