gpt4 book ai didi

python - Django - 在某些情况下使用中间件来阻止调试数据

转载 作者:行者123 更新时间:2023-12-04 01:11:02 25 4
gpt4 key购买 nike

我在开发环境中以 Debug模式使用 Django。

当某些 View 失败时,它会返回调试页面(不是 debug_toolbar,只是包含已安装应用列表、环境变量、堆栈跟踪等的页面)

在我的中间件中,在某些情况下(特定 URL、特定用户……)我想删除这些数据并只返回原始响应。我应该怎么做?

目前我最好的想法是:

response.data = {}
return response

但我不确定这样做是否正确,是否涵盖所有情况等。我只是想在某些情况下使用中间件来控制并避免为它们使用 DEBUG 模式。

最佳答案

您可以使用异常中间件。 See Django docs了解更多信息。

下面是异常中间件的示例实现:

class ExceptionHandlerMiddleware:
def __init__(self, get_response):
# if DEBUG is False we do not need this middleware
if not settings.DEBUG:
raise MiddlewareNotUsed
self.get_response = get_response


def __call__(self, request):
return self.get_response(request)


def process_exception(self, request, exception):
if request.user.is_authenticated: #any custom logic based on request and/or exception
#returning None kicks in default exception handling
#i.e. it will show full debug info page if settings.DEBUG is True
return None

else:
#returning HttpResponse will force applying template response and response
#middleware and the resulting response will be returned to the browser
return HttpResponse('Something went wrong')

从 Django 3.1 开始,您还可以通过定义 DEFAULT_EXCEPTION_REPORTER 来使用自定义错误报告器类。环境。自定义错误报告器类需要继承自django.views.debug.ExceptionReporter你可以覆盖 get_traceback_data()实现自定义逻辑。 See Django docs了解更多信息。

关于python - Django - 在某些情况下使用中间件来阻止调试数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64829320/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com