在Django中基于类视图的参数的函数装饰器 [英] Function decorators with parameters on a class based view in Django
本文介绍了在Django中基于类视图的参数的函数装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
官方文档解释如何装饰基于类的视图,但是我找不到有关如何向装饰器提供参数的任何信息。
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想要实现类似于
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):
....
如何处理这样的情况?
推荐答案
@method_decorator
将一个函数作为参数。如果要传递带参数的装饰器,则只需要:
@method_decorator
takes a function as parameter. If you want to pass a decorator with parameters, you only need to:
- 评估decorator-creator函数中的参数。 >
- 将评估值传递给
@method_decorator
。
- Evaluate the parameters in the decorator-creator function.
- Pass the evaluated value to
@method_decorator
.
在显式的Python代码中,这将是:
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):
...
这篇关于在Django中基于类视图的参数的函数装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文