簡體   English   中英

當tastypie連接非ORM源時,如何返回404?

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

我正在使用這里描述的類似外觀的模式: 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

我不能返回None,拋出一個錯誤。

您應該引發異常: 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類(Resource類的超類)中查看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).")

異常:self._meta.object_class.DoesNotExist在找不到對象時引發,最終變為ObjectDoesNotExist異常 - 因此它在項目內部不一致。

我使用django.core.exceptions中的ObjectDoesNotExist exeption

   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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM