Using Django's built-in middleware

 Using Django's built-in middleware


In Django, we can use middleware to add functionality to the request/response processing flow. Middleware can be used for tasks such as authentication, logging, and caching. We can define middleware in our app's middleware.py file. Here's an example middleware that logs the request method and URL:


python


class LoggingMiddleware:

    def __init__(self, get_response):

        self.get_response = get_response


    def __call__(self, request):

        method = request.method

        path = request.path

        print(f'{method} {path}')

        response = self.get_response(request)

        return response

In this example, we define a LoggingMiddleware class that takes the get_response argument and logs the request method and URL. We define the __call__ method to handle the request and return the response.


We can add our middleware to the middleware stack by adding it to the MIDDLEWARE setting in our app's settings.py file:


python


MIDDLEWARE = [

    'django.middleware.security.SecurityMiddleware',

    'django.contrib.sessions.middleware.SessionMiddleware',

    'django.middleware.common.CommonMiddleware',

    'django.middleware.csrf.CsrfViewMiddleware',

    'django.contrib.auth.middleware.AuthenticationMiddleware',

    'django.contrib.messages.middleware.MessageMiddleware',

    'django.middleware.clickjacking.XFrameOptionsMiddleware',

    'myapp.middleware.LoggingMiddleware',

]

In this example, we add our LoggingMiddleware to the MIDDLEWARE setting after the built-in middleware provided by Django.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...