如何在Django中引发410错误 [英] How to raise a 410 error in Django
问题描述
我希望在某些Django页面返回410个错误,而不是返回404。基本上,而不是调用 raise Http404('some error message')
,我想改为调用 raise Http410('some error message')
快捷方式。
我很困惑,因为在django.http中,函数Http404只是简单的:
$ b $ / code>
所以如果我做同样的事情并创建我的Http410功能,我会假设它看起来像:
class Http410例外):
pass
但是,这样做会返回异常,但提供了一个500错误页。如何重新创建Http404异常的魔法?我应该注意,我需要从我的模型(而不是视图)引发异常,所以我不能只返回一个HttpResponseGone。
提前感谢!
更新:
我完全了解HttpResponseGone,并在我的原始问题中提到了这一点。我已经知道如何在我的观点回报这个。我的问题是:你如何提高一个Http 410异常,类似于你如何提高Http 404异常?我想能够在任何地方提出这个例外,而不仅仅是在我的观点。谢谢!
Django不包括一个机制,因为走了应该是正常的工作流程,而不是错误的条件,但如果你不想将其视为退货回复,作为例外,只需实施中间件。
class MyGoneMiddleware(object):
def process_exception(self,request,exception)
如果isinstance(异常,Http410):
返回HttpResponseGone(Gone!)
返回无
I'd like to return 410 errors at for some of my Django pages instead of returning 404s. Basically, instead of calling raise Http404('some error message')
, I would like to instead call raise Http410('some error message')
shortcut.
I am confused because in django.http, the function Http404 is simply:
class Http404(Exception):
pass
So if I do the same thing and create my Http410 function, I would assume it would look like:
class Http410(Exception):
pass
However, doing this returns the exception but serves up a 500 error page. How do I recreate the magic of the Http404 exception? I should note, I need to raise the exception from my models (not views) so I can't just return an HttpResponseGone.
Thanks in advance!
Update: I am fully aware of HttpResponseGone and mentioned this in my original question. I already know how to return this in my views. My question is: How do you raise an Http 410 exception similarly to how you raise an Http 404 exception? I want to be able to raise this exception anywhere, not just in my views. Thanks!
Django does not include a mechanism for this because gone should be normal workflow, not an error condition, but if you want to not treat it as a return response, and as an exception, just implement a middleware.
class MyGoneMiddleware(object):
def process_exception(self, request, exception):
if isinstance(exception, Http410):
return HttpResponseGone("Gone!")
return None
这篇关于如何在Django中引发410错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!