【问题标题】:Switch on django error page only for admins when debug = False当 debug = False 时,仅为管理员打开 django 错误页面
【发布时间】:2013-09-29 11:51:39
【问题描述】:

它是以下内容的副本: is there a way to show the Django debug stacktrace page to admin users even if DEBUG=False in settings? 但没有答案

当 debug=False 时,如何仅对管理员用户显示带有堆栈跟踪的 django 错误页面。 我不想使用哨兵。

【问题讨论】:

  • @karthikr 你读过链接了吗?我没有看到任何回答他的问题的东西,至少我是如何解释的
  • 认真的吗?链接中的标题和第一行还不够看懂吗??
  • 谢谢,但我在第一行找不到答案。当 debug 仅适用于管理员时,我需要实时查看错误。

标签: python django


【解决方案1】:

我找到了答案

在 urls.py 中添加

handler404 = 'site_utils.handler404'

在 urls.py 所在的同一文件夹中创建 site_utils.py 并添加到那里

from django.http import HttpResponseRedirect,  HttpResponsePermanentRedirect
import sys
from django.views.debug import technical_404_response, technical_500_response 
def handler404(request):
    if (request.user.is_active and request.user.is_staff) or request.user.is_superuser:
        exc_type, exc_value, tb = sys.exc_info()
        return technical_404_response(request, exc_value)
    else:
        return  HttpResponsePermanentRedirect("/")

【讨论】:

    【解决方案2】:

    您要求做的事情非常不安全,这可能是 Django 没有提供默认方法来执行此操作的原因。在生产应用上运行 DEBUG 可以将您的 SETTINGS 文件(包括 API 令牌)暴露给全世界。

    如果你真的想这样做,看看django.views.debug.technical_500_response 并写一个custom exception handler 从那里返回值。

    【讨论】:

    • 怎么样?在默认的 Django 500 错误页面中,我看到的只是“SECRET_KEY u'************************'”
    • 看来我弄错了。默认情况下,Django 会保护您不发布您的密钥,以及它deems inappropriate to display 的设置。将任何形式的调试信息传递给任何客户端仍然是一个非常糟糕的主意。例如,调试信息可以显示您的 DATABASES 设置,这可能会导致安全漏洞。您应该改用logging
    【解决方案3】:

    这是 Django 3.2 的版本。

    将以下文件保存在例如mysite/debug.py

    from django.utils.deprecation import MiddlewareMixin
    from django.views.debug import technical_500_response
    import sys
    
    class UserBasedExceptionMiddleware(MiddlewareMixin):
        def process_exception(self, request, exception):
            if request.user.is_superuser:
                return technical_500_response(request, *sys.exc_info())
    

    如下更新您的mysite/settings.py

    MIDDLEWARE_CLASSES = (
      ... whatever ...
      'mysite.debug.UserBasedExceptionMiddleware',
    )
    

    【讨论】:

      猜你喜欢
      • 2018-09-26
      • 2020-06-25
      • 1970-01-01
      • 2021-08-13
      • 2016-10-08
      • 1970-01-01
      • 2021-11-05
      • 2019-09-29
      • 2013-12-03
      相关资源
      最近更新 更多