2012-01-27 20 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

答えて

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): 

私は強くこれを理解するために、この質問に電子サティスからの回答をお勧めします: How to make a chain of function decorators?

+0

このコードそのままでは機能しません。「自己」は定義されておらず、削除する必要があります。 –

+0

ああ、そうです。更新しました - ありがとう! –

関連する問題