【问题标题】:Django create custom decoratorDjango 创建自定义装饰器
【发布时间】:2015-11-02 16:16:45
【问题描述】:

我将 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

所以我尝试编写自己的装饰器,但它不起作用。 :(

【问题讨论】:

    标签: django decorator


    【解决方案1】:

    你已经很接近了。你的dosomething 视图应该调用它正在装饰的函数func,而不是返回request

    其次,内部函数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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-07
      • 2020-06-02
      • 1970-01-01
      • 2013-02-06
      • 2011-10-16
      • 2015-03-25
      相关资源
      最近更新 更多