gpt4 book ai didi

python - 如何从装饰器向基于 Django 类的 View 添加/修改属性?

转载 作者:行者123 更新时间:2023-12-01 05:17:52 24 4
gpt4 key购买 nike

我有一个基于类的 Django View ,如下所示:

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

在我的 request_management 装饰器中,我想将 myView.request 的值设置为传递到调度函数中的参数。所以我做了这样的事情:

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

但是从装饰器内部,我无法访问装饰方法的“self”实例。如何获取该实例并向其附加一个名为 request 的属性,以便我可以在该实例的其他方法中使用该属性?

最佳答案

method_decorator 的目的是 convert a function decorator into a 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

关于python - 如何从装饰器向基于 Django 类的 View 添加/修改属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22903618/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com