2015-11-02 90 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 –