python - 当 tastypie 连接非 ORM 源​​时,如何返回 404?

标签 python rest http-status-code-404 tastypie

我正在使用此处描述的类立面模式: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 类的父类(super class))中的 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 异常——所以项目内部没有达成共识。

关于python - 当 tastypie 连接非 ORM 源​​时,如何返回 404?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10899148/

相关文章:

python - 对seaborn histplot 中的重叠条有一些指示

java - 是否可以使用 java 或 python 中的应用程序与 WCF TCP 服务进行通信?

spring - Spring Data REST 在不使用 DTO 的情况下通过 REST 资源公开实体是否有问题?

wordpress - category.php 上的分页在 wordpress 中不起作用

html - 如何获取更多信息以调试404错误

python - Pandas Series 参数函数内存

python - 请求响应的 Xpath 返回空列表

java - REST API URL 模式设计

rest - 如何使用 cowboy_rest 重定向

IIS 404 自定义错误 : URL return response code 200 instead