有没有相当于Flask的`@应用程序错误处理程序`在Django?

2024-03-29 15:34:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写几个视图,并希望验证请求主体。常见的情况是主体必须是一个JSON对象,并且存在某些键。我写了一个视图,代码如下:

try:
    body = json.loads(request.body)
except ValueError:
    return InvalidInputResponse("Could not load request body")

if not isinstance(body, dict):
    return InvalidInputResponse("Request body was not a JSON object")

if set(body.keys()) != {'author', 'title', 'content'}:
    return InvalidInputResponse("Request object missing keys")

InvalidInputResponsehttp.HttpResponse的子类。在

我想在其他视图中重用此代码。我真正想做的是:

^{pr2}$

然而,由于现在的代码,我不能这样做。我要做的是:

body = process_body(request.body, required_keys={'author', 'title', 'content'})
if isinstance(body, http.HttpResponse):
    return body
# rest of code here ...

这有点难看。在

在Flask中,我可以创建一个自定义异常,名为InvalidInputException,然后register an error handler for it。。。比如说,比如:

@app.errorhandler(InvalidInputException)
def handle_invalid_input(error):
    return InvalidInputResponse(error.reason)

在Django中有没有一个等效的机制?如果没有等效的机制,那么处理这个问题的等效方法是什么?在


Tags: 代码视图jsonreturnifobjectrequestnot
1条回答
网友
1楼 · 发布于 2024-03-29 15:34:04

Django也有自定义的异常处理程序。它们可以附加via middleware。在

class InvalidInputMiddleware(object):
    def process_exception(self, request, exception):
        if isinstance(exception, InvalidInputException):
             return InvalidInputResponse(exception.reason)

        return None

Django将返回任何中间件返回的第一个响应。注意,响应阶段以相反的顺序运行中间件。在

如果全局使用,只需添加到^{}的末尾。对于非全局的情况,我使用了一个(稍微邪恶的)middleware_on_classmonkey patcher来完成这个任务:

^{pr2}$

用作

handle_invalid_input = middleware_on_class(InvalidInputMiddleware)

@handle_invalid_input
class View(...):
    pass

相关问题 更多 >