Tastypie django自定义错误处理
我想返回一些JSON响应,而不仅仅是返回带有错误代码的头。在Tastype中有没有办法处理这样的错误?最终解决了。如果有人需要,这里有一个很好的资源Tastypie django自定义错误处理,django,error-handling,tastypie,Django,Error Handling,Tastypie,我想返回一些JSON响应,而不仅仅是返回带有错误代码的头。在Tastype中有没有办法处理这样的错误?最终解决了。如果有人需要,这里有一个很好的资源 您可以覆盖tastypie的资源方法。它以下划线开头的事实确实表明这是一个“私有”方法,不应该被覆盖,但我发现它比必须覆盖wrap\u view()并复制大量逻辑更干净 这是我使用它的方式: from tastypie import http from tastypie.resources import ModelResource from tas
您可以覆盖tastypie的
资源
方法。它以下划线开头的事实确实表明这是一个“私有”方法,不应该被覆盖,但我发现它比必须覆盖wrap\u view()
并复制大量逻辑更干净
这是我使用它的方式:
from tastypie import http
from tastypie.resources import ModelResource
from tastypie.exceptions import TastypieError
class MyResource(ModelResource):
class Meta:
queryset = MyModel.objects.all()
fields = ('my', 'fields')
def _handle_500(self, request, exception):
if isinstance(exception, TastypieError):
data = {
'error_message': getattr(
settings,
'TASTYPIE_CANNED_ERROR',
'Sorry, this request could not be processed.'
),
}
return self.error_response(
request,
data,
response_class=http.HttpApplicationError
)
else:
return super(MyResource, self)._handle_500(request, exception)
在本例中,我通过检查exception
是否是tastypeerror
的实例来捕获所有tastypi错误,并返回一个JSON响应,其中包含消息“抱歉,此请求无法处理”。如果是另一个异常,我将使用super()
调用父级\u handle\u 500
,这将在开发模式下创建django错误页,或在生产模式下创建send\u admins()
如果您想为特定异常提供特定的JSON响应,只需对特定异常执行isinstance()
检查即可。以下是所有Tastype例外情况:
实际上,我认为在Tastypie中应该有更好/更干净的方法来实现这一点,所以我在他们的github上找到了答案。最终找到了答案。如果有人需要,这里有一个很好的资源。如果可以的话,把它清理干净,让它成为帮助社区的答案
from tastypie import http
from tastypie.resources import ModelResource
from tastypie.exceptions import TastypieError
class MyResource(ModelResource):
class Meta:
queryset = MyModel.objects.all()
fields = ('my', 'fields')
def _handle_500(self, request, exception):
if isinstance(exception, TastypieError):
data = {
'error_message': getattr(
settings,
'TASTYPIE_CANNED_ERROR',
'Sorry, this request could not be processed.'
),
}
return self.error_response(
request,
data,
response_class=http.HttpApplicationError
)
else:
return super(MyResource, self)._handle_500(request, exception)