Complete the code to define an event handler function in FastAPI.
from fastapi import FastAPI app = FastAPI() @app.[1]("/items/") async def create_item(): return {"message": "Item created"}
The @app.post decorator defines a POST request handler, which is commonly used to create resources in event-driven APIs.
Complete the code to publish an event message asynchronously.
import asyncio async def publish_event(event_data): await [1](event_data) async def send_message(data): print(f"Sending: {data}")
The function send_message is awaited to simulate sending an event asynchronously.
Fix the error in the event listener registration code.
from fastapi import FastAPI app = FastAPI() @[1]("/event") async def event_listener(): return {"status": "Event received"}
FastAPI uses @app.get or other HTTP method decorators to define endpoints. app.listen or app.on are not valid decorators.
Fill both blanks to create a background task that handles events.
from fastapi import FastAPI, BackgroundTasks app = FastAPI() def process_event(data): print(f"Processing {data}") @app.post("/event") async def handle_event(data: dict, [1]: BackgroundTasks): [2].add_task(process_event, data) return {"message": "Event received"}
The parameter name background_tasks is used to receive the BackgroundTasks instance, and then background_tasks.add_task schedules the event processing.
Fill all three blanks to implement a simple event bus with subscription and publishing.
class EventBus: def __init__(self): self.subscribers = {} def subscribe(self, event_type, handler): if event_type not in self.subscribers: self.subscribers[[1]] = [] self.subscribers[event_type].append(handler) async def publish(self, event_type, data): for handler in self.subscribers.get(event_type, [2]): await handler([3])
We use event_type as the key to store handlers, default to empty list [] if no subscribers, and pass data to each handler when publishing.