Sobes.tech
Junior — Middle

Can you give an example of a situation where middleware is used?

sobes.tech AI

Answer from AI

Middleware is often used in web development to handle HTTP requests between the client and server. For example, in Python frameworks like Flask or Django, middleware can be used for user authentication, request logging, or error handling.

Example: In Django, middleware can intercept a request, check if the user is authenticated, and if not, redirect to the login page.

class SimpleMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if not request.user.is_authenticated:
            from django.shortcuts import redirect
            return redirect('/login/')
        response = self.get_response(request)
        return response

Thus, middleware allows centralized handling of common tasks without duplicating code in each handler.

Can you give an example of a situation where… - sobes.tech