A
A
Abror Maksudov2022-01-13 10:03:36
Python
Abror Maksudov, 2022-01-13 10:03:36

What is Middlewares in aiogram?

For a long time I just can’t understand what Middleware is, what they are for, where and when they are used. Please explain in detail, can you throw off another link with examples

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Nesterov, 2022-01-13
@AlexNest

In general, Middlewares is a layer called automatically after a request and before it is processed by the server. Can be used, for example, for logging or adding a payload.
An example from the docs that adds a counter value to the data of each message

from aiogram import BaseMiddleware
from aiogram.types import Message


class CounterMiddleware(BaseMiddleware):
    def __init__(self) -> None:
        self.counter = 0

    async def __call__(
        self,
        handler: Callable, Awaitable[Any]],
        event: Message,
        data: Dict[str, Any]
    ) -> Any:
        self.counter += 1
        data['counter'] = self.counter
        return await handler(event, data)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question