Creating custom middleware
Custom Django middleware should be used to execute code that we want to run for all the requests/responses. For example, we want to add a custom header to all the requests/responses, or we want to add logging or monitoring for requests. In Chapter 6, we learned how to use custom middleware to add get user_id
for each request for logging. In this section, we will learn about the core concepts of custom middleware in Django.
Let us now check how to create a custom middleware in Django:
- Create a file called
custom_middleware.py
(any other name can also be given). Add the following code to thecommon/custom_middleware.py
file:class CustomMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): print("custom middleware before request view") ...