python - Django Rest 框架基于类的 View 中的 Django 快捷方式 get_object_or_404

标签 python django django-rest-framework

Django 中的 get_object_or_404 快捷函数在遇到异常时会给出一个非常好的错误消息,格式如下:

'No %s matches the given query.' % queryset.model._meta.object_name)

但是,在基于 DRF 3.X 类的 View 中使用它时,最终的 404 响应数据具有非常精简的版本,如下所示:

{"detail": "Not found."}

很明显,DRF 消息非常通用,没有关于模型名称的信息。我假设 DRF NotFound 异常类定义了 here将消息剥离到当前的最低限度。

尽管在基于 DRF 类的 View 中使用了 Django 返回的原始错误消息,但我如何才能得到它?

最佳答案

APIView 的默认异常处理程序类由 get_exception_handler 决定方法。即,

def get_exception_handler(self):
    """
    Returns the exception handler that this view uses.
    """
    return self.settings.EXCEPTION_HANDLER

换句话说,APIView 类默认使用的处理函数是 rest_framework.views.exception_handler (在 default settings 上指定)。

根据 DRF 文档,

By default DRF handle the REST framework APIException, and alsoDjango's built-in Http404 and PermissionDenied exceptions.

由于在这种情况下您只想为 Http404 自定义错误消息,因此您可以像这样创建自己的处理程序。

即,

from rest_framework.views import exception_handler

def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    # Now overide the error message.
    if response is not None and isinstance(exc, Http404):
        # set the custom message data on response object
        response.data['detail'] =  exc.args[0] # exc.args[0] will have the message text, 

    return response

然后将此自定义处理程序放入您的项目设置中。

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
}

注意:此解决方案未经测试。

关于python - Django Rest 框架基于类的 View 中的 Django 快捷方式 get_object_or_404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53149680/

相关文章:

python - SSH2 Python 如何识别文件是目录

python - 如何在 django rest 框架中获取外键字段名称而不是 id

Django-import-export 更改/删除上传文件中不存在的针对数据库的记录

python - 如何使用 Django Rest Framework API 对 Angular2 进行分页

Django Rest框架向序列化器添加模型方法两次

Django Rest Framework - 创建权限

python - PyQt中的无限背景while循环

python - Linux 将我的 URL 转换为符号?

python - 以哈希形式将密码存储在 MySQL 数据库中 Django App

javascript - Django 中的 Bootstrap 异常慢(40 秒以上): Why?