Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0314· OpenAIAi2 WildChat-4.8M (AI2)

Представь, что ты программист Django. Следующий код вызывает эту ошибку:…

  1. User

    Представь, что ты программист Django. Следующий код вызывает эту ошибку: django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.

    class UserUpdateApi(generics.UpdateAPIView): serializer_class = UserUpdateSerializer queryset = CustomUser.objects.all() permission_classes = [permissions.IsAuthenticated]

    def get_object(self):
        return self.request.user
    
    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)
    
    def update(self, request, *args, **kwargs):
        user = self.get_object()
        serializer = self.get_serializer(user, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        response_data = ''
        email = request.data.get('email', None)
        phone_number = request.data.get('phone_number', None)
    
        if phone_number:
            res = SendOrResendSMSAPIView.as_view()(request._request, *args, **kwargs)
    
            if res.status_code == 200:
                response_data = {"detail": _(
                    "Verification e-mail and SMS sent.")}
    
        elif email and not phone_number:
            res = ResendEmailVerificationView.as_view()(request._request, *args, **kwargs)
    
            if res.status_code == 200:
                response_data = {"detail": _(
                    "Verification e-mail sent.")}
    
        else:
            res = SendOrResendSMSAPIView.as_view()(request._request, *args, **kwargs)
    
            if res.status_code == 200:
                response_data = {"detail": _("Verification SMS sent.")}
    
        self.perform_update(serializer)
        return Response(serializer.data, status=status.HTTP_200_OK)
    

    Исправь этот код.

  2. Assistant

    Чтобы исправить эту ошибку, я бы изменил код следующим образом:

    1. Вынес бы отправку SMS и электронной почты из метода update и поместил их в отдельные методы.

    2. Поместил бы вызовы этих методов внутри блока with transaction.atomic(): чтобы гарантировать, что все операции находятся в пакете атомарных транзакций.

    Вот измененный код:

    from django.db import transaction
    
    class UserUpdateApi(generics.UpdateAPIView):
        serializer_class = UserUpdateSerializer
        queryset = CustomUser.objects.all()
        permission_classes = [permissions.IsAuthenticated]
    
        def get_object(self):
            return self.request.user
    
        def put(self, request, *args, **kwargs):
            return self.update(request, *args, **kwargs)
    
        def _send_sms(self, request, *args, **kwargs):
            res = SendOrResendSMSAPIView.as_view()(request._request, *args, **kwargs)
            return res.status_code == 200
    
        def _send_email_verification(self, request, *args, **kwargs):
            res = ResendEmailVerificationView.as_view()(request._request, *args, **kwargs)
            return res.status_code == 200
    
        def update(self, request, *args, **kwargs):
            user = self.get_object()
            serializer = self.get_serializer(user, data=request.data, partial=True)
            serializer.is_valid(raise_exception=True)
    
            response_data = ''
            email = request.data.get('email', None)
            phone_number = request.data.get('phone_number', None)
    
            with transaction.atomic():
                if phone_number:
                    if self._send_sms(request, *args, **kwargs):
                        response_data = {"detail": _("Verification e-mail and SMS sent.")}
                elif email and not phone_number:
                    if self._send_email_verification(request, *args, **kwargs):
                        response_data = {"detail": _("Verification e-mail sent.")}
                else:
                    if self._send_sms(request, *args, **kwargs):
                        response_data = {"detail": _("Verification SMS sent.")}
    
                self.perform_update(serializer)
    
            return Response(serializer.data, status=status.HTTP_200_OK)
    

    Теперь ошибки типа TransactionManagementError не возникнут, потому что отправка SMS и электронной почты находится в отдельных методах и обернуты внутри блока transaction.atomic(). Это гарантирует, что все операции выполняются в рамках единой транзакции.

  3. User

    Этот код снова вызывает эту ошибку. Может дело в сериализаторе, посмотри его пожалуйста, может его нужно тоже переписать: class UserUpdateSerializer(serializers.ModelSerializer): phone_number = PhoneNumberField( source='phone.phone_number', required=False, read_only=True, validators=[ UniqueValidator( queryset=PhoneNumber.objects.all(), message=_( "A user is already registered with this phone number."), ) ], ) email = serializers.EmailField(required=False)

    class Meta:
        model = CustomUser
        fields = ("email", "phone_number", "first_name", "last_name")
    
    def update(self, instance, validated_data):
        if 'phone_number' in validated_data:
            phone_number = validated_data.pop('phone_number')
            phone, created = PhoneNumber.objects.get_or_create(phone_number=phone_number)
            instance.phone = phone
    
        instance = super().update(instance, validated_data)
        return instance
    
  4. Assistant

    По коду сериализатора проблем нет. Сомнения вызывает обновление пользователя во views, смешанное с логикой отправки сообщений и почты. Вам нужно обновить пользователя и сохранить изменения перед отправкой его на верификацию.

    Вам необходимо переместить вызовы проверки в другую функцию, которая следует выполняться после завершения атомарного блока. Отправка сообщений и обработка их результатов в данном случае рекомендуется выполнить также после изменения пользователя.

    Вот обновленный код:

    from django.db import transaction
    
    class UserUpdateApi(generics.UpdateAPIView):
        serializer_class = UserUpdateSerializer
        queryset = CustomUser.objects.all()
        permission_classes = [permissions.IsAuthenticated]
    
        def get_object(self):
            return self.request.user
    
        def put(self, request, *args, **kwargs):
            return self.update(request, *args, **kwargs)
    
        def _send_sms(self, request, *args, **kwargs):
            res = SendOrResendSMSAPIView.as_view()(request._request, *args, **kwargs)
            return res.status_code == 200
    
        def _send_email_verification(self, request, *args, **kwargs):
            res = ResendEmailVerificationView.as_view()(request._request, *args, **kwargs)
            return res.status_code == 200
    
        def _send_verification_messages(self, request, email, phone_number, *args, **kwargs):
            response_data = ''
    
            if phone_number and self._send_sms(request, *args, **kwargs):
                response_data = {"detail": _("Verification e-mail and SMS sent.")}
            elif email and not phone_number:
                if self._send_email_verification(request, *args, **kwargs):
                    response_data = {"detail": _("Verification e-mail sent.")}
            else:
                if self._send_sms(request, *args, **kwargs):
                    response_data = {"detail": _("Verification SMS sent.")}
    
            return response_data
    
        def update(self, request, *args, **kwargs):
            user = self.get_object()
            serializer = self.get_serializer(user, data=request.data, partial=True)
            serializer.is_valid(raise_exception=True)
    
            email = request.data.get('email', None)
            phone_number = request.data.get('phone_number', None)
    
            with transaction.atomic():
                self.perform_update(serializer)
    
            response_data = self._send_verification_messages(request, email, phone_number, *args, **kwargs)
    
            return Response({**serializer.data, **response_data}, status=status.HTTP_200_OK)
    

    Теперь код разделен на функции обновления пользователя и отправку сообщений. Функция _send_verification_messages() будет вызываться после завершения атомарного блока.

  5. User

    Все равно вызывается эта ошибка: django_1 | An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.: /user/user-update/ django_1 | Traceback (most recent call last): django_1 | File "/usr/local/lib/python3.9/site-packages/rest_framework/views.py", line 497, in dispatch django_1 | self.initial(request, *args, kwargs) django_1 | File "/usr/local/lib/python3.9/site-packages/rest_framework/views.py", line 414, in initial django_1 | self.perform_authentication(request) django_1 | File "/usr/local/lib/python3.9/site-packages/rest_framework/views.py", line 324, in perform_authentication django_1 | request.user django_1 | File "/usr/local/lib/python3.9/site-packages/rest_framework/request.py", line 227, in user django_1 | self._authenticate() django_1 | File "/usr/local/lib/python3.9/site-packages/rest_framework/request.py", line 380, in _authenticate django_1 | user_auth_tuple = authenticator.authenticate(self) django_1 | File "/usr/local/lib/python3.9/site-packages/dj_rest_auth/jwt_auth.py", line 141, in authenticate django_1 | return self.get_user(validated_token), validated_token django_1 | File "/usr/local/lib/python3.9/site-packages/rest_framework_simplejwt/authentication.py", line 119, in get_user django_1 | user = self.user_model.objects.get({api_settings.USER_ID_FIELD: user_id}) django_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method django_1 | return getattr(self.get_queryset(), name)(*args, **kwargs) django_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 435, in get django_1 | num = len(clone) django_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 262, in len django_1 | self._fetch_all() django_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 1354, in _fetch_all django_1 | self._result_cache = list(self._iterable_class(self)) django_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 51, in iter django_1 | results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) django_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1202, in execute_sql django_1 | cursor.execute(sql, params) django_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 99, in execute django_1 | return super().execute(sql, params) django_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 67, in execute django_1 | return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) django_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers django_1 | return executor(sql, params, many, context) django_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 79, in _execute django_1 | self.db.validate_no_broken_transaction() django_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 458, in validate_no_broken_transaction django_1 | raise TransactionManagementError( django_1 | django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. django_1 | An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.: /user/user-update/ django_1 | Traceback (most recent call last): django_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/fields/related_descriptors.py", line 402, in get django_1 | rel_obj = self.related.get_cached_value(instance) django_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/fields/mixins.py", line 15, in get_cached_value django_1 | return instance._state.fields_cache[cache_name] django_1 | KeyError: 'phone' django_1 | django_1 | During handling of the above exception, another exception occurred: django_1 | django_1 | Traceback (most recent call last): django_1 | File "/usr/local/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch django_1 | response = handler(request, *args, **kwargs) django_1 | File "/usr/local/lib/python3.9/site-packages/rest_framework/generics.py", line 229, in patch django_1 | return self.partial_update(request, *args, **kwargs) django_1 | File "/usr/local/lib/python3.9/site-packages/rest_framework/mixins.py", line 82, in partial_update django_1 | return self.update(request, *args, **kwargs) django_1 | File "/app/authentication/api/users.py", line 262, in update django_1 | return Response({**serializer.data, **response_data}, status=status.HTTP_200_OK) django_1 | File "/usr/local/lib/python3.9/site-packages/rest_framework/serializers.py", line 555, in data django_1 | ret = super().data django_1 | File "/usr/local/lib/python3.9/site-packages/rest_framework/serializers.py", line 253, in data django_1 | self._data = self.to_representation(self.instance) django_1 | File "/usr/local/lib/python3.9/site-packages/rest_framework/serializers.py", line 509, in to_representation django_1 | attribute = field.get_attribute(instance) django_1 | File "/usr/local/lib/python3.9/site-packages/rest_framework/fields.py", line 457, in get_attribute django_1 | return get_attribute(instance, self.source_attrs) django_1 | File "/usr/local/lib/python3.9/site-packages/rest_framework/fields.py", line 97, in get_attribute django_1 | instance = getattr(instance, attr) django_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/fields/related_descriptors.py", line 410, in get django_1 | rel_obj = self.get_queryset(instance=instance).get(**filter_args) django_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 435, in get django_1 | num = len(clone) django_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 262, in len django_1 | self._fetch_all() django_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 1354, in _fetch_all django_1 | self._result_cache = list(self._iterable_class(self)) django_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 51, in iter django_1 | results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) django_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1202, in execute_sql django_1 | cursor.execute(sql, params) django_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 99, in execute django_1 | return super().execute(sql, params) django_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 67, in execute django_1 | return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) django_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers django_1 | return executor(sql, params, many, context) django_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 79, in _execute django_1 | self.db.validate_no_broken_transaction() django_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 458, in validate_no_broken_transaction django_1 | raise TransactionManagementError( django_1 | django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. django_1 | [06/Jun/2023 09:23:50] "PATCH /user/user-update/ HTTP/1.1" 500 183

  6. Assistant

    Спасибо за предоставленные данные об ошибках. Похоже, проблема возникает в процессе аутентификации пользователя, которая является частью обработки запроса перед выполнением вашего кода. Поскольку мы добавили атомарную транзакцию в метод update, это может вызвать конфликт с транзакцией в джанго рест-аутентификации.

    Вам следует удалить атомарную транзакцию из вашего метода update. Вместо этого можно использовать параметр atomic_requests в классе настройки базы данных Django. Добавьте следующий код в ваш settings.py, чтобы все запросы к базе данных, связанные с вашим приложением, были атомарными:

    # settings.py
    
    DATABASES = {
        'default': {
            ...
            'ATOMIC_REQUESTS': True,
            ...
        }
    }
    

    очень важно, что вся ваша бизнес-логика вызывала ошибки только через исключения, чей эффект будет отлеживаемым Django. Если его не содержать на верхнем уровне запроса, и ошибка возникнет внутри, откатить транзакцию станет проблемой.