Skip to content

Middlewares

Default Service Provider#

Pyrannic makes available to you a service provider which can be used to register automatically your middlewares.

bootstrap/providers.py
from typing import Type

from app.providers.app import AppServiceProvider

from pyrannic import (
    DatabaseServiceProvider,
    MiddlewaresServiceProvider,
    RoutersServiceProvider,
    ExceptionHandlersServiceProvider,
    ServiceProvider,
)

providers: list[Type[ServiceProvider]] = [
    ExceptionHandlersServiceProvider,
    AppServiceProvider,
    DatabaseServiceProvider,
    RoutersServiceProvider,
    MiddlewaresServiceProvider,
]

This provider will get all your modules from the path app/http/middlewares and search for any public function or any public class and register them in the application.

Bootstrapping File#

By default, the provider will register your routers by alphabetic order of the module's name. But, with middlewares, sometimes you will need more granularity in their registration, requiring an specific order between them.

You can customise this order in the registration of your middlewares creating a new file middlewares.py in the bootstrap folder of your app. The provider will read the middlewares list from this file and use it to register them.

bootstrap/middlewares.py
from app.http.middlewares.middleware_a import A_Middleware
from app.http.middlewares.middleware_b import B_Middleware
from app.http.middlewares.middleware_c import C_Middleware
from app.http.middlewares.middleware_func import middleware_func


middlewares: list[object] = [
    B_Middleware,
    middleware_func,
    C_Middleware,
    A_Middleware,
]

Custom Service Provider#

To use the default service provider from Pyrannic is not mandatory. You can write your own service provider and register your middlewares just like you would do it normally in FastAPI.

Custom MiddlewaresServiceProvider
from pyrannic import ServiceProvider
from app.http.middlewares.middleware_a import A_Middleware
from app.http.middlewares.middleware_b import B_Middleware


class MiddlewaresServiceProvider(ServiceProvider):
    def register(self):
        self.app.add_middleware(B_Middleware)
        self.app.add_middleware(A_Middleware)

The property app

The ServiceProvider give you access to the underneath application through the app property. This property is an instance of an ApplicationInterface but, in the end, it is also an instance of a FastAPI application, and you can use all its methods. To know more about the service providers check its documentation.