如何在 Django 中引发 410 错误

发布于 2024-10-03 08:53:23 字数 643 浏览 0 评论 0原文

我想为我的一些 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

诠释孤独 2024-10-10 08:53:23
from django.http import HttpResponse
return HttpResponse(status=410)
from django.http import HttpResponse
return HttpResponse(status=410)
梦幻的味道 2024-10-10 08:53:23

Django 不包含这样的机制,因为 gone 应该是正常的工作流程,而不是错误条件,但如果您不想将其视为返回响应,而是作为异常,只需实现 中间件

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

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
泪是无色的血 2024-10-10 08:53:23

返回一个 HttpResponseGone,它是 HttpResponse,在视图处理程序中。

Return a HttpResponseGone, a subclass of HttpResponse, in your view handler.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文