Trying to figure out how to use decorator_from_middleware functionality

Viewed 1324

As the title states I want to use the 'decorator_from_middleware' function from here: https://docs.djangoproject.com/en/2.1/_modules/django/utils/decorators/

However I'm just confued on how to properly use it. I have my custom middleware class and all the normal middleware stuff set up. How would I incorperate this function to be able to use my middleware as a per view basis with the help of a decorator?

Example: Let's say I have some middleware class

class SimpleMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.

        return response

How would I use decorator_from_middleware(middleware_class): and apply it to a particular view?

1 Answers

Notice: Your middleware may not work, as documentation asserts that it needs to be compliant with old-style middleware methods. Check it out.

Assuming that this code is your views module:

from django.http import HttpResponse
from django.utils.decorators import decorator_from_middleware
from myapp.middleware import SimpleMiddleware

simple_decorator = decorator_from_middleware(SimpleMiddleware)

@simple_decorator 
def some_view(request):
    return HttpResponse("Hello World")

If you want to apply this to class based views, you need will need to decorate dispatch method. You may even write a mixin as such:

class SimpleMiddlewareMixin:
    @simple_decorator 
    def dispatch(*args, **kwargs):
        return super().dispatch(*args, **kwargs)

class MyClassBasedView(SimpleMiddlewareMixin, ListView):
    ...
Related