@@ -11,32 +11,21 @@ Configure SQLAlchemy with FastAPI:
1111
1212.. code-block :: python
1313
14- from contextlib import asynccontextmanager
1514 from typing import AsyncGenerator
1615
1716 from fastapi import FastAPI
1817
19- from advanced_alchemy.config import AsyncSessionConfig, SQLAlchemyAsyncConfig
20- from advanced_alchemy.base import metadata_registry
21- from advanced_alchemy.extensions.starlette import StarletteAdvancedAlchemy
18+ from advanced_alchemy.extensions.fastapi import AdvancedAlchemy, AsyncSessionConfig, SQLAlchemyAsyncConfig
2219
23- session_config = AsyncSessionConfig(expire_on_commit = False )
2420 sqlalchemy_config = SQLAlchemyAsyncConfig(
2521 connection_string = " sqlite+aiosqlite:///test.sqlite" ,
26- session_config = session_config
22+ session_config = AsyncSessionConfig(expire_on_commit = False ),
23+ create_all = True ,
24+ commit_mode = " autocommit" ,
2725 )
2826
29- @asynccontextmanager
30- async def on_lifespan (app : FastAPI) -> AsyncGenerator[None , None ]:
31- """ Initializes the database."""
32- metadata = metadata_registry.get(sqlalchemy_config.bind_key)
33- if sqlalchemy_config.create_all:
34- async with sqlalchemy_config.get_engine().begin() as conn:
35- await conn.run_sync(metadata.create_all)
36- yield
37-
38- app = FastAPI(lifespan = on_lifespan)
39- alchemy = StarletteAdvancedAlchemy(config = sqlalchemy_config, app = app)
27+ app = FastAPI()
28+ alchemy = AdvancedAlchemy(config = sqlalchemy_config, app = app)
4029
4130 Models and Schemas
4231------------------
@@ -88,38 +77,40 @@ Create repository and service classes:
8877
8978.. code-block :: python
9079
80+ from typing import Annotated, AsyncGenerator, Optional
81+
82+ from advanced_alchemy.extensions.fastapi import repository, service
83+ from fastapi import Depends
9184 from sqlalchemy.ext.asyncio import AsyncSession
92- from advanced_alchemy.repository import SQLAlchemyAsyncRepository
93- from advanced_alchemy.service import SQLAlchemyAsyncRepositoryService
94- from typing import AsyncGenerator
9585
96- class AuthorRepository (SQLAlchemyAsyncRepository[AuthorModel]):
97- """ Author repository."""
98- model_type = AuthorModel
9986
100- class AuthorService (SQLAlchemyAsyncRepositoryService[AuthorModel]):
87+ class AuthorService (service . SQLAlchemyAsyncRepositoryService[AuthorModel]):
10188 """ Author service."""
102- repository_type = AuthorRepository
10389
104- async def provide_authors_service (
105- db_session : Annotated[AsyncSession, Depends(provide_db_session)],
106- ) -> AsyncGenerator[AuthorService, None ]:
107- """ This provides the default Authors repository. """
108- async with AuthorService.new( session = db_session) as service:
109- yield service
90+ class Repo ( repository .SQLAlchemyAsyncRepository[AuthorModel]):
91+ """ Author repository. """
92+ model_type = AuthorModel
93+
94+ repository_type = Repo
95+
11096
11197 Dependency Injection
11298--------------------
11399
114- Set up dependency injection for the database session:
100+ Set up dependency injected into the request context.
115101
116102.. code-block :: python
117103
118104 from fastapi import Request
119105
120- async def provide_db_session (request : Request) -> AsyncSession:
121- """ Provide a DB session."""
122- return alchemy.get_session(request) # this is the `StarletteAdvancedAlchemy` object
106+ DatabaseSession = Annotated[AsyncSession, Depends(alchemy.provide_session())]
107+ Authors = Annotated[AuthorService, Depends(provide_authors_service)]
108+
109+ async def provide_authors_service (db_session : DatabaseSession) -> AsyncGenerator[AuthorService, None ]:
110+ """ This provides the default Authors repository."""
111+ async with AuthorService.new(session = db_session) as service:
112+ yield service
113+
123114
124115 Controllers
125116-----------
@@ -130,32 +121,31 @@ Create controllers using the service:
130121
131122 from fastapi import APIRouter, Depends
132123 from uuid import UUID
133- from advanced_alchemy.filters import LimitOffset
134- from advanced_alchemy.service import OffsetPagination
124+ from advanced_alchemy.extensions.fastapi import filters
135125
136126 author_router = APIRouter()
137127
138- @author_router.get (path = " /authors" , response_model = OffsetPagination[Author])
128+ @author_router.get (path = " /authors" , response_model = filters. OffsetPagination[Author])
139129 async def list_authors (
140- authors_service : Annotated[AuthorService, Depends(provide_authors_service)] ,
141- limit_offset : Annotated[LimitOffset, Depends(provide_limit_offset_pagination)],
142- ) -> OffsetPagination[AuthorModel]:
130+ authors_service : Authors ,
131+ limit_offset : Annotated[filters. LimitOffset, Depends(provide_limit_offset_pagination)],
132+ ) -> filters. OffsetPagination[AuthorModel]:
143133 """ List authors."""
144134 results, total = await authors_service.list_and_count(limit_offset)
145135 return authors_service.to_schema(results, total, filters = [limit_offset])
146136
147137 @author_router.post (path = " /authors" , response_model = Author)
148138 async def create_author (
149- authors_service : Annotated[AuthorService, Depends(provide_authors_service)] ,
139+ authors_service : Authors ,
150140 data : AuthorCreate,
151141 ) -> AuthorModel:
152142 """ Create a new author."""
153- obj = await authors_service.create(data.model_dump( exclude_unset = True , exclude_none = True ), auto_commit = True )
143+ obj = await authors_service.create(data)
154144 return authors_service.to_schema(obj)
155145
156146 @author_router.get (path = " /authors/{author_id} " , response_model = Author)
157147 async def get_author (
158- authors_service : Annotated[AuthorService, Depends(provide_authors_service)] ,
148+ authors_service : Authors ,
159149 author_id : UUID ,
160150 ) -> AuthorModel:
161151 """ Get an existing author."""
@@ -164,25 +154,21 @@ Create controllers using the service:
164154
165155 @author_router.patch (path = " /authors/{author_id} " , response_model = Author)
166156 async def update_author (
167- authors_service : Annotated[AuthorService, Depends(provide_authors_service)] ,
157+ authors_service : Authors ,
168158 data : AuthorUpdate,
169159 author_id : UUID ,
170160 ) -> AuthorModel:
171161 """ Update an author."""
172- obj = await authors_service.update(
173- data.model_dump(exclude_unset = True , exclude_none = True ),
174- item_id = author_id,
175- auto_commit = True ,
176- )
162+ obj = await authors_service.update(data, item_id = author_id)
177163 return authors_service.to_schema(obj)
178164
179165 @author_router.delete (path = " /authors/{author_id} " )
180166 async def delete_author (
181- authors_service : Annotated[AuthorService, Depends(provide_authors_service)] ,
167+ authors_service : Authors ,
182168 author_id : UUID ,
183169 ) -> None :
184170 """ Delete an author from the system."""
185- _ = await authors_service.delete(author_id, auto_commit = True )
171+ _ = await authors_service.delete(author_id)
186172
187173 Application Configuration
188174-------------------------
0 commit comments