django - 将 HttpError 转换为 JSON

标签 django

在我的 Django 应用程序中,我在几个地方这样做:

raise HttpError(
    message="Bla bla bla",
    status=400,
)

是否有某种方法可以拦截所有引发的 HttpError 并将它们包装在一个漂亮的 JSON 正文中?像这样的东西:

{
    "status": "error",
    "message":" "Bla bla bla"
}

最佳答案

自定义 middleware是你应该做这项工作的地方。

创建中间件类,定义process_exception()方法;如果发生 HttpError,则返回 json 响应,否则返回 None(不要重新引发异常):

Django calls process_exception() when a view raises an exception. process_exception() should return either None or an HttpResponse object. If it returns an HttpResponse object, the template response and response middleware will be applied, and the resulting response returned to the browser. Otherwise, default exception handling kicks in.

这是一个例子:

class CustomMiddleware():
    def process_exception(self, request, exception):
        if not isinstance(exception, HttpError):
            return None

        response = json.dumps({'status': exception.status, 
                               'message': exception.message})
        return HttpResponse(response, 
                            content_type='application/json; charset=utf-8')

另外,不要忘记将您的中间件添加到 MIDDLEWARE_CLASSES设置。

希望有帮助。

关于django - 将 HttpError 转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20916967/

相关文章:

python - 具有特定条件的模型的 Django 下一个/上一个实例?

python - 我的第一个网络应用程序 (Python) : use CGI, 还是像 Django 这样的框架?

Django - 如何覆盖模型上的过滤器?

python - 如何诊断似乎什么都不做的 Django 注册表?

django - 模板中的Django多对多

django - Django Unit Test,用于测试文件下载

python - Django后台任务

Django - 如何复制使用带有直通模型的 m2m 字段的模型实例

django-tables2 linkcolumn 同一单元格中的多个项目

python - celery 、kombu 和 django - 导入错误