postgresql 如何在文件上传失败时不保存到数据库

olhwl3o2  于 2023-01-05  发布在  PostgreSQL
关注(0)|答案(1)|浏览(123)

当用户上传一个文档并点击提交时,该文件将被存储在一个文件夹中,并与一堆其他细节沿着创建一个数据库条目。我正在寻找的是,如果文档没有被上传到特定位置,则可以避免保存。
serializer.py

class DocumentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Request
        fields = ['file', 'doc_type']

    def create(self, validated_data):
        msg = self.__construct_message_body()
        validated_data['type'] = Request.request_types[-1][0]
        validated_data['input_message'] = msg
        instance = ParseRequest.objects.create(**validated_data)
        msg['request_id'] = instance.id
        instance.input_message = msg
        instance.save()
        return instance

views.py

class DocumentView(CreateAPIView, ResponseViewMixin):
    parser_classes = (MultiPartParser, FileUploadParser,)
    serializer_class = DocumentSerializer

    def create(self, request, *args, **kwargs):
        try:
            data = request.data
            serializer = self.get_serializer(
                data=data, context={'request': request})
            serializer.is_valid()
            serializer.save()
        except Exception as e:
            logger.error(e)
            return self.error_response(message=ERROR_RESPONSE['UPLOAD_DOCUMENT'])
        return self.success_response(message=SUCCESS_RESPONSE['UPLOAD_DOCUMENT'])
a5g8bdjr

a5g8bdjr1#

您可以使用原子事务。并且可以按如下方式更改代码:
第一个月

from django.db import transaction

class DocumentView(CreateAPIView, ResponseViewMixin):
    parser_classes = (MultiPartParser, FileUploadParser,)
    serializer_class = DocumentSerializer

    def create(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                data = request.data
                serializer = self.get_serializer(
                    data=data, context={'request': request})
                serializer.is_valid()
                serializer.save()
                return self.success_response(message=SUCCESS_RESPONSE['UPLOAD_DOCUMENT'])
        except Exception as e:
            logger.error(e)
            return self.error_response(message=ERROR_RESPONSE['UPLOAD_DOCUMENT'])

如果with块内部发生错误,则不会将其保存到数据库中。

相关问题