Beispiel #1
0
    def post(self, request):
        # 1. 接收参数
        user_id = request.session.get("ID")
        sku_id = request.POST.get("sku_id")
        count = request.POST.get("count")

        # a.判断为整数
        try:
            sku_id = int(sku_id)
            count = int(count)
        except:
            return JsonResponse(json_msg(1, "参数错误!"))
        # b.要在数据库中存在商品
        try:
            goods_sku = GoodsSKU.objects.get(pk=sku_id)
        except GoodsSKU.DoesNotExist:
            return JsonResponse(json_msg(2, "商品不存在!"))

        # 判断库存
        if goods_sku.stock < count:
            return JsonResponse(json_msg(3, "库存不足!"))

        # 2. 操作数据
        # 创建连接
        r = get_redis_connection()
        # 处理购物车的 key
        cart_key = get_cart_key(user_id)

        # 添加
        # 获取购物车中已经存在的数量 加 上 需要添加 与 库存进行比较
        old_count = r.hget(cart_key, sku_id)  # 二进制
        if old_count is None:
            old_count = 0
        else:
            old_count = int(old_count)

        if goods_sku.stock < old_count + count:
            return JsonResponse(json_msg(3, "库存不足!"))

        # 将商品添加到购物车
        # r.hset(cart_key,sku_id,old_count + count)
        # ctrl + shift + u
        rs_count = r.hincrby(cart_key, sku_id, count)
        if rs_count <= 0:
            # 删除field
            r.hdel(cart_key, sku_id)

        # 获取购物车中的总数量
        cart_count = get_cart_count(request)

        # 3. 合成响应
        return JsonResponse(json_msg(0, "添加购物车成功", data=cart_count))
Beispiel #2
0
    def post(self, request):
        # 接收数据
        data = request.POST.dict()  # 强制转换成字典

        # 字典保存用户
        data['user_id'] = request.session.get("ID")

        # 表单验证数据合法性
        form = AddressModelForm(data)
        if form.is_valid():
            form.instance.user_id = SpUser.objects.get(pk=data['user_id'])
            form.save()
            # return redirect('user:收货地址列表')
            return JsonResponse(json_msg(0, '添加成功'))
        else:
            context = {'form': form}
            # return render(request, 'user/address.html', context=context)
            return JsonResponse(json_msg(1, "添加失败", data=form.errors))
Beispiel #3
0
    def post(self, request):
        # 接受参数
        user_id = request.session.get('ID')
        sku_id = request.POST.get('sku_id')
        count = request.POST.get('count')
        # 判断id和数量是否为整数
        try:
            sku_id = int(sku_id)
            count = int(count)
        except:
            return JsonResponse(json_msg(1, '参数错误'))
        # 要在数据库中存在商品
        try:
            shop_sku = ShopSKU.objects.get(pk=sku_id)
        except ShopSKU.DoesNotExist:

            return JsonResponse(json_msg(2, '商品不存在'))
        #         判断库存
        if shop_sku.stock < count:
            return JsonResponse(json_msg(3, '库存不足'))
        #         操作数据库
        r = get_redis_connection()
        #         处理key
        cart_key = f'cart_{user_id}'
        # 获取购物车中的数量加上需要的数量与库存作比较
        # 是二进制
        old_count = r.hget(cart_key, sku_id)
        if old_count is None:
            old_count = 0
        else:
            old_count = int(old_count)
        if shop_sku.stock < old_count + count:
            return JsonResponse(json_msg(3, '库存不足'))
        #         添加购物车
        r.hincrby(cart_key, sku_id, count)
        # 获取购物车中的总数量
        cart_count = get_cart_count(request)

        return JsonResponse(json_msg(0, '添加购物车成功', data=cart_count))
Beispiel #4
0
 def verify_login(request, *args, **kwargs):
     # 验证session中是否有登录标识
     if request.session.get("ID") is None:
         referer = request.META.get('HTTP_REFERER', None)
         if referer:
             request.session['referer'] = referer
         if request.is_ajax():
             return JsonResponse(json_msg(1, '未登录'))
         else:
             # 跳转到登录
             return redirect('user:登录')
     else:
         # 调用原函数
         return func(request, *args, **kwargs)
Beispiel #5
0
    def verify_login(request, *args, **kwargs):
        # 判断是否登录
        # 根据session里面的id 判断
        if request.session.get('ID') is None:
            # 将上个请求地址保存到session
            referer = request.META.get('HTTP_REFERER', None)
            if referer:
                request.session['referer'] = referer

                # 判断 是否为ajax请求
            if request.is_ajax():
                return JsonResponse(json_msg(1, '未登录'))

            # 跳转到登录
            return redirect('用户:用户登录')
        else:
            # 调用原函数
            return func(request, *args, **kwargs)
Beispiel #6
0
    def post(self,reqeust):
        """
             保存订单数据
             1. 订单基本信息表 和 订单商品表
         """
        # 1. 接收参数
        transport_id = request.POST.get('transport')
        sku_ids = request.POST.getlist('sku_ids')
        address_id = request.POST.get('address')

        # 接收用户的id
        user_id = request.session.get("ID")
        user = User.objects.get(pk=user_id)

        # 验证数据的合法性
        try:
            transport_id = int(transport_id)
            address_id = int(address_id)
            sku_ids = [int(i) for i in sku_ids]
        except:
            return JsonResponse(json_msg(2, "参数错误"))

        # 验证收货地址和运输方式存在
        try:
            address = UserAddress.objects.get(pk=address_id)
        except UserAddress.DoesNotExist:
            return JsonResponse(json_msg(3, "收货地址不存在!"))

        try:
            transport = Transport.objects.get(pk=transport_id)
        except Transport.DoesNotExist:
            return JsonResponse(json_msg(4, "运输方式不存在!"))

        # 2. 操作数据

        # >>>1 . 操作订单基本信息表
        order_sn = "{}{}{}".format(datetime.now().strftime("%Y%m%d%H%M%S"), user_id, random.randrange(10000, 99999))
        address_info = "{}{}{}-{}".format(address.hcity, address.hproper, address.harea, address.brief)
        order = Order.objects.create(
            user=user,
            order_sn=order_sn,
            transport_price=transport.price,
            transport=transport.name,
            username=address.username,
            phone=address.phone,
            address=address_info
        )

        # >>>2. 操作订单商品表
        # 操作redis
        r = get_redis_connection()
        cart_key = get_cart_key(user_id)

        # 准备个变量保存商品总金额
        goods_total_price = 0
        for sku_id in sku_ids:

            # 获取商品对象
            try:
                goods_sku = GoodsskuClassModel.objects.get(pk=sku_id, is_delete=False, is_on_sale=True)
            except GoodsskuClassModel.DoesNotExist:
                return JsonResponse(json_msg(5, "商品不存在"))

            # 获取购物车中商品的数量
            # redis 基于内存的存储,有可能数据会丢失
            try:
                count = r.hget(cart_key, sku_id)
                count = int(count)
            except:
                return JsonResponse(json_msg(6, "购物车中数量不存在!"))

            # 判断库存是否足够
            if goods_sku.stock < count:
                return JsonResponse(json_msg(7, "库存不足!"))

            # 保存订单商品表
            order_goods = OrderGoods.objects.create(
                order=order,
                goods_sku=goods_sku,
                price=goods_sku.price,
                count=count
            )

            # 添加商品总金额
            goods_total_price += goods_sku.price * count

            # 扣除库存, 销量增加
            goods_sku.stock -= count
            goods_sku.sale_num += count
            goods_sku.save()

        # 3. 反过头来操作订单基本信息表 商品总金额 和 订单总金额
        # 订单总金额
        order_price = goods_total_price + transport.price
        order.goods_total_price = goods_total_price
        order.order_price = order_price
        order.save()

        # 4. 清空redis中的购物车数据(对应sku_id)
        r.hdel(cart_key, *sku_ids)

        # 3. 合成响应
        return JsonResponse(json_msg(0, "创建订单成功!", data=order_sn))
Beispiel #7
0
    def post(self, request):

        # 参数接收
        payment = request.POST.get('payment')
        order_sn = request.POST.get('order_sn')
        user_id = request.session.get('ID')

        # 判断参数合法性
        try:
            payment = int(payment)
        except:
            return JsonResponse(json_msg(1, "参数错误"))

        # 支付方式存在
        try:
            payment = Payment.objects.get(pk=payment)
        except Payment.DoesNotExist:
            return JsonResponse(json_msg(2, "支付方式不存在"))

        # 判断该订单是否是自己的, 并且是一个未支付的订单
        try:
            order = Order.objects.get(user_id=user_id,
                                      order_sn=order_sn,
                                      order_status=0)
        except Order.DoesNotExist:
            return JsonResponse(json_msg(3, "订单不满足要求"))

        # 判断 用户是否需要使用支付宝支付
        if payment.name == "支付宝":
            # 构造支付请求
            app_private_key_string = open(
                os.path.join(settings.BASE_DIR,
                             "alipay/user_private_key.txt")).read()
            alipay_public_key_string = open(
                os.path.join(settings.BASE_DIR,
                             'alipay/alipay_public_key.txt')).read()

            # 初始化对象
            alipay = AliPay(
                appid="2016092400582019",
                app_notify_url=None,  # 默认回调url
                app_private_key_string=app_private_key_string,
                # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,
                alipay_public_key_string=alipay_public_key_string,
                sign_type="RSA2",  # RSA 或者 RSA2
                debug=True  # 默认False
            )

            # 构造请求地址
            order_string = alipay.api_alipay_trade_wap_pay(
                out_trade_no=order.order_sn,  # 订单编号
                total_amount=str(order.order_price),  # 订单金额
                subject="张爸爸超市订单支付",  # 订单描述
                return_url="http://127.0.0.1:8008/order/pay/",  # 同步通知地址
                notify_url=None  # 异步通知地址 重要
            )

            # 拼接地址
            url = "https://openapi.alipaydev.com/gateway.do?" + order_string

            # 通过json返回请求地址
            return JsonResponse(json_msg(0, "创建支付地址成功", data=url))
        else:
            return JsonResponse(json_msg(4, "该支付方式暂不支支持"))
Beispiel #8
0
    def post(self, request):
        """
        保存订单数据
        1. 订单基本信息表 和 订单商品表

        """
        # 1. 接收参数
        transport_id = request.POST.get("transport")
        address_id = request.POST.get("address")
        sku_ids = request.POST.getlist("sku_ids")

        user_id = request.session.get("ID")
        user = SpUser.objects.get(pk=user_id)
        # 验证数据合法性
        try:
            transport_id = int(transport_id)
            address_id = int(address_id)
            sku_ids = [int(i) for i in sku_ids]
        except:
            return JsonResponse(json_msg(2, "数据不合法"))

        # 验证收货地址和运输方式存在
        try:
            address = UserAddress.objects.get(pk=address_id)
        except UserAddress.DoesNotExist:
            return JsonResponse(json_msg(3, "收货地址不存在"))
        try:
            transport = Transport.objects.get(pk=transport_id)
        except Transport.DoesNotExist:
            return JsonResponse(json_msg(4, "运输方式不存在"))

        # 2. 操作数据
        # 创建保存点
        sid = transaction.savepoint()

        #  操作订单基本信息表
        order_sn = "{}{}{}".format(datetime.now().strftime("%Y%m%d%H%M%S"),
                                   user_id, random.randrange(10000, 99999))
        address_info = "{}{}{}-{}".format(address.hcity, address.hproper,
                                          address.harea, address.brief)
        try:
            order = Order.objects.create(
                user=user,
                order_sn=order_sn,
                transport_price=transport.price,
                transport=transport.name,
                username=address.username,
                phone=address.phone,
                address=address_info,
            )
        except:
            return JsonResponse(json_msg(8, "创建订单基本数据失败"))
        # 操作订单商品表
        # 操作redis
        r = get_redis_connection()
        cart_key = get_cart_key(user_id)
        goods_total_price = 0
        for sku_id in sku_ids:
            try:
                goods_sku = GoodsSKU.objects.select_for_update().get(
                    pk=sku_id, is_delete=False, is_on_sale=True)
            except GoodsSKU.DoesNotExist:
                # 回滚数据
                transaction.savepoint_rollback(sid)
                return JsonResponse(json_msg(5, "商品不存在"))

            # 获取购物车中商品的数量
            # redis 是基于内存的存储,有可能数据会丢失
            try:
                count = r.hget(cart_key, sku_id)
                count = int(count)
            except:
                transaction.savepoint_rollback(sid)
                return JsonResponse(json_msg(6, "购物车数量不存在"))
            # 判断库存 是否足够
            if goods_sku.stock < count:
                transaction.savepoint_rollback(sid)
                return JsonResponse(json_msg(7, "库存不足"))

            order_goods = OrderGoods.objects.create(
                order=order,
                goods_sku=goods_sku,
                price=goods_sku.price,
                count=count,
            )

            goods_total_price += count * goods_sku.price

            # 扣除库存 销量增加
            # GoodsSKU.objects.filter(pk=sku_id,stock=goods_sku.stock).update(stock=goods_sku.stock-count)
            goods_sku.stock -= count
            goods_sku.sale_num += count
            goods_sku.save()

        # 再次操作订单基本信息表 商品总金额 订单总金额
        try:
            order_total_price = goods_total_price + transport.price
            order.goods_total_price = goods_total_price
            order.order_total_price = order_total_price
            order.save()
        except:
            # 回滚
            transaction.savepoint_rollback(sid)
            return JsonResponse(json_msg(9, "更新订单失败"))

        # 清空redis中的购物车数据(对应sku_id的)
        r.hdel(cart_key, *sku_ids)

        # 下单成功,提交事务
        transaction.savepoint_commit(sid)
        # 3. 合成响应
        return JsonResponse(json_msg(0, "创建订单成功", data=order_sn))