Performance: Sending and receiving messages
This affects how quickly messages are sent and received over the network, impacting server response time and user interaction speed.
from fastapi import FastAPI import asyncio app = FastAPI() @app.post('/send') async def send_message(message: str): # Simulate async processing await asyncio.sleep(0.1) return {'status': 'sent'}
from fastapi import FastAPI app = FastAPI() @app.post('/send') def send_message(message: str): # Simulate heavy processing import time time.sleep(5) return {'status': 'sent'}
| Pattern | Server Blocking | Concurrency | Response Time | Verdict |
|---|---|---|---|---|
| Synchronous blocking with time.sleep | High (blocks worker) | Low (serial requests) | Slow (delays response) | [X] Bad |
| Asynchronous with await asyncio.sleep | Low (non-blocking) | High (handles many requests) | Fast (quick response) | [OK] Good |
Message?{"text": "Hello"}?
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Message(BaseModel):
text: str
@app.post('/echo')
async def echo_message(msg: Message):
return {"message": msg.text.upper()}from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Message(BaseModel):
content: str
@app.post('/receive')
def receive_message(msg: Message):
return {"received": msg.content}text field, and returns a list of all texts in uppercase. Which code snippet correctly implements this?Pass the test and this pattern moves unknown