2012-06-05 1 views
7

Я использую фасад, как образец, описанный здесь: http://django-tastypie.readthedocs.org/en/latest/non_orm_data_sources.htmlКак мне вернуть 404, когда tastypie взаимодействует с источниками, отличными от ORM?

def obj_get(self, request=None, **kwargs): 
    rv = MyObject(init=kwargs['pk']) 
    audit_trail.message(...) 
    return rv 

Я не могу вернуться None, бросает ошибку.

+1

Исследование источника предлагает повысить NotFound Exception (от tastypie.exception) с существом тела: { "error_message": «К сожалению, этот запрос может не обрабатывается. Повторите попытку позже. "} –

ответ

6

Вы должны поднять исключение: tastypie.exceptions.NotFound (в соответствии с документацией по коду).

Я работаю над tastypie для CouchDB и вникаю в проблему. В классе tastypie.resources.Resource вы можете найти метод, который вы должны переопределить:

def obj_get(self, request=None, **kwargs): 
    """ 
    Fetches an individual object on the resource. 

    This needs to be implemented at the user level. If the object can not 
    be found, this should raise a ``NotFound`` exception. 

    ``ModelResource`` includes a full working version specific to Django's 
    ``Models``. 
    """ 
    raise NotImplementedError() 

Мой пример:

def obj_get(self, request=None, **kwargs): 
    """ 
    Fetches an individual object on the resource. 

    This needs to be implemented at the user level. If the object can not 
    be found, this should raise a ``NotFound`` exception. 
    """ 
    id_ = kwargs['pk'] 
    ups = UpsDAO().get_ups(ups_id = id_) 
    if ups is None: 
     raise NotFound(
       "Couldn't find an instance of '%s' which matched id='%s'."% 
       ("UpsResource", id_)) 
    return ups 

Одно странно для меня. Когда я взглянул на obj_get метод в классе ModelResource (суперкласс класса ресурсов):

def obj_get(self, request=None, **kwargs): 
    """ 
    A ORM-specific implementation of ``obj_get``. 

    Takes optional ``kwargs``, which are used to narrow the query to find 
    the instance. 
    """ 
    try: 
     base_object_list = self.get_object_list(request).filter(**kwargs) 
     object_list = self.apply_authorization_limits(request, base_object_list) 
     stringified_kwargs = ', '.join(["%s=%s" % (k, v) for k, v in kwargs.items()]) 

     if len(object_list) <= 0: 
      raise self._meta.object_class.DoesNotExist("Couldn't find an instance of '%s' which matched '%s'." % (self._meta.object_class.__name__, stringified_kwargs)) 
     elif len(object_list) > 1: 
      raise MultipleObjectsReturned("More than '%s' matched '%s'." % (self._meta.object_class.__name__, stringified_kwargs)) 

     return object_list[0] 
    except ValueError: 
     raise NotFound("Invalid resource lookup data provided (mismatched type).") 

исключение: self._meta.object_class.DoesNotExist возникает, когда объект не найден, который в конечном итоге становится ObjectDoesNotExist исключение - поэтому в проекте не существует консенсуса.

+0

И источник исключений https://github.com/toastdriven/django-tastypie/blob/master/tastypie/exceptions.py – TankorSmash

2

Я использую ObjectDoesNotExist Exeption из django.core.exceptions

def obj_get(self, request=None, **kwargs): 
     try: 
      info = Info.get(kwargs['pk']) 
     except ResourceNotFound: 
      raise ObjectDoesNotExist('Sorry, no results on that page.') 
     return info 

 Смежные вопросы

  • Нет связанных вопросов^_^