2012-06-05 5 views
7

estoy usando el patrón de fachada como se describe aquí: http://django-tastypie.readthedocs.org/en/latest/non_orm_data_sources.html¿Cómo devuelvo 404 cuando tastypie está interactuando con fuentes que no son ORM?

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

no puedo volver Ninguno, arroja un error.

+1

examinar la fuente sugiere elevar NotFound Excepción (de tastypie.exception) con el ser corporal: { "mensaje_error": "Lo siento, esta solicitud puede no se procesará. Vuelva a intentarlo más tarde.}} –

Respuesta

6

Debe hacer una excepción: tastypie.exceptions.NotFound (según la documentación del código).

Estoy trabajando en tastypie para CouchDB y profundicé en el problema. En la clase tastypie.resources.Resource se puede encontrar el método que hay que anular:

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() 

Mi ejemplo:

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 

Una cosa es extraño para mí. Cuando tuve un vistazo a obj_get método en la clase ModelResource (la superclase de la clase de recursos):

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).") 

una excepción: self._meta.object_class.DoesNotExist se eleva cuando no se encuentra objeto, que finalmente se convierte en una excepción ObjectDoesNotExist - entonces no es consenso dentro del proyecto.

+0

Y la fuente de excepciones https://github.com/toastdriven/django-tastypie/blob/master/tastypie/exceptions.py – TankorSmash

2

usar excepcion ObjectDoesNotExist de 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 
Cuestiones relacionadas