编程语言
首页 > 编程语言> > python – 忽略[Django]错误(外部IP):内部服务器错误

python – 忽略[Django]错误(外部IP):内部服务器错误

作者:互联网

我已经正确设置了ALLOWED_HOSTS,但我不断收到来自所有类型网站的请求,这些请求会导致发送“[Django] ERROR(外部IP):内部服务器错误”.

如何忽略此特定错误?

解决方法:

当Host:http标头与所需的ALLOWED_HOSTS设置不匹配时,Django的CommonMiddleware中会出现SuspiciousOperation异常.此异常未经过特殊处理,因此错误将通过日志记录系统传播.

您可以使用lborgav的答案以不同方式转移所有错误消息,但如果您只想捕获这一个错误,则可以设计自定义中间件.

以下代码片段是一个Middleware类,您可以将其添加到settings.py中的MIDDLEWARE_CLASSES以压缩此错误.

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

这必须在django.middleware.common.CommonMiddleware之前发生,因为您希望检测是否存在错误条件并在进入CommonMiddleware之前立即返回响应,这将生成异常.

# 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)

标签:python,django,django-settings
来源: https://codeday.me/bug/20190728/1565767.html