Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return 404 when tastypie is interfacing non-ORM sources?

I am using the facade-like pattern described here: http://django-tastypie.readthedocs.org/en/latest/non_orm_data_sources.html

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

I can't return None, tosses an error.

like image 707
Árni St. Sigurðsson Avatar asked Jun 05 '12 14:06

Árni St. Sigurðsson


People also ask

How can I use tastypie without knowing about Orm?

Hooking up things like a NoSQL store (see Using Tastypie With Non-ORM Data Sources ), a search solution like Haystack or even managed filesystem data are all good use cases for Resource knowing nothing about the ORM. Tastypie can be thought of as a set of class-based views that provide the API functionality.

What is data in tastypie?

This data could be a table of a database, a collection of other resources or a similar form of data storage. In Tastypie, these resources are generally intermediaries between the end user & objects, usually Django models.

What is resource in tastypie?

In Tastypie, these resources are generally intermediaries between the end user & objects, usually Django models. As such, Resource (and its model-specific twin ModelResource) form the heart of Tastypie’s functionality. A sample resource definition might look something like:

What does 404 not found mean in an API response?

The information returned with the response is dependent on the method used in the request. 404 Not Found - The server has not found anything matching the Request-URI. In the context of your API, it very much depends on how queries are created and how objects are retrieved. But, my interpretation has always been that:


1 Answers

You should raise an exception: tastypie.exceptions.NotFound (according to the code documentation).

I am working on tastypie for CouchDB and delved into the issue. In the tastypie.resources.Resource class you can find the method that you have to override:

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

My example:

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

One thing is strange for me. When I had a look at obj_get method in ModelResource class (the superclass of Resource class):

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

an exception: self._meta.object_class.DoesNotExist is raised when object is not found, which eventually becomes ObjectDoesNotExist exception - so it is not consensus inside the project.

like image 171
ady Avatar answered Oct 13 '22 01:10

ady