0
0
Djangoframework~5 mins

Creating custom middleware in Django - Quick Revision & Summary

Choose your learning style9 modes available
Recall & Review
beginner
What is middleware in Django?
Middleware is a way to process requests and responses globally before they reach the view or after the view has processed them. It acts like a middle step in the request-response cycle.
Click to reveal answer
intermediate
How do you create a custom middleware class in Django?
Create a class with an __init__ method and a __call__ method that takes the request and returns a response. You can also define process_view, process_exception, or process_template_response methods for specific hooks.
Click to reveal answer
beginner
Where do you add your custom middleware so Django uses it?
Add the full Python path of your middleware class to the MIDDLEWARE list in the settings.py file. Django processes middleware in the order listed.
Click to reveal answer
intermediate
What is the purpose of the __call__ method in Django middleware?
The __call__ method is called for each request. It receives the request, can modify it, calls the next middleware or view, and then can modify the response before returning it.
Click to reveal answer
beginner
Give a simple example of a custom middleware that prints 'Hello' for every request.
class HelloMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        print('Hello')
        response = self.get_response(request)
        return response
Click to reveal answer
What method must a Django middleware class implement to process each request?
A__call__
Bprocess_request
Chandle_request
Dprocess_response
Where do you register your custom middleware in a Django project?
AINSTALLED_APPS
BTEMPLATES
CMIDDLEWARE
DDATABASES
What does the get_response argument in middleware's __init__ method represent?
AThe HTTP request object
BThe Django settings object
CThe HTTP response object
DThe next middleware or view to call
Which of these is NOT a typical use of custom middleware?
AModifying responses
BDefining database models
CLogging requests
DHandling exceptions globally
In what order does Django process middleware listed in settings?
AFrom first to last
BRandom order
CFrom last to first
DAlphabetical order
Explain how to create and register a simple custom middleware in Django.
Think about the request-response cycle and where your middleware fits.
You got /4 concepts.
    Describe the role of middleware in Django's request-response cycle.
    Middleware acts like a checkpoint between the browser and your views.
    You got /4 concepts.