|
| 1 | +import asyncio |
| 2 | +from typing import Annotated |
| 3 | + |
| 4 | +from dependency_injector import containers, providers |
| 5 | +from dependency_injector.wiring import Provide, inject |
| 6 | +from faststream import Depends, FastStream |
| 7 | +from faststream.redis import RedisBroker, RedisRouter |
| 8 | +from pydantic import BaseModel |
| 9 | + |
| 10 | + |
| 11 | +class Counter: |
| 12 | + def __init__(self): |
| 13 | + self.count = 0 |
| 14 | + |
| 15 | + def next(self) -> int: |
| 16 | + self.count += 1 |
| 17 | + return self.count |
| 18 | + |
| 19 | + |
| 20 | +class Container(containers.DeclarativeContainer): |
| 21 | + counter = providers.Singleton(Counter) |
| 22 | + |
| 23 | + config = providers.Configuration() |
| 24 | + |
| 25 | + broker = providers.Singleton(RedisBroker, config.redis_url, logger=None) |
| 26 | + app = providers.Factory(FastStream, broker, logger=None) |
| 27 | + |
| 28 | + |
| 29 | +class Message(BaseModel): |
| 30 | + user: str |
| 31 | + text: str |
| 32 | + |
| 33 | + |
| 34 | +router = RedisRouter() |
| 35 | + |
| 36 | + |
| 37 | +@router.subscriber("messages") |
| 38 | +@inject |
| 39 | +async def handle_user_message( |
| 40 | + message: Message, |
| 41 | + counter: Annotated[ |
| 42 | + Counter, |
| 43 | + Depends( |
| 44 | + Provide[Container.counter], |
| 45 | + cast=False, # <-- this is the key part |
| 46 | + ), |
| 47 | + ], |
| 48 | +) -> None: |
| 49 | + count = counter.next() |
| 50 | + print(f"Message #{count} from {message.user}: '{message.text}'") |
| 51 | + |
| 52 | + |
| 53 | +async def main() -> None: |
| 54 | + container = Container() |
| 55 | + container.wire(modules=[__name__]) |
| 56 | + |
| 57 | + container.config.redis_url.from_env("REDIS_URL") |
| 58 | + |
| 59 | + broker = container.broker() |
| 60 | + broker.include_router(router) |
| 61 | + |
| 62 | + app = container.app() |
| 63 | + await app.run() |
| 64 | + |
| 65 | + |
| 66 | +if __name__ == "__main__": |
| 67 | + asyncio.run(main()) |
0 commit comments