-
-
Notifications
You must be signed in to change notification settings - Fork 342
Expand file tree
/
Copy pathconsumer.py
More file actions
57 lines (39 loc) · 1.15 KB
/
consumer.py
File metadata and controls
57 lines (39 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import asyncio
from typing import Annotated
from dependency_injector import containers, providers
from dependency_injector.wiring import Provide, inject
from faststream import Depends, FastStream
from faststream.redis import RedisBroker
from pydantic import BaseModel
class Counter:
def __init__(self):
self.count = 0
def next(self) -> int:
self.count += 1
return self.count
class Container(containers.DeclarativeContainer):
counter = providers.Singleton(Counter)
broker = RedisBroker("redis://redis", logger=None)
class Message(BaseModel):
user: str
text: str
@broker.subscriber("messages")
@inject
async def handle_user_message(
message: Message,
counter: Annotated[
Counter,
Depends(
Provide[Container.counter],
cast=False, # <-- this is the key part
),
],
) -> None:
count = counter.next()
print(f"Message #{count} from {message.user}: '{message.text}'")
async def main() -> None:
container = Container()
container.wire(modules=[__name__])
await FastStream(broker, logger=None).run()
if __name__ == "__main__":
asyncio.run(main())