2012-06-05 39 views
7

我使用這裏所描述的立面狀的圖案:http://django-tastypie.readthedocs.org/en/latest/non_orm_data_sources.html當tastypie連接非ORM源時,我該如何返回404?

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

我不能回到無,扔一個錯誤。

+1

檢查源表明與主體之中,以提高NotFound異常(從tastypie.exception)ObjectDoesNotExist exeption:{ 「ERROR_MESSAGE」:「對不起,此請求可能不予處理,請稍後再試。「} –

回答

6

您應該引發一個異常:tastypie.exceptions.NotFound(根據代碼文檔)。

我正在研究CouchDB的tastypie並深入研究這個問題。在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 

一件事是怪我。當我在ModelResource類(資源類的父類),看看obj_get方法:

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

一個例外:如果找不到對象,最終成爲ObjectDoesNotExist例外self._meta.object_class.DoesNotExist上升 - 所以這不是項目內部的共識。

+0

而異常來源https://github.com/toastdriven/django-tastypie/blob/master/tastypie/exceptions.py – TankorSmash

2

我使用從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 
相關問題