2012-01-27 41 views
3

我有以下修饰器和视图哪些工作正常。Django添加可选参数给修饰器

装饰

def event_admin_only(func): 
    """ 
    Checks if the current role for the user is an Event Admin or not 
    """ 
    def decorator(request, *args, **kwargs): 
     event = get_object_or_404(Event, slug=kwargs['event_slug']) 

     allowed_roles = [role[1] for role in Role.ADMIN_ROLES] 

     # get user current role 
     current_role = request.session.get('current_role') 

     if current_role not in allowed_roles: 
      url = reverse('no_perms') 
      return redirect(url) 
     else:  
      return func(request, *args, **kwargs) 
    return decorator 

查看

@event_admin_only 
def event_dashboard(request, event_slug: 

但我怎么能修改我的装饰等,它需要在一个额外的参数,像这样:

@event_admin_only(obj1,[...]) 
def event_dashboard(request, event_slug: 
+1

可能重复[如何创建一个可以使用或不使用参数的Python装饰器?](http://stackoverflow.com/questions/653368/how-to-create-a-python-decorator-可以使用的,无论是否带参数) – DrTyrsa 2012-01-27 07:47:47

回答

8

你需要包裹中的另一功能的装饰功能创建:

def the_decorator(arg1, arg2): 

    def _method_wrapper(view_method): 

     def _arguments_wrapper(request, *args, **kwargs) : 
      """ 
      Wrapper with arguments to invoke the method 
      """ 

      #do something with arg1 and arg2 

      return view_method(request, *args, **kwargs) 

     return _arguments_wrapper 

    return _method_wrapper 

这可以被称为是这样的:

@the_decorator("an_argument", "another_argument") 
def event_dashboard(request, event_slug): 

我强烈建议从E-SATIS的答案对这个问题理解这一点: How to make a chain of function decorators?

+0

此代码不起作用,'自我'未定义,需要删除。 – 2015-06-14 20:07:44

+0

啊是的。更新 - 谢谢! – 2015-06-15 08:16:59