How to obtain a plain text Django error page

后端 未结 5 2161
独厮守ぢ
独厮守ぢ 2020-12-06 02:05

During development, I am running Django in Debug mode and I am posting data to my application using a text mode application. Ideally, I need to receive a plain text response

5条回答
  •  时光说笑
    2020-12-06 02:41

    This is an improvement on Yuji's answer, which provides a stacktrace, more instructions (for us django newbies) and is simpler.

    Put this code in a file somewhere in your application, e.g. PROJECT_ROOT/MAIN_APP/middleware/exceptions.py, and make sure you have an empty __init__.py in the same directory.

    import traceback
    from django.http import HttpResponse
    
    class PlainExceptionsMiddleware(object):
        def process_exception(self, request, exception):
            return HttpResponse(traceback.format_exc(exception), content_type="text/plain", status=500)
    

    Now edit your settings.py and find MIDDLEWARE_CLASSES = (. Add another entry so it is like this:

    MIDDLEWARE_CLASSES = (
        # (all the previous entries)
    
        # Plain text exception pages.
        'MAIN_APP.middleware.exceptions.PlainExceptionsMiddleware',
    )
    

    Restart django and you are good to go!

    User-agent aware formatting.

    If you're like me and developing an app and a website both backed by django, you probably want to show plain text error pages to the app, and the nice formatted ones to the browser. A simple way to to that is to check the user agent:

    import traceback
    from django.http import HttpResponse
    
    class PlainExceptionsMiddleware(object):
        def process_exception(self, request, exception):
            if "HTTP_USER_AGENT" in request.META and "chrome" in request.META["HTTP_USER_AGENT"].lower():
                return
            return HttpResponse(traceback.format_exc(exception), content_type="text/plain", status=500)
    

提交回复
热议问题