2012-01-10 2 views
8

오류 코드가있는 헤더를 반환하는 대신 일부 JSON 응답을 반환하고 싶습니다. 그런 실수를 처리하는 tastypie의 방법이 있습니까?Tastypie-django 사용자 지정 오류 처리

+0

결국 알아 냈습니다. 다른 사람이 필요로 할 때 여기를 볼 수있는 좋은 자료입니다. https://gist.github.com/1116962 –

+0

가능하다면 이것을 정리하고 지역 사회를 돕기위한 답을하십시오. – Dave

답변

5

결국 알아 냈습니다. 다른 사람이 필요로 할 때 여기를 볼 수있는 좋은 자료입니다. http://gist.github.com/1116962

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 
3

당신은 tastypie의 Resource 방법 _handle_500()를 덮어 쓸 수 있습니다. 실제로 이것이 밑줄로 시작한다는 사실은 이것이 "개인적인"방법이며 덮어 써서는 안된다는 것을 나타내지 만 나는 wrap_view()을 덮어 쓰고 많은 논리를 복제하는 것보다 더 깔끔한 방법이라고 생각합니다. 이 경우

from tastypie import http 
from tastypie.resources import ModelResource 
from tastypie.exceptions import TastypieError 

class MyResource(ModelResource): 

    class Meta: 
     queryset = MyModel.objects.all() 
     fields = ('my', 'fields') 

    def _handle_500(self, request, exception): 

     if isinstance(exception, TastypieError): 

      data = { 
       'error_message': getattr(
        settings, 
        'TASTYPIE_CANNED_ERROR', 
        'Sorry, this request could not be processed.' 
       ), 
      } 

      return self.error_response(
       request, 
       data, 
       response_class=http.HttpApplicationError 
      ) 

     else: 
      return super(MyResource, self)._handle_500(request, exception) 

내가 exception 죄송합니다,이 요청이 있었다 "TastypieError의 인스턴스이며, 메시지와 JSON의 reponse를 반환 할 경우 확인하여 모든 Tastypie 오류를 잡아 :

내가 그것을 사용하는 방법입니다 처리되지 않습니다. " 다른 예외 인 경우 _handle_500super()을 사용하여 호출하면 개발 모드에서 장고 오류 페이지가 생성되고 프로덕션 모드에서는 send_admins()이 생성됩니다.

특정 예외에 대해 특정 JSON 응답을 받으려면 isinstance() 특정 예외를 확인하십시오.

https://github.com/toastdriven/django-tastypie/blob/master/tastypie/exceptions.py

는 사실 내가 Tastypie에서이 작업을 수행 할 수있는 더 나은/청소기 방법이 있어야한다고 생각합니다, 그래서 자신의 GitHub의에 I opened a ticket : 여기에 모든 Tastypie 예외입니다.

관련 문제