Reader small image

You're reading from  Django in Production

Product typeBook
Published inApr 2024
Reading LevelIntermediate
PublisherPackt
ISBN-139781804610480
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Arghya Saha
Arghya Saha
author image
Arghya Saha

Arghya (argo) Saha, is a software developer with 8+ years of experience and has been working with Django since 2015. Apart from Django, he is proficient in JavaScript, ReactJS, Node.js, Postgres, AWS, and several other technologies. He has worked with multiple start-ups, such as Postman and HealthifyMe, among others, to build applications at scale. He currently works at Abnormal Security as a senior Site Reliability Engineer to explore his passion in the infrastructure domain. In his spare time, he writes tech blogs. He is also an adventurous person who has done multiple Himalayan treks and is an endurance athlete with multiple marathons and triathlons under his belt.
Read more about Arghya Saha

Right arrow

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:

  1. Create a file called custom_middleware.py (any other name can also be given). Add the following code to the common/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")
         ...
lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Django in Production
Published in: Apr 2024Publisher: PacktISBN-13: 9781804610480

Author (1)

author image
Arghya Saha

Arghya (argo) Saha, is a software developer with 8+ years of experience and has been working with Django since 2015. Apart from Django, he is proficient in JavaScript, ReactJS, Node.js, Postgres, AWS, and several other technologies. He has worked with multiple start-ups, such as Postman and HealthifyMe, among others, to build applications at scale. He currently works at Abnormal Security as a senior Site Reliability Engineer to explore his passion in the infrastructure domain. In his spare time, he writes tech blogs. He is also an adventurous person who has done multiple Himalayan treks and is an endurance athlete with multiple marathons and triathlons under his belt.
Read more about Arghya Saha