-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path09_eventbus_decorator.py
More file actions
64 lines (49 loc) · 1.75 KB
/
09_eventbus_decorator.py
File metadata and controls
64 lines (49 loc) · 1.75 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
57
58
59
60
61
62
63
64
"""EventBus with Decorator Registration
Demonstrates:
- Using @event_handler decorator for handler registration
- Global EventBus initialization with init_eventbus()
- Multiple handlers for the same event type
- APP scope events
"""
import asyncio
import logging
from opensecflow.eventbus.memory_broker import AsyncQueueBroker
from opensecflow.eventbus.eventbus import event_handler, init_eventbus
from opensecflow.eventbus.event import ScopedEvent, EventScope
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
async def main():
"""Using @event_handler decorator for registration"""
print("\n=== EventBus with Decorator Registration ===\n")
# Define event class
class UserRegisteredEvent(ScopedEvent):
type: str = "user.registered"
user_id: str
email: str
scope: EventScope = EventScope.APP
# Use decorator to register handlers
@event_handler(UserRegisteredEvent)
async def send_welcome_email(event_data: UserRegisteredEvent):
print(f" 📧 Sending welcome email to: {event_data.email}")
@event_handler(UserRegisteredEvent)
async def create_user_profile(event_data: UserRegisteredEvent):
print(f" 👤 Creating profile for user: {event_data.user_id}")
# Initialize global EventBus
process_broker = AsyncQueueBroker()
app_broker = AsyncQueueBroker()
bus = init_eventbus(process_broker, app_broker)
await bus.start()
# Publish event
event = UserRegisteredEvent(
source="user-service",
user_id="U-001",
email="[email protected]"
)
await bus.publish(event)
await asyncio.sleep(0.2)
await bus.stop()
if __name__ == "__main__":
asyncio.run(main())