Django在装饰器中查看参数

时间:2013-02-16 09:15:19

标签: django python-2.7 django-views

我有一个函数生病,喜欢与装饰有争论的装饰者,请任何人帮助这个

def get_permission(request,permission_level):
    if has_permission(request,permission_level):#this is another function
        #my work will be done here
    else:
        raise Http404

而且我只想在我的视图中使用它

@get_permission(permission_level)
def a_view(request)

请问有人帮忙吗?感谢

1 个答案:

答案 0 :(得分:0)

查看django/contrib/auth/decorators.py,例如

from functools import wraps
from django.utils.decorators import available_attrs

def get_permission(permission_level):
    def decorator(func):
        @wraps(func, assigned=available_attrs(func))
        def _wrapped(request, *args, **kwargs):
            if has_permission(request, permission_level): 
                'special logic goes here...'
                return func(request, *args, **kwargs)
            else:
                raise Http404

检查How to make a chain of function decorators?PEP 318是否有编写装饰器。

如果装饰者只是检查权限以确定要返回的结果,您可以直接利用django/contrib/auth/decorators.py中的user_passes_testpermission_required