-
Notifications
You must be signed in to change notification settings - Fork 1
/
decorator_api.py
56 lines (40 loc) · 1.32 KB
/
decorator_api.py
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 AsyncGenerator, Tuple
from pydantic import BaseModel
from simple_aiokafka import (
ConsumerRecord,
kafka_consumer,
kafka_processor,
kafka_producer,
)
class Document(BaseModel):
text: str
id: int
note: str = None
def document_serializer(document: Document):
return document.json().encode()
@kafka_producer(value_serializer=document_serializer)
async def produce() -> AsyncGenerator[Tuple[str, Document], None]:
for i in range(100):
yield str(i), Document(text="Hello Kafka", id=i)
await asyncio.sleep(1)
@kafka_consumer("aiokafka.result", value_deserializer=Document.parse_raw)
async def consume(msg: ConsumerRecord = None) -> None:
print("Consume Message:", msg)
@kafka_processor(
input_topic="aiokafka.output",
output_topic="aiokafka.result",
consumer_args={"value_deserializer": Document.parse_raw},
producer_args={"value_serializer": document_serializer},
)
async def process(msg: ConsumerRecord = None) -> Tuple[str, str]:
document = msg.value
document.note = "Hello Kafka :)"
return msg.key, document
async def main():
asyncio.create_task(produce())
asyncio.create_task(process())
await consume()
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())