gpt4 book ai didi

python - 在 Django 中是否有相当于 Flask 的 `@app.errorhandler`?

转载 作者:太空宇宙 更新时间:2023-11-04 00:49:46 24 4
gpt4 key购买 nike

我正在编写多个 View ,并希望验证请求主体。常见情况是正文必须是具有特定键的 JSON 对象。我写了一个 View ,并有这段代码:

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 的子类。

我想在其他 View 中重复使用此代码。我真正想做的是:

body = process_body(request.body, required_keys={'author', 'title', 'content'})
# rest of code here ...

但是,按照现在的代码,我不能这样做。我必须这样做:

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 中是否有等效的机制?如果没有等效机制,那么等效的处理方法是什么?

最佳答案

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

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

return None

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

如果全局使用,只需添加到MIDDLEWARE_CLASSES的末尾.对于非全局案例,我使用了一个(有点邪恶的)middleware_on_class monkey-patcher 来完成这项工作:

from functools import wraps
from django.utils.decorators import (
decorator_from_middleware,
method_decorator
)

def middleware_on_class(middleware):
def decorator(cls):
dispatch = cls.dispatch

@wraps(dispatch)
@method_decorator(decorator_from_middleware(middleware))
def wrapper(self, *args, **kwargs):
return dispatch(self, *args, **kwargs)

cls.dispatch = wrapper
return cls
return decorator

用作

handle_invalid_input = middleware_on_class(InvalidInputMiddleware)

@handle_invalid_input
class View(...):
pass

关于python - 在 Django 中是否有相当于 Flask 的 `@app.errorhandler`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37598538/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com