An error occurred in the current transaction. You can‘t execute queries until the end of the ‘atomic

问题

如图所示,错误返回结果是An error occurred in the current transaction. You can't execute queries until the end of the 'atomic block

 (这个在django中,用swagger进行调试,自己捕获异常的结果)

分析

字面意思

An error occurred in the current transaction. You can‘t execute queries until the end of the ‘atomic_第1张图片

就是django中从开启事务后,到事务with结束(包含异常)后,执行了数据查询语句。

我代码的基本结构(犯了最底下的两个要点)

class InfoStore(APIView):

    @swagger_auto_schema(******)
    def post(self, request):
        receive_data = request.data

        with transaction.atomic():   # 1 在transaction中去try except自己捕获异常
            # 创建事务保存点
            save_id = transaction.savepoint()
            try:
                if(InfoTest.objects.filter(**)):  # 2 在transaction中执行查询语句
                    # process information
                    info_test = InfoTest()
                    info_test .save()

            except Exception as e:
                transaction.savepoint_rollback(save_id)
                return response_as_json(data={
                        'code': '500',
                        'msg': '服务基本信息数据异常存储',
                        'data': e.__str__()
                    },
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR
                )

            transaction.savepoint_commit(save_id)

            return response_as_json(data={'code': '200', 'msg': 'Success', 'data': 'None'}, status=status.HTTP_200_OK)

 

解决

这里参照官方代码的部分解释:(PS:这里是翻译软件翻译出来的,可能细节不够准确)

An error occurred in the current transaction. You can‘t execute queries until the end of the ‘atomic_第2张图片

主要要点:

1不推荐在with transaction.automic中去捕获异常

2在with transaction.automic中执行查询语句会导致TransactionManagementError

 

你可能感兴趣的:(python,SQL,后台,transaction,django,异步,事务)