【问题标题】:Making decorator for class method in Django在 Django 中为类方法制作装饰器
【发布时间】:2015-03-17 06:13:28
【问题描述】:

我为基于函数的视图创建了 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 个)

我该如何解决?

【问题讨论】:

    标签: python django python-2.7 decorator python-decorators


    【解决方案1】:

    您需要使用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)
    

    解释here

    或者用urls装饰:

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

    【讨论】:

      猜你喜欢
      • 2014-02-18
      • 2016-10-14
      • 2021-04-12
      • 1970-01-01
      • 2014-01-14
      • 2020-01-11
      • 1970-01-01
      • 2017-07-28
      • 1970-01-01
      相关资源
      最近更新 更多