2015-11-02 100 views
0

我爲我的服務器使用Django,並在單個Django安裝中託管多個域。Django創建自定義裝飾器

我目前正在對我的視圖中的每個傳入請求執行檢查,以查看是否訪問www.aaa.com或www.bbb.com。

我想將此檢查放在裝飾器中,原因很明顯,但是至今未能實現此功能。 :(

我的主頁查看:

def index(request, value=None): 

    # Here I check the domain the user wants to visit. 
    if request.META['HTTP_HOST'] != "www.aaa.com": 
     raise Http404("Requested website is not availble on the server.") 

    # Code here 

    # Load HTML 
    return render(request, 'frontend/homepage.html'}) 

登錄觀點:

def login_view(request): 

     # Check the domain the user wants to visit. 
     if request.META['HTTP_HOST'] != "www.aaa.com": 
      raise Http404("Requested website is not availble on the server.") 

     # Code here 

     # Load HTML 
     return render(request, 'frontend/login.html') 

我的裝飾企圖自動化HTTP_HOST檢查:

def checkClient(func): 
     def dosomething(request): 
      if request.META['HTTP_HOST'] != "www.aaa.com": 
       raise Http404("This domain is not hosted on this server.") 
      return request 
     return dosomething 

所以我試圖寫我自己的裝飾,但它不工作。 :(

回答

2

你是八九不離十。而不是返回request的,你dosomething視圖應該調用函數func它是裝飾。

其次,內在功能dosomething應該處理*args**kwargs,這樣就可以裝飾觀點,採取位置和關鍵字參數,

def checkClient(func): 
    def dosomething(request, *args, **kwargs): 
     if request.META['HTTP_HOST'] != "www.aaa.com": 
      raise Http404("This domain is not hosted on this server.") 
     return func(request, *args, **kwargs) 
    return dosomething 
+0

謝謝,作品!:D –