如何在 Django 中引发 410 错误
我想为我的一些 Django 页面返回 410 错误,而不是返回 404。基本上,我不想调用 raise Http404('some error message')
,而是调用 raise Http410('some error message')
快捷方式。
我很困惑,因为在 django.http 中,函数 Http404 很简单:
class Http404(Exception):
pass
因此,如果我做同样的事情并创建我的 Http410 函数,我会假设它看起来像:
class Http410(Exception):
pass
但是,这样做会返回异常,但会提供 500 错误页面。如何重现 Http404 异常的魔力?我应该注意,我需要从我的模型(而不是视图)中引发异常,所以我不能只返回 HttpResponseGone。
提前致谢!
更新: 我完全了解 HttpResponseGone 并在我原来的问题中提到了这一点。我已经知道如何在我的观点中回报这一点。我的问题是:如何像引发 Http 404 异常一样引发 Http 410 异常?我希望能够在任何地方提出这个例外,而不仅仅是在我的观点中。谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Django 不包含这样的机制,因为 gone 应该是正常的工作流程,而不是错误条件,但如果您不想将其视为返回响应,而是作为异常,只需实现 中间件。
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.
返回一个
HttpResponseGone
,它是HttpResponse
,在视图处理程序中。Return a
HttpResponseGone
, a subclass ofHttpResponse
, in your view handler.