Creating custom ASGI middleware
ASGI is a specification for Python web servers and applications to communicate with each other, designed to support asynchronous functionality. Middleware is a critical component in web applications, providing a way to process requests and responses.
We have already seen, in the Creating custom middleware recipe in Chapter 8, Advanced Features and Best Practices, how to create custom middleware. However, this technique relies on the BasicHTTPMiddleware
class from the Starlette library, which is a high-level implementation of HTTP middleware.
In this recipe, we’ll learn how to create custom ASGI middleware from scratch and integrate it into a FastAPI application. The middleware will be simple and will only print log message information on the terminal.
This approach provides greater control over the request/response cycle compared to the BasicHTTPMiddleware
class, allowing for advanced customizations and the creation of any kind of middleware...