0

我有装饰器的问题。我正在尝试使用可选参数编​​写自己的装饰器。

这就是它现在的完成方式:

def CheckPremissions(manager=1):
    def wrap(func):
        def wrapper(request, *args, **kwargs):
            if request.user.is_anonymous():
                return HttpResponseRedirect(reverse('login'))

            logged_user = getRelatedWorker(request.user)

            if (logged_user == None):
                return HttpResponseRedirect('accounts/no_worker_error.html')

            if self.manager != 0:
                try:
                    dzial = Dzial.objects.get(kierownik=logged_user)
                except Dzial.DoesNotExist:
                    isManager = False
                else:
                    isManager = True

                if not isManager:
                    return HttpResponseRedirect('accounts/denied_logged.html')

            return func(request, *args, **kwargs)
        return wrapper
    return wrap

代码看起来不错(对我来说),但是当我使用装饰器时,出现以下错误:

Environment:

    Request Method: GET
    Request URL: http://127.0.0.1:8080/applications/show

    Django Version: 1.4.1
    Python Version: 2.7.3


Traceback:
    File "/home/marcin/projekt/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
      188.                 response = middleware_method(request, response)
    File "/home/marcin/projekt/lib/python2.7/site-packages/django/middleware/common.py" in process_response
      94.         if response.status_code == 404:

    Exception Type: AttributeError at /applications/show
    Exception Value: 'function' object has no attribute 'status_code'

我究竟做错了什么?

4

1 回答 1

7

我怀疑您错误地应用了装饰器。您需要调用它来指定manager参数:

@CheckPremissions()
def someview(request):
    pass

或明确指定它:

@CheckPremissions(manager=0)
def someview(request):
    pass

你的装饰器也有不同的问题;self.manager你在代码中提到:

if self.manager != 0:

但这不是实例,也没有self参数。我想你的意思是:

if manager:

(您可以通过将其视为布尔值来测试变量是否为非零)。哦,你可能想修正装饰器的拼写;你可能的意思是CheckPermissions。:-)

于 2012-09-12T10:57:36.893 回答