Consider this FastAPI code snippet using an event system:
from fastapi import FastAPI
app = FastAPI()
subscribers = []
def on_event(data):
subscribers.append(data)
@app.post('/emit')
async def emit_event(payload: dict):
on_event(payload['message'])
return {'status': 'event received'}
@app.get('/subscribers')
async def get_subscribers():
return {'messages': subscribers}What will be the output of a GET request to /subscribers after posting {"message": "hello"} to /emit once?
from fastapi import FastAPI app = FastAPI() subscribers = [] def on_event(data): subscribers.append(data) @app.post('/emit') async def emit_event(payload: dict): on_event(payload['message']) return {'status': 'event received'} @app.get('/subscribers') async def get_subscribers(): return {'messages': subscribers}
Think about what the on_event function does with the data it receives.
The on_event function appends the message string to the subscribers list. Posting to /emit triggers this function with the message "hello". So, the /subscribers endpoint returns the list containing "hello".
In FastAPI, you can register a function to run on startup using @app.on_event('startup'). When exactly does this function run?
from fastapi import FastAPI app = FastAPI() @app.on_event('startup') async def startup_event(): print('App is starting')
Think about the server lifecycle phases: startup, running, shutdown.
The startup event runs once when the FastAPI server starts, before it handles any requests. It is used to prepare resources or initialize state.
Look at this FastAPI code:
from fastapi import FastAPI
app = FastAPI()
state = {'count': 0}
def increment():
state = {'count': state['count'] + 1}
@app.post('/inc')
async def increment_endpoint():
increment()
return stateWhy does calling /inc never increase count?
from fastapi import FastAPI app = FastAPI() state = {'count': 0} def increment(): state = {'count': state['count'] + 1} @app.post('/inc') async def increment_endpoint(): increment() return state
Check variable scope and assignment inside the increment function.
Inside increment, assigning to state creates a new local variable, shadowing the global state. The global state remains unchanged, so the count never increases.
Identify the option that contains a syntax error in defining an event handler in FastAPI.
Look carefully at function definitions and punctuation.
Option A is missing a colon at the end of the function definition line, causing a SyntaxError.
Choose the best explanation of why event-driven architecture is useful in FastAPI applications.
Think about how events help parts of an app communicate without tight connections.
Event-driven architecture lets components respond to events independently, which helps scale the app and makes it easier to change parts without breaking others.