简体   繁体   中英

How to add/modify an attribute to a Django class based view from a Decorator?

I have a class-based Django view as follows:

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. 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?

The purpose of method_decorator is to convert a function decorator into a 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM