From 8efbbdf7f1fde1f6aa19b428478182c5aee71e0e Mon Sep 17 00:00:00 2001 From: Xiaofeng <1169646434@qq.com> Date: Tue, 20 May 2025 17:38:57 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8F=90=E9=AB=98=E5=88=9B=E5=BB=BA=E5=AF=B9?= =?UTF-8?q?=E8=AF=9D=E7=9A=84=E7=A8=B3=E5=AE=9A=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/expertproducts/views.py | 116 +++++++++++++++++++---------------- 1 file changed, 63 insertions(+), 53 deletions(-) diff --git a/apps/expertproducts/views.py b/apps/expertproducts/views.py index a8d9d4c..42bbaf7 100644 --- a/apps/expertproducts/views.py +++ b/apps/expertproducts/views.py @@ -169,67 +169,77 @@ class NegotiationViewSet(viewsets.ModelViewSet): serializer_class = NegotiationSerializer def create(self, request, *args, **kwargs): - """创建谈判并返回包含初始消息的响应""" - serializer = self.get_serializer(data=request.data) - serializer.is_valid(raise_exception=True) + """创建谈判(事务保护版)""" + try: + # 开启事务:所有数据库操作要么全部成功,要么全部回滚 + with transaction.atomic(): + # 1. 验证请求数据 + serializer = self.get_serializer(data=request.data) + serializer.is_valid(raise_exception=True) # 自动返回400错误 - # Extract creator and product from validated data - creator = serializer.validated_data['creator'] - product = serializer.validated_data['product'] + creator = serializer.validated_data['creator'] + product = serializer.validated_data['product'] - # 检查该用户是否存在 - if not CreatorProfile.objects.filter(id=creator.id).exists(): - return Response({ - "code": 404, - "message": "未找到指定的达人", - "data": None - }) + # 2. 检查达人是否存在 + if not CreatorProfile.objects.filter(id=creator.id).exists(): + return Response( + {"code": 404, "message": "未找到指定的达人", "data": None}, + status=status.HTTP_404_NOT_FOUND + ) - # Check if the product exists - if not Product.objects.filter(id=product.id).exists(): - return Response({ - "code": 404, - "message": "未找到指定的商品", - "data": None - }) + # 3. 检查商品是否存在 + if not Product.objects.filter(id=product.id).exists(): + return Response( + {"code": 404, "message": "未找到指定的商品", "data": None}, + status=status.HTTP_404_NOT_FOUND + ) - # Check if a negotiation already exists for the same creator and product - existing_negotiation = Negotiation.objects.filter(creator=creator, product=product).first() - if existing_negotiation: - return Response({ - "code": 400, - "message": "谈判已存在", - "data": { - "negotiation_id": existing_negotiation.id - } - }) + # 4. 检查是否已存在相同谈判 + if Negotiation.objects.filter(creator=creator, product=product).exists(): + return Response( + { + "code": 400, + "message": "谈判已存在", + "data": {} + }, + status=status.HTTP_400_BAD_REQUEST + ) - # 1. 创建谈判记录 - negotiation = serializer.save() + # 5. 创建谈判记录 + negotiation = serializer.save() - # 2. 生成并保存初始消息 - initial_message = self._generate_welcome_message(negotiation) - message = Message.objects.create( - negotiation=negotiation, - role='assistant', - content=initial_message, - stage=negotiation.status - ) + # 6. 生成初始消息 + initial_message = self._generate_welcome_message(negotiation) + message = Message.objects.create( + negotiation=negotiation, + role='assistant', + content=initial_message, + stage=negotiation.status + ) - # 4. 构建响应数据 - response_data = { - "code": 200, - "message": "谈判已创建", - "data": { - "id": message.id, - **serializer.data, - "content": initial_message, - "created_at": message.created_at - } - } + # 7. 返回成功响应 + return Response( + { + "code": 200, + "message": "谈判已创建", + "data": { + "id": message.id, + **serializer.data, + "content": initial_message, + "created_at": message.created_at + } + }, + status=status.HTTP_201_CREATED, + headers=self.get_success_headers(serializer.data) + ) - headers = self.get_success_headers(serializer.data) - return Response(response_data, status=status.HTTP_201_CREATED, headers=headers) + except Exception as e: + # 记录异常细节(实际生产环境应接入监控系统) + # logger.error(f"谈判创建失败: {str(e)}", exc_info=True) + return Response( + {"code": 500, "message": "服务器内部错误", "data": None}, + status=status.HTTP_500_INTERNAL_SERVER_ERROR + ) @action(detail=True, methods=['post']) def chat(self, request, pk=None):