[PYTHON] Django Server Error (500) Strategy [2019 Adcare]

This is my first participation in the Advent calendar. I look forward to working with you.

Overview

My hobby is Pythonista. I got started with Django this year and created a website. This time, I'm going to write a rough strategy for Django beginners who are the same as me, about the things that will first bother me and make a heartbreaking scream. It is ** Server Error (500) **.

Server Error (500)

At this time, try to display the error content on the screen, output the log, or notify Slack of the error content even temporarily.

Server Error (500) occurred

I'm a beginner, so I just added a bug to the views.py method.

views.py


def index(request):

    aaaa  #← Sudden aaaa

    return HttpResponse('<p>Hello world.</p>')

If DEBUG in settings.py is True, you will get a clear error message like this:

わかりやすいエラーメッセージ

However, as soon as you change DEBUG to False, you will see a Server Error (500) from the parent's face.

Server Error (500)

This screen is displayed by handler500

The handler when a server error occurs is [django.conf.urls. \ _ \ _ Init \ _ \ _. Py](https://github.com/django/django/blob/master/django/conf/urls/ It was in init.py # L9).

django/conf/urls/__init__.py


handler500 = defaults.server_error

This handler500 is executed when an error occurs on the server. That is, the defaults.server_error function is executed. If you look inside django.views.defaults.server_error, you can see the process displaying this screen. It is described.

django/views/defaults.py


@requires_csrf_token
def server_error(request, template_name=ERROR_500_TEMPLATE_NAME):
    """
    500 error handler.
    Templates: :template:`500.html`
    Context: None
    """

    #Omission

        return HttpResponseServerError(
            ERROR_PAGE_TEMPLATE % {'title': 'Server Error (500)', 'details': ''},
            content_type='text/html',
        )

Then, the function to be assigned to handler500 should be a different function instead of defaults.server_error.

Assign a different function to handler500

  1. Define your own server_error function
  2. Assign it to handler500

Try defining your own server_error in views.py. Because the original one is defined in django.views.defaults.

views.py


@requires_csrf_token
def my_customized_server_error(request, template_name='500.html'):
    return HttpResponseServerError('<h1>Server Error (500)That's right</h1>')

The assignment to handler500 is done in urls.py. The original handler500 definition is in django.conf.urls.

urls.py


handler500 = views.my_customized_server_error

I was able to change the Server Error screen.

django3.jpg

After that, you can write whatever you like in my_customized_server_error.

Example of my_customized_server_error

This is the code that normally prints.

views.py


@requires_csrf_token
def my_customized_server_error(request, template_name='500.html'):
    import traceback
    print(traceback.format_exc())
    return HttpResponseServerError('<h1>Server Error (500)That's right</h1>')

This code gives the same error screen as when DEBUG = True. This is easy to see, isn't it? (Small feeling)

views.py


@requires_csrf_token
def my_customized_server_error(request, template_name='500.html'):
    import sys
    from django.views import debug
    error_html = debug.technical_500_response(request, *sys.exc_info()).content
    return HttpResponseServerError(error_html)

Code that brings up the default Server Error (500) screen as seen from the parent's face. You can use the django.views.defaults.server_error you found earlier and you're good to go.

views.py


@requires_csrf_token
def my_customized_server_error(request, template_name='500.html'):
    from django.views.defaults import server_error
    return server_error(request, template_name)

Code that skips notifications to everyone's favorite Slack.

views.py


@requires_csrf_token
def my_customized_server_error(request, template_name='500.html'):
    import requests
    import json
    import traceback
    requests.post(
        'Your Slack Webhook URL',
        data=json.dumps({
            'text': '\n'.join([
                f'Request uri: {request.build_absolute_uri()}',
                traceback.format_exc(),
            ]),
            'username': 'Django error notification',
            'icon_emoji': ':jack_o_lantern:',
        })
    )
    return HttpResponseServerError('<h1>Server Error (500)That's right</h1>')

I flew. Since the directory structure of my place is displayed, I will put a mosaic.

django4.jpg

Tomorrow's Django Advent Calendar is @boxboxbax. Good luck!

Recommended Posts

Django Server Error (500) Strategy [2019 Adcare]
Django2.2 SQLite3 version error
Django settings.py SECRET_KEY error
Error: 500 (Internal Server Error) Jupyter lab
[Django] Create your own 403, 404, 500 error pages