django rest未定义模型对象时将字符串序列化

时间:2018-11-21 00:28:55

标签: python django django-models django-rest-framework

在try / except语句期间,在序列化字符串时遇到麻烦。

在这里,我有一个端点,该端点调用另一个函数refund,该响应是我尝试序列化的那个函数返回的响应。

class RefundOrder(APIView):
    def post(self, request, **kwargs):
        print('test')
        body_unicode = request.body.decode('utf-8')
        body_data = json.loads(body_unicode)
        amount = body_data['amount']
        tenant = get_object_or_404(Tenant, pk=kwargs['tenant_id'])

        refund = SquareGateway(tenant).refund(amount)
        serializer = RefundSerializer(refund)
        return  Response(serializer.data)

这是在post端点中调用的函数。我在try语句中添加了它,以处理square api中的错误。如果api调用失败,我想返回一个错误,如果它们是一个,否则序列化该数据。

    def refund(self, order, amount, reason):

        try:
            response = self.client.transaction().create_refund(stuff)
                
            refund = Refund(
                order=order,
                amount=response.refund.amount_money.amount,
            )
            refund.save()
            return refund
        except ApiException as e:
            return json.loads(e.body)['errors'][0]['detail']

这是退款序列化

class RefundSerializer(serializers.ModelSerializer):
    class Meta:
        model = Refund
        fields = ('id', 'amount')

序列化字符串不会引发错误,只是不会返回im返回的错误消息。当前它返回一个空的序列化对象。

1 个答案:

答案 0 :(得分:2)

据我了解,您需要一个 自定义API异常,该异常会返回自定义消息
因此,首先创建如下的自定义异常类,

from rest_framework.exceptions import APIException
from rest_framework import status


class GenericAPIException(APIException):
    """
    raises API exceptions with custom messages and custom status codes
    """
    status_code = status.HTTP_400_BAD_REQUEST
    default_code = 'error'

    def __init__(self, detail, status_code=None):
        self.detail = detail
        if status_code is not None:
            self.status_code = status_code



然后 引发 refund() 函数中的异常。

def refund(self, order, amount, reason):

    try:
        # your code
    except ApiException as e:
        raise GenericAPIException({"message":"my custom msg"})