2012-04-04 56 views
3

現在我使用這個應用程序的權限檢查permision:django-rules如何寫的一類基於視圖中的裝飾 - 基於對象的視圖

然而,至今尚未更新了一年多並且沒有「新」(自django 1.3)基於類的視圖的裝飾器。我希望能夠在urls.py像這樣使用:

url(r'^casos/(?P<pk>\d+)/editar/$', rules_permission_required('lawsuits.logical_check', raise_exception=True)(CaseUpdateView.as_view()), name='case_edit'), 

我無法弄清楚如何獲得從裝飾類基於視圖的對象。你們有什麼想法嗎?這是我到目前爲止:

from django.utils.decorators import available_attrs 
def rules_permission_required(perm, queryset=None, login_url=None, raise_exception=False): 
    def wrapper(view_func): 
     @wraps(view_func, assigned=available_attrs(view_func)) 
     def inner(request, *args, **kwargs): 
      #view_func is the class based view -> <function MyEditView at 0x94e54c4> 

      print view_func.get_object() # doesnt work 
      print view_func(request, *args, **kwargs).get_object() # doesnt work either 

      #any ideas? 

      if not request.user.has_perm(perm, obj=obj): 
       return redirect_to_login(request, login_url, raise_exception) 
      return view_func(request, *args, **kwargs) 
     return inner 
    return wrapper 

非常感謝提前!

回答

7

的調度()方法使用method_decoratorhttps://docs.djangoproject.com/en/dev/topics/class-based-views/#decorating-class-based-views

from django.utils.decorators import method_decorator 
class ClassBasedView(View): 
    @method_decorator(rules_permission_required) 
    def dispatch(self, *args, **kwargs): 
     return super(ClassBasedView, self).dispatch(*args, **kwargs) 

或者你可以裝點as_view類方法的輸出,無論是在您的網址配置(如上面的鏈接描述的),或者通過保存該實例放入一個變量中。

class ClassBasedView(View): 
    def dispatch(self, *args, **kwargs): 
     return super(ClassBasedView, self).dispatch(*args, **kwargs) 
class_based_view = rules_permission_required(ClassBasedView.as_view()) 

儘管我不太確定最後一個例子是否會導致線程安全問題(取決於Django如何處理實例)。最好的辦法可能是堅持method_decorator

0

我結束了使用一類裝飾

def rules_permission_required(perm, queryset=None, login_url=None, raise_exception=False): 

    def wrapper(cls):     
     def view_wrapper(view_func): 
      @wraps(view_func, assigned=available_attrs(view_func)) 
      def inner(self, request, *args, **kwargs): 
       # get object 
       obj = get_object_from_classbased_instance(
         self, queryset, request, *args, **kwargs 
        ) 

       # do anything you want 
      return inner 
     cls.dispatch = view_wrapper(cls.dispatch) 
     return cls 
    return wrapper 
+2

有人能解釋爲什麼切換到基於類的觀點是一種進步,當它過於複雜化這樣的事情。如果你問我,似乎是朝着錯誤的方向邁出的一步。 – fred 2014-01-10 14:34:19

相關問題