[英]How to add/modify an attribute to a Django class based view from a Decorator?
I have a class-based Django view as follows: 我有一个基于类的Django视图,如下所示:
class myView(TemplateView):
template_name = 'templateFile.html'
request = None
@method_decorator(request_management)
def dispatch(self, request, *args, **kwargs):
...
return super(myView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, *args, **kwargs):
ctx = super(newFeatures, self).get_context_data(**kwargs)
ctx['requester'] = self.requester
return ctx
In my request_management decorator, I would like to set the value of myView.request to the argument that was passed into the dispatch function. 在我的request_management装饰器中,我想将myView.request的值设置为传递给调度函数的参数。 So I do something like this: 所以我做这样的事情:
def request_management(function):
@wraps(function)
def decorator(*args, **kwargs):
logger.debug("request = %s" % str(args[0]))
# I want to say here something like:
# self.request = args[0]
# but of course, "self" is not defined in this context.
return function(*args, **kwargs)
return decorator
But from within the decorator, I can't access the "self" instance of the decorated method. 但是从装饰器内部,我无法访问装饰方法的“自身”实例。 How can I get that instance and attach an attribute named request to it so that I can use that attribute in other methods of that instance? 如何获得该实例并将一个名为request的属性附加到该实例,以便可以在该实例的其他方法中使用该属性?
The purpose of method_decorator
is to convert a function decorator into a method decorator . method_decorator
的目的是将函数装饰器转换为方法装饰器 。 But since you're writing your own decorator, you can just go ahead and write it as an actual method decorator: 但是由于您正在编写自己的装饰器,因此可以继续将其编写为实际的方法装饰器:
class myView(TemplateView):
@request_management
def dispatch(self, request, *args, **kwargs):
...
return super(myView, self).dispatch(request, *args, **kwargs)
def request_management(method):
@wraps(method)
def decorator(self, request, *args, **kwargs):
logger.debug("request = %s" % str(request))
self.request = request
return method(self, request, *args, **kwargs)
return decorator
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.