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

[매개 변수의 유무에 상관없이 사용할 수있는 파이썬 장식을 만드는 방법] (http://stackoverflow.com/questions/653368/how-to-create-a-python-decorator- -with-with-without-parametre) – DrTyrsa

답변

8

당신 필요한 것 다른 함수에 장식 기능 생성을 포장하기 : 난 강력하게 이것을 이해하려면이 문제에 전자 satis에서 답을 권 해드립니다

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

:

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 

이 다음과 같이 호출 할 수 있습니다 : How to make a chain of function decorators?

+0

이 코드 있는 그대로 작동하지 않습니다. '자체'는 정의되지 않았으며 제거해야합니다. –

+0

아 맞습니다. 업데이트 됨 - 감사합니다! –

관련 문제