3 回答

TA貢獻(xiàn)1840條經(jīng)驗(yàn) 獲得超5個(gè)贊
請不要替換中間件或做一些其他奇怪的事情。非常簡單:DisallowedHost() 由調(diào)用get_host()請求對象的第一個(gè)事物引發(fā)。通常,這是一個(gè)中間件,因?yàn)樵谡埱?響應(yīng)周期中過早執(zhí)行它會導(dǎo)致無法關(guān)閉或自定義。
因此,首先將您的自定義中間件注入鏈中并短路那里的東西:
# 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)
設(shè)置:
MIDDLEWARE = [
"main.middleware.FriendlyDisallowedHost",
# ... rest of middleware
]

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超7個(gè)贊
因?yàn)?Django 將在調(diào)用您的視圖之前攔截請求并引發(fā)此異常,所以您應(yīng)該使用自定義錯(cuò)誤視圖來覆蓋默認(rèn)錯(cuò)誤視圖來處理此類錯(cuò)誤
在您的應(yīng)用程序視圖中,編寫您想要處理的處理程序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 處理程序設(shè)置為您的自定義視圖:
handler400 = 'mysite.views.my_bad_request_handler'

TA貢獻(xiàn)2080條經(jīng)驗(yàn) 獲得超4個(gè)贊
您可以為此使用自定義中間件。
為此,通過子類化CommonMiddleware
--(Doc)類并重寫process_request(...)
--(Doc)方法來創(chuàng)建自定義中間件
# 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)設(shè)置django.middleware.common.CommonMiddleware
中新創(chuàng)建的自定義類,如下所示: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')
添加回答
舉報(bào)