Django custom decorator example

Django -- Posted on April 5, 2021

In the code you provided, you have defined a custom decorator dec, which prints a message before and after calling the decorated function. You have applied this decorator in two different ways:

  1. Applied to a class-based view (HomeView): The @method_decorator(dec, name='dispatch') line applies the dec decorator to the dispatch method of the HomeView class. The dispatch method is called when a request is made to the view. So, whenever you access the HomeView URL, the decorator dec will be invoked before and after the dispatch method is executed.

  2. Applied to a function-based view (hello_view): The @dec line applies the dec decorator directly to the hello_view function. Whenever you access the URL associated with this view, the dec decorator will be invoked before and after the hello_view function is executed.

Here's how the execution flow works for each case:

  1. For HomeView: When a request is made to the URL mapped to HomeView, the following will happen:

    • The decorator dec will be called first (before the dispatch method is called).
    • The dispatch method will be called, executing the view's logic.
    • The decorator dec will be called again (after the dispatch method finishes).
  2. For hello_view: When a request is made to the URL mapped to hello_view, the following will happen:

    • The decorator dec will be called first (before the hello_view function is called).
    • The hello_view function will be executed, which returns an HTTP response with the content 'hello'.
    • The decorator dec will be called again (after the hello_view function finishes).

In both cases, you will see the print statements from the dec decorator in the console when the respective views are accessed.

Keep in mind that decorators can be useful for performing actions before and after executing view logic, like authentication checks, logging, or modifying the response.

 

              
                from django.views.generic import TemplateView
from django.utils.decorators import method_decorator
from django.http import HttpResponse
from django.contrib.auth.mixins import LoginRequiredMixin


def dec(func):
    def wrapper(request, *args, **kwargs):
        print('decorating')
        v = func(request, *args, **kwargs)
        print('end decorating')
        return v
    return wrapper


@method_decorator(dec, name='dispatch')
class HomeView(TemplateView):
    template_name = "index.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        return context

@dec
def hello_view(request):
    return HttpResponse('hello')
                  
   
            

Related Posts