3 回答
TA贡献1840条经验 获得超5个赞
请不要替换中间件或做一些其他奇怪的事情。非常简单:DisallowedHost() 由调用get_host()请求对象的第一个事物引发。通常,这是一个中间件,因为在请求/响应周期中过早执行它会导致无法关闭或自定义。
因此,首先将您的自定义中间件注入链中并短路那里的东西:
# File: main.middleware
from django.shortcuts import redirect
from django.core.exceptions import DisallowedHost
class FriendlyDisallowedHost:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request, *args, **kwargs):
try:
checkhost = request.get_host()
except DisallowedHost:
return redirect("http://localhost/")
return self.get_response(request)
设置:
MIDDLEWARE = [
"main.middleware.FriendlyDisallowedHost",
# ... rest of middleware
]
TA贡献1804条经验 获得超7个赞
因为 Django 将在调用您的视图之前拦截请求并引发此异常,所以您应该使用自定义错误视图来覆盖默认错误视图来处理此类错误
在您的应用程序视图中,编写您想要处理的处理程序DisallowedHost
from django.views.defaults import bad_request as default_bad_request
from django.core.exceptions import DisallowedHost
from django.http import HttpResponse
def my_bad_request_handler(request, exception=None, **kwargs):
if isinstance(exception, DisallowedHost):
return HttpResponse("This server is not configured for this hostname", status=400)
# if it's some other kind of bad request, use Django's default handler
return default_bad_request(request, exception, **kwargs)
然后在 URLConf 中将 400 处理程序设置为您的自定义视图:
handler400 = 'mysite.views.my_bad_request_handler'
TA贡献2080条经验 获得超4个赞
您可以为此使用自定义中间件。
为此,通过子类化CommonMiddleware
--(Doc)类并重写process_request(...)
--(Doc)方法来创建自定义中间件
# some_place/some_module.py
from django.middleware.common import CommonMiddleware
from django.core.exceptions import DisallowedHost
from django.http.response import HttpResponse
from django.shortcuts import render
class CustomCommonMiddleware(CommonMiddleware):
def process_request(self, request):
try:
return super().process_request(request)
except DisallowedHost:
return render(request, 'something.html')
然后,将中间件替换为-(Doc)设置django.middleware.common.CommonMiddleware
中新创建的自定义类,如下所示:MIDDLEWARE
# some_place/some_module.py
from django.middleware.common import CommonMiddleware
from django.core.exceptions import DisallowedHost
from django.http.response import HttpResponse
from django.shortcuts import render
class CustomCommonMiddleware(CommonMiddleware):
def process_request(self, request):
try:
return super().process_request(request)
except DisallowedHost:
return render(request, 'something.html')
添加回答
举报