【问题标题】:Function decorators with parameters on a class based view in DjangoDjango中基于类的视图上带有参数的函数装饰器
【发布时间】:2015-03-07 21:32:54
【问题描述】:

官方documentation 解释了如何装饰基于类的视图,但是我找不到任何关于如何向装饰器提供参数的信息。

我想实现类似的目标

class MyView(View):
    @method_decorator(mydecorator, some_parameters)
    def dispatch(self, *args, **kwargs):
        return super(MyView, self).dispatch(*args, **kwargs)

应该等价于

@mydecorator(some_parameters)
def my_view(request):
    ....

我该如何处理这种情况?

【问题讨论】:

标签: django python-decorators


【解决方案1】:

@method_decorator 将函数作为参数。如果你想传递一个带参数的装饰器,你只需要:

  • 评估 decorator-creator 函数中的参数。
  • 将评估值传递给@method_decorator

在显式 Python 代码中,这将是:

decorator = mydecorator(arg1, arg2, arg...)
method_dec = method_decorator(decorator)

class MyClass(View):
    @method_dec
    def my_view(request):
        ...

所以,完全使用语法糖:

class MyClass(View):
    @method_decorator(mydecorator(arg1, arg2, arg...))
    def my_view(request):
        ...

【讨论】:

    猜你喜欢
    • 2020-07-07
    • 2023-02-07
    • 2017-03-08
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    • 1970-01-01
    相关资源
    最近更新 更多