Function decorators with parameters on a class based view in Django

送分小仙女□ 提交于 2019-12-04 16:49:21

问题


The official documentation explains how to decorate a class based view, however I could not find any information on how to provide parameters to the decorator.

I would like to achieve something like

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

which should be equivalent to

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

How do I deal with such cases?


回答1:


@method_decorator takes a function as parameter. If you want to pass a decorator with parameters, you only need to:

  • Evaluate the parameters in the decorator-creator function.
  • Pass the evaluated value to @method_decorator.

In explicit Python code this would be:

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

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

So, using the syntactic sugar completely:

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


来源:https://stackoverflow.com/questions/27862660/function-decorators-with-parameters-on-a-class-based-view-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!