Árn*_*son 8 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
Run Code Online (Sandbox Code Playgroud)
我不能返回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()
Run Code Online (Sandbox Code Playgroud)
我的例子:
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
Run Code Online (Sandbox Code Playgroud)
有一点对我来说很奇怪.当我在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).")
Run Code Online (Sandbox Code Playgroud)
异常:self._meta.object_class.DoesNotExist在找不到对象时引发,最终变为ObjectDoesNotExist异常 - 因此它在项目内部不一致.
| 归档时间: |
|
| 查看次数: |
2641 次 |
| 最近记录: |