How to obtain a plain text Django error page

后端 未结 5 2143
独厮守ぢ
独厮守ぢ 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:20

    Building off of Timmmm's answer, I had to make several modifications for it to work in Django 3.1:

    Create a file somewhere in your application, such as YOUR_APP_NAME/middleware/exceptions.py and paste the following code:

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

    It is not necessary to create an __init__.py file in the middleware folder.

    In settings.py, add the following item to the end of the MIDDLEWARE variable, so that it looks like:

    MIDDLEWARE = [
        # ...
        'YOUR_APP_NAME.middleware.exceptions.PlainExceptionsMiddleware'
    ]
    

    Now, if "HTTP_USER_AGENT" and "chrome" are in the request header, this middleware doesn't do anything, so Django returns an HTML response as usual. Otherwise, it returns a plain-text representation of the error as a response (e.g., ValueError("Field 'id' expected a number but got 'undefined'.")) and prints out the traceback to the Django console, as Django normally would. Of course, you can instead return the full traceback as your response.

提交回复
热议问题