Performance: CRUD operations
CRUD operations impact server response time and client rendering speed, affecting how quickly users see and interact with data changes.
Jump into concepts and practice - no test required
from fastapi import FastAPI import asyncio app = FastAPI() items = {} @app.get('/items/{item_id}') async def read_item(item_id: int): await asyncio.sleep(2) # Non-blocking placeholder for async DB call return items.get(item_id, {'error': 'Not found'}) @app.post('/items/{item_id}') async def create_item(item_id: int, item: dict): items[item_id] = item return item
from fastapi import FastAPI app = FastAPI() items = {} @app.get('/items/{item_id}') async def read_item(item_id: int): # Simulate slow DB call import time time.sleep(2) return items.get(item_id, {'error': 'Not found'}) @app.post('/items/{item_id}') async def create_item(item_id: int, item: dict): items[item_id] = item return item
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous blocking DB calls | Minimal | Multiple due to delayed updates | High due to delayed content | [X] Bad |
| Asynchronous non-blocking DB calls | Minimal | Single or minimal | Low due to faster content delivery | [OK] Good |
| Sequential synchronous updates | Minimal | Multiple reflows due to slow updates | High | [X] Bad |
| Parallel asynchronous updates | Minimal | Single reflow after batch update | Low | [OK] Good |
| Returning full large data sets | Many DOM nodes | Multiple reflows | High paint cost | [X] Bad |
| Paginated data responses | Few DOM nodes per page | Single reflow per page | Low paint cost | [OK] Good |
GET /items/42 if the item exists?
from fastapi import FastAPI
app = FastAPI()
items = {42: {"name": "Book", "price": 10.99}}
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return items.get(item_id, {"error": "Item not found"})from fastapi import FastAPI
app = FastAPI()
items = {1: "apple", 2: "banana"}
@app.delete("/items/{item_id}")
async def delete_item(item_id: int):
del items[item_id]
return {"message": "Item deleted"}@app.put("/items/{item_id}")
async def update_item(item_id: int, item: dict):
items[item_id] = item
return item
B:
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: dict):
if item_id not in items:
return {"error": "Not found"}
items[item_id] = item
return item
C:
from fastapi import HTTPException
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: dict):
if item_id not in items:
raise HTTPException(status_code=404, detail="Item not found")
items[item_id] = item
return item
D:
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: dict):
try:
items[item_id] = item
except KeyError:
return {"error": "Not found"}
return item