簡體   English   中英

在Django中為類方法制作裝飾器

[英]Making decorator for class method in Django

我已經建立了staff_member_required用於基於函數的視圖,但是找不到用於類方法。 好吧,我試圖為基於類的視圖編寫裝飾器:

from django.contrib.admin.views.decorators import staff_member_required
from django.views.generic import View

def cls_method_staff_member_decorator(func):
    def wrapper(self, request, *args, **kwargs):
        return staff_member_required(view_func=func)(request, *args, **kwargs)
    return wrapper

class SetUserData(View):
    http_method_names = ['get', ]

    @cls_method_staff_member_decorator
    def get(self, request, user_id):
        # ... some actions with data

但是通過runserver命令啟動服務器后,出現錯誤:

/ en-us / user / userdata / 7 / get()處的TypeError恰好接受3個參數(給定2個)

我該如何解決?

您需要使用method_decorator裝飾dispatch方法。

class SetUserData(View):
    @method_decorator(cls_method_staff_member_decorator)
    def dispatch(self, *args, **kwargs):
        return super(SetUserData, self).dispatch(*args, **kwargs)

在這里解釋

或者用urls裝飾:

urlpatterns = patterns('',
    ...
    (r'^your_url/', cls_method_staff_member_decorator(SetUserData.as_view())),
    ...
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM