我有装饰器的问题。我正在尝试使用可选参数编写自己的装饰器。
现在就是这样做的:
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'
我做错了什么?
答案 0 :(得分:7)
我怀疑你错误地应用装饰器。您需要调用它来指定manager
参数:
@CheckPremissions()
def someview(request):
pass
或明确指定:
@CheckPremissions(manager=0)
def someview(request):
pass
你的装饰师也有不同的问题;您在代码中引用self.manager
:
if self.manager != 0:
但这不是实例,并且没有self
参数。我想你的意思是:
if manager:
(通过将变量视为布尔值,可以测试变量为非零)。哦,你可能想修复装饰的拼写;你的意思可能是CheckPermissions
。 : - )