5
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)
2
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)
- [Django]-How to use date based views in Django
- [Django]-Replace "tzinfo" and print with localtime amends six minutes