SQLAlchemy 2 In Practice - Chapter 8: SQLAlchemy and the Web
a day ago
- SQLAlchemy can be integrated into web applications without any special integration by using db.py and models.py with the session context manager.
- To avoid long import lists and naming collisions, import only parent modules (sqlalchemy as sa, sqlalchemy.orm as so) and access symbols through prefixes.
- Model serialization for web APIs can be done by adding a to_dict() method to each model, which returns a dictionary serializable to JSON, including related objects recursively.
- The Alchemical package simplifies SQLAlchemy setup by encapsulating Engine, MetaData, Model base, and Session into a single Alchemical instance, with built-in Flask and async support.
- Example web applications using Flask and FastAPI demonstrate a server-side table with pagination, sorting, and search, using two queries: one for total count and one for paginated data.
- Flask routes use a blueprint with a session automatically managed by Alchemical, while FastAPI uses async endpoints with explicit session context managers.