سؤال

I've setup my ALLOWED_HOSTS properly but I keep getting requests from all types of sites that cause this '[Django] ERROR (EXTERNAL IP): Internal Server Error' to be sent out.

How can I ignore this particular error?

هل كانت مفيدة؟

المحلول

A SuspiciousOperation exception is raised in Django's CommonMiddleware when the Host: http header doesn't match the required ALLOWED_HOSTS settings. This exception is not treated specially, so errors are propagated through the logging system.

You can use the answer by lborgav to divert all error messages differently, but if you just want to just catch this one error you can design a custom middleware.

The following snippet is a Middleware class which you can add to MIDDLEWARE_CLASSES in settings.py to squash just this error.

MIDDLEWARE_CLASSES = [
    'myapp.middleware.SquashInvalidHostMiddleware',
    ....
]

This must occur before django.middleware.common.CommonMiddleware, since you want to detect the presence of the error condition and return a response immediately before progressing to the CommonMiddleware which would generate an exception.

# myapp/middleware/__init__.py

from django.core.exceptions import SuspiciousOperation
from django.views.defaults import server_error


class SquashInvalidHostMiddleware(object):
    """
    Middleware class to squash errors due to suspicious Host: headers.
    """

    def process_request(self, request):
        """
        Check for denied Hosts.
        """

        try:
            # Attempt to obtain Host: from http header.  This may elicit a
            # SuspiciousOperation if Host: doesn't match ALLOWED_HOSTS.
            # Unceremoniously squash these errors to prevent log emails,
            # diverting straight to 500 page.

            request.get_host()
        except SuspiciousOperation:
            return server_error(request)

نصائح أخرى

In your LOGGING configuration you can override handler class

'handlers': {
    'mail_admins': {
    'level': 'ERROR',
    'class': 'django.utils.log.MyAdminEmailHandler',
    'include_html': True,
    }
},

Now you can write your class MyAdminEmailHandler. Check its code in AdminEmailHandler

In emit function, just get rid of report if (request.META.get('REMOTE_ADDR') not in settings.INTERNAL_IPS)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top