如何在Django中引发410错误

Spi*_*ike 10 python django error-handling httpresponse http-status-code-410

我想为我的一些Django页面返回410错误,而不是返回404.基本上,raise Http404('some error message')我不想打电话,而是打电话给raise Http410('some error message')快捷方式.

我很困惑因为在django.http中,函数Http404很简单:

class Http404(Exception):
    pass
Run Code Online (Sandbox Code Playgroud)

所以,如果我做同样的事情并创建我的Http410函数,我会认为它看起来像:

class Http410(Exception):
    pass
Run Code Online (Sandbox Code Playgroud)

但是,这样做会返回异常,但会提供500错误页面.如何重新创建Http404异常的魔力?我应该注意,我需要从我的模型(而不是视图)中引发异常,所以我不能只返回一个HttpResponseGone.

提前致谢!

更新:我完全了解HttpResponseGone,并在我原来的问题中提到了这一点.我已经知道如何在我的观点中返回这个.我的问题是:你如何提出一个Http 410异常与你如何引发Http 404异常类似?我希望能够在任何地方提出这个例外,而不仅仅是在我的观点中.谢谢!

Spi*_*nim 22

from django.http import HttpResponse
return HttpResponse(status=410)
Run Code Online (Sandbox Code Playgroud)


Mik*_*iak 16

Django没有包含这种机制,因为它应该是正常的工作流,而不是错误条件,但是如果你不想把它当作一个返回响应,并且作为例外,只需实现一个中间件.

class MyGoneMiddleware(object):
    def process_exception(self, request, exception):
        if isinstance(exception, Http410):
            return HttpResponseGone("Gone!")
        return None
Run Code Online (Sandbox Code Playgroud)


San*_*nta 11

在视图处理程序中返回a HttpResponseGone的子类HttpResponse.