python项目_mysql开启事务

wensonlee 2020-06-25

1.导入模块包

from django.db import transaction

2.设置回滚点

with transaction.atomic():
            save_id = transaction.savepoint() # 设置回滚点
            try:
                order = Order.objects.create(
                    order_title=order_title,
                    total_price=total_price,
                    real_price=real_price,
                    order_number=order_number,
                    order_status = 0,
                    pay_type=pay_type,
                    credit=credit,
                    coupon=coupon,
                    user_id=user_id
                )

                # 记录当前订单定义的课程信息到订单详情
                redis_conn = get_redis_connection("cart")
                cart_hash = redis_conn.hgetall("cart_%s" % user_id)
                selected_set = redis_conn.smembers("selected_%s" % user_id)

                # 开启redis事务
                pipe = redis_conn.pipeline()
                pipe.multi()

                # 计算取当前课程的总价格价格
                total_price = 0
                coupon_price = 0

                for course_id_bytes in selected_set:
                    course_id = course_id_bytes.decode()
                    expire_time = int( cart_hash.get(course_id_bytes).decode() )

                    # 根据当前课程ID来获取课程信息
                    course = Course.objects.get(pk=course_id)

                    # 把课程信息添加到订单详情里面
                    order_detail = OrderDetail.objects.create(
                        order=order,
                        course=course,
                        expire=expire_time,
                        price=course.real_price(expire_time),
                        real_price=course.real_price(expire_time), # todo 将来完成优惠券或者积分的时候计算真实的价格
                        discount_name="原价购买", # todo 将来完成了优惠以后,这里进行调整
                    )

                    # 从购物车中删除对应的商品课程
                    pipe.hdel("cart_%s" % user_id, course_id)
                    pipe.srem("selected_%s" % user_id, course_id)

                    total_price += float(order_detail.price)

                # 计算订单的总价格
                # 判断是否使用了积分,,如果使用了积分,则积分抵扣的金额
                if credit > 0:
                    # 判断是否使用了优惠券,如果使用了优惠券,则计算优惠券的抵扣金额
                    credit_price = credit / constants.CREDIT_MONEY

                if coupon > 0:
                    user = self.context["request"].user
                    coupon = validated_data.get("coupon")
                    now_time = datetime.now()
                    try:
                        result = UserCoupon.objects.get(pk=coupon, is_show=True, is_deleted=False, user_id=user.id, start_time__lt=now_time, end_time__gt=now_time)
                    except UserCoupon.DoesNotExist:
                        raise serializers.ValidationError("对不起,当前优惠券不存在或者已经过期不可用!")

                    sale = result.coupon.sale
                    if result.coupon.coupon_type == 0:
                        # 折扣优惠
                        coupon_price = total_price * (1-float(sale[1:]))
                    else:
                        # 减免优惠
                        coupon_price =  float(sale[1:] )

                # 提交redis事务操作
                pipe.execute()

                #保存总价格和实付价格到订单里面
                order.total_price = total_price
                order.real_price = total_price - credit/constants.CREDIT_MONEY - coupon_price
                order.save()
            except:
                transaction.savepoint_rollback(save_id)
                return serializers.ValidationError("订单生成失败!")

相关推荐