Performance: Async database queries
This concept affects how quickly the server can respond to requests by not blocking while waiting for database results.
from fastapi import FastAPI from databases import Database app = FastAPI() database = Database('sqlite:///test.db') @app.on_event('startup') async def startup(): await database.connect() @app.on_event('shutdown') async def shutdown(): await database.disconnect() @app.get('/items') async def read_items(): query = 'SELECT * FROM items' items = await database.fetch_all(query) # async non-blocking call return items
from fastapi import FastAPI, Depends from sqlalchemy.orm import Session app = FastAPI() def get_db(): db = Session() try: yield db finally: db.close() @app.get('/items') def read_items(db: Session = Depends(get_db)): items = db.query(Item).all() # synchronous blocking call return items
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous DB query | N/A (server-side) | N/A | N/A | [X] Bad |
| Async DB query | N/A (server-side) | N/A | N/A | [OK] Good |
async database queries in FastAPI?async def to use await inside.await must be used with the async session call.async def fetch_users(session):
result = await session.execute("SELECT name FROM users")
users = result.scalars().all()
return usersfetch_users return?await waits for the query to finish and returns a Result object.scalars().all() extracts all values from the first column as a list.async def get_items(session):
result = session.execute("SELECT * FROM items")
return await result.fetchall()Pass the test and this pattern moves unknown