我正在从另一个应用程序中调用 Django。
在调试时,如果发生 Django 异常,则会拾取 (html) 响应正文,然后将其包装在调用应用程序中生成的异常中。
这使得确定问题所在变得非常痛苦,因为我需要费力地研究 CSS、Html、Js 等。
有没有办法让 Django 只以纯文本形式输出异常消息和堆栈跟踪?
最佳答案
您可以编写自己的异常处理中间件类。请参阅 process_exception
middleware method 的文档:
process_exception(self, request, exception)
request
is anHttpRequest
object.exception
is anException
object raised by the view function.Django calls
process_exception()
when a view raises an exception.process_exception()
should return eitherNone
or anHttpResponse
object. If it returns anHttpResponse
object, the response will be returned to the browser. Otherwise, default exception handling kicks in.
所以我认为你需要写这样的东西:
import traceback
from django.http import HttpResponse
class PlainTextExceptionMiddleware(object):
def process_exception(self, request, exception):
return HttpResponse(traceback.format_exc(), "text/plain")
然后将该类添加到您的 MIDDLEWARE_CLASSES
设置中。
关于python - 禁用 Django 异常格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15899074/