HttpRespons的Django映射异常

2024-04-24 02:47:39 发布

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

有没有办法将异常映射到django中的HttpResponse对象?在

例如,我想将自己的“UnauthorizedException”映射到HttpResponseForbidden响应对象,这样当我的视图引发该异常时,而不是自动映射到500,某些异常可以被视为401。在


Tags: 对象django视图httpresponse办法httpresponseforbiddenunauthorizedexception
1条回答
网友
1楼 · 发布于 2024-04-24 02:47:39

如果您实现自己的中间件来实现^{}方法,则可以这样做。一个简单的例子:

from django.http import HttpResponseForbidden
from app.exceptions import UnauthorizedException


class UnauthorizedAccessMiddleware(object):
    def process_exception(self, request, exception):
        if isinstance(exception, UnauthorizedException):
           return HttpResponseForbidden("You are not authorized to access that page.")

相关问题 更多 >