【问题标题】:Returning custom message in tastypie in obj_create method在 obj_create 方法中返回美味派的自定义消息
【发布时间】:2015-02-04 12:59:54
【问题描述】:

我正在tastepie中编写Rest API并创建如下自定义资源

class Myresource(Resource):
      def obj_create(self, request, **kwargs):
          # logic when POST request is called
          # here if some error occurs while inserting data I want to add my custom error message and return it response. 
          return bundle

如何从 obj_create 消息返回自定义错误消息。现在我正在处理异常,但 sweetpie 总是返回 201。

【问题讨论】:

    标签: python tastypie


    【解决方案1】:

    我认为您需要重写资源中的 wrap_view 方法,如 here 所述。

    这就是它的工作方式。

    class YourResource(ModelResource):
    
    def wrap_view(self, view):
        """
        Wraps views to return custom error codes instead of generic 500's
        """
        @csrf_exempt
        def wrapper(request, *args, **kwargs):
            try:
                callback = getattr(self, view)
                response = callback(request, *args, **kwargs)
    
                if request.is_ajax():
                    patch_cache_control(response, no_cache=True)
    
                # response is a HttpResponse object, so follow Django's instructions
                # to change it to your needs before you return it.
                # https://docs.djangoproject.com/en/dev/ref/request-response/
                return response
            except (BadRequest, ApiFieldError), e:
                return HttpBadRequest({'code': 666, 'message':e.args[0]})
            except ValidationError, e:
                # Or do some JSON wrapping around the standard 500
                return HttpBadRequest({'code': 777, 'message':', '.join(e.messages)})
            except Exception, e:
                # Rather than re-raising, we're going to things similar to
                # what Django does. The difference is returning a serialized
                # error message.
                return self._handle_500(request, e)
    
        return wrapper
    

    【讨论】:

      猜你喜欢
      • 2015-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多