【问题标题】:django rest serialize a string when model object is not defined未定义模型对象时,django rest序列化字符串
【发布时间】:2018-11-21 00:28:55
【问题描述】:

在 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']

这是 Refundserialize

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

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

【问题讨论】:

  • 你有什么问题?您的代码是否会产生错误消息?如果是这样,请发布回溯。
  • 抱歉刚刚更新了我的问题。
  • 所以你的问题一定出自这句话json.loads(e.body)['errors'][0]['detail']
  • 是的,所以json.loads(e.body)['errors'][0]['detail'] 返回一个字符串One or more refunds might already have been applied to this payment,当我将该字符串传递给`RefundSerializer(refund)` 时,会返回一个类似{"amount": null} 的空对象@ 我想返回该字符串而不是物体。如果 api 调用失败。
  • 所以你想返回一个看起来像{"amount": "One or more refunds might already have been applied to this payment"}的对象,对吧?

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


【解决方案1】:

据我了解,您需要一个返回自定义消息的自定义 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"})

【讨论】:

  • 很高兴听到这个消息!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-20
  • 1970-01-01
  • 2015-06-01
  • 2020-10-30
  • 1970-01-01
  • 2015-03-12
  • 1970-01-01
相关资源
最近更新 更多