为什么 Django 的平面页面允许记录 404 错误?

发布于 2024-12-08 21:14:08 字数 354 浏览 1 评论 0原文

我注意到 Django 的 flatpages 应用程序有一件有趣的事情:它允许 core/handlers/base.py 记录警告 Not Found: $page。因此,我的 Sentry 日志充满了合法页面和工作页面的 404 错误。之所以会发生这种情况,是因为 Django 首先记录了 404,然后返回了一个 HttpResponseNotFound 对象,然后 Flatpages 中间件启动并返回了正确的 200 响应。

我可以认为这是 Django 中的错误吗?我的理由是,有效的平面页面不是缺失页面,因此不应记录 404 消息。是否有其他方法可以捕获 404 而不将其记录为丢失?

A funny thing I've noticed about Django's flatpages app: it allows core/handlers/base.py to log a warning Not Found: $page. As a result of that, my Sentry logs are full with 404s for legitimate and working pages. It seems to happen because first Django logs a 404, then it returns a HttpResponseNotFound object and then the flatpages middleware kicks in and returns a proper 200 response.

Is this something I could consider a bug in Django? My reasoning is that a valid flatpage is not a missing page and thus shouldn't log a 404 message. Isn't there an other way to catch a 404 without logging it as missing?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

木有鱼丸 2024-12-15 21:14:09

我认为解决您问题的方法很简单:只需将 Sentry404CatchMiddleware 重新排序到 MIDDLEWARES 设置的顶部即可。至少,它应该位于 flatpages 中间件之上。

为了解释发生了什么,理解 会很有帮助中间件的执行顺序。我猜您遵循了 Sentry 文档 并将其放置在底部。这使得它成为第一个被执行的中间件。如果传入的请求不匹配 URL 模式,Django 会引发 404 错误,Sentry 中间件会记录该错误。但是 Django 然后运行其他中间件,而 flatpages 中间件会查找匹配的页面是否存在,并实际替换响应。

如果将 Sentry 中间件移至顶部,则只会记录整个中间件堆栈中冒泡的 404 错误,这可能正是您想要的。

I think the solution to your problem is easy: just re-order the Sentry404CatchMiddleware to the top of your MIDDLEWARES setting. At the very least, it should be above the flatpages middleware.

To explain what's going on, it's helpful to understand the order in which middlewares are executed. I'm guessing you followed the Sentry docs and placed it at the bottom. That makes it the first middleware to be executed. If a request comes in for an unmatched URL pattern, Django raises a 404 and the Sentry middleware logs it. But Django then runs through the other middlewares, and the flatpages middleware does it's thing where it looks up if a matching page exists, and actually replaces the response.

If you move the Sentry middleware to the top, only 404 errors that bubble all the way through the middleware stack will get logged, which is likely what you want.

花开浅夏 2024-12-15 21:14:09

这不是一个错误,而是 django flatpages 应用程序的工作方式:它的中间件在 url 的 404 之后启动。这就是为什么你的哨兵充满了 404。

考虑不在哨兵中注册404。 :/我在这里看不到任何其他方式。

可能还有另一种解决方案:不要使用中间件,而是尝试在urlpatterns的末尾包含flatpages.urls

It's not a bug, it's the way that django flatpages app work: its middleware kicks in after 404 from urls. That's why your sentry is full of 404s.

Consider not registering 404 in sentry. :/ I dont see any other way here.

There might be another solution: instead of using middleware try to include flatpages.urls at end of your urlpatterns.

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