Coverage for fastapi_restly/db/_session.py: 98%

223 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-11-09 21:47 +0000

1import warnings 

2import weakref 

3from collections.abc import AsyncIterator, Callable, Iterator 

4from functools import partial 

5from inspect import ( 

6 Parameter, 

7 Signature, 

8 isasyncgenfunction, 

9 isgeneratorfunction, 

10 signature, 

11 unwrap, 

12) 

13from typing import Annotated, Any, cast 

14 

15from fastapi import Depends, FastAPI 

16from sqlalchemy import Connection, Engine, MetaData, create_engine, event 

17from sqlalchemy.ext.asyncio import ( 

18 AsyncConnection, 

19 AsyncEngine, 

20 async_sessionmaker, 

21 create_async_engine, 

22) 

23from sqlalchemy.ext.asyncio import AsyncSession as SA_AsyncSession 

24from sqlalchemy.orm import DeclarativeBase, SessionTransaction, sessionmaker 

25from sqlalchemy.orm import Session as SA_Session 

26 

27from .._routes import iter_routes 

28from ..exc import ( 

29 RestlyConfigurationError, 

30 RestlyExpireOnCommitWarning, 

31 RestlyUncommittedChangesWarning, 

32) 

33from ._config import _fr_config 

34from ._engine_defaults import apply_connect_hooks, engine_options 

35 

36 

37def _setup_async_database_connection( 

38 async_database_url: str | None = None, 

39 *, 

40 async_engine: AsyncEngine | None = None, 

41 async_make_session: async_sessionmaker[Any] | None = None, 

42) -> async_sessionmaker[Any]: 

43 if not async_make_session: 

44 if not async_engine: 

45 async_engine = create_async_engine( 

46 async_database_url, # type: ignore[arg-type] 

47 **engine_options(async_database_url), # type: ignore[arg-type] 

48 ) 

49 apply_connect_hooks(async_engine) 

50 async_make_session = async_sessionmaker( 

51 bind=async_engine, autoflush=False, expire_on_commit=False 

52 ) 

53 

54 factory_kw = getattr(async_make_session, "kw", None) 

55 if factory_kw is not None and factory_kw.get("expire_on_commit", True): 55 ↛ 56line 55 didn't jump to line 56 because the condition on line 55 was never true

56 warnings.warn( 

57 "The async session factory passed to fr.configure() has " 

58 "expire_on_commit=True. Restly's write handlers commit inside the " 

59 "request, so the commit expires every loaded attribute on the " 

60 "object the response is built from. Reading one back then happens in " 

61 "plain async context, where SQLAlchemy raises MissingGreenlet: always " 

62 "in the response serializer, and earlier too if an after_action_commit hook " 

63 "reads the committed object. Pass expire_on_commit=False to your " 

64 "async_sessionmaker.", 

65 RestlyExpireOnCommitWarning, 

66 stacklevel=3, 

67 ) 

68 

69 _fr_config.async_database_url = async_database_url 

70 _fr_config.async_make_session = async_make_session 

71 return async_make_session 

72 

73 

74def _setup_database_connection( 

75 database_url: str | None = None, 

76 *, 

77 engine: Engine | None = None, 

78 make_session: sessionmaker[Any] | None = None, 

79) -> sessionmaker[Any]: 

80 if make_session is None: 

81 if engine is None: 

82 # create_engine is overloaded, so the options splat costs pyright 

83 # the return type; the cast restores it. 

84 engine = cast( 

85 Engine, 

86 create_engine( 

87 database_url, # type: ignore[arg-type] 

88 **engine_options(database_url), # type: ignore[arg-type] 

89 ), 

90 ) 

91 apply_connect_hooks(engine) 

92 make_session = sessionmaker(bind=engine, expire_on_commit=False) 

93 

94 _fr_config.database_url = database_url 

95 _fr_config.make_session = make_session 

96 return make_session 

97 

98 

99async def _health() -> dict[str, str]: 

100 """Liveness response for the route ``fr.configure(health=...)`` mounts.""" 

101 return {"status": "ok"} 

102 

103 

104def _register_health_route(app: FastAPI, path: str) -> None: 

105 """Mount the liveness endpoint at ``path``. 

106 

107 Skips if ``app`` already has a route at that path, whatever its method: a 

108 repeated :func:`configure` call does not mount a second one, and an 

109 application's own endpoint there is left in place. 

110 """ 

111 if any(getattr(route, "path", None) == path for route in iter_routes(app.routes)): 

112 return 

113 # name= keeps the private handler out of the generated operationId. 

114 app.add_api_route(path, _health, methods=["GET"], name="health") 

115 

116 

117def _is_generator(call: Any, check: Callable[[Any], bool]) -> bool: 

118 """Whether ``check``, such as ``isasyncgenfunction``, is true for 

119 ``call``, as FastAPI tells the kind of a dependency: also through 

120 ``functools.partial``, a decorator that uses ``functools.wraps``, or the 

121 ``__call__`` method of an object.""" 

122 if call is None: 

123 return False 

124 for candidate in (call, getattr(call, "__call__", None)): 

125 while isinstance(candidate, partial): 

126 candidate = candidate.func 

127 if candidate is not None and (check(candidate) or check(unwrap(candidate))): 

128 return True 

129 return False 

130 

131 

132def configure( 

133 app: FastAPI | None = None, 

134 *, 

135 async_database_url: str | None = None, 

136 async_engine: AsyncEngine | None = None, 

137 async_make_session: async_sessionmaker[Any] | None = None, 

138 database_url: str | None = None, 

139 engine: Engine | None = None, 

140 make_session: sessionmaker[Any] | None = None, 

141 async_session_generator: Callable[..., AsyncIterator[SA_AsyncSession]] 

142 | None = None, 

143 session_generator: Callable[..., Iterator[SA_Session]] | None = None, 

144 warn_on_misuse: bool | None = None, 

145 warn_on_uncommitted: bool | None = None, 

146 health: str | None = None, 

147) -> None: 

148 """Configure FastAPI-Restly. Call it at startup. A second call replaces 

149 only the sources that it names, for every app in the process. 

150 

151 Async support comes from ``async_database_url``, ``async_engine``, 

152 ``async_make_session`` or ``async_session_generator``; sync support from 

153 ``database_url``, ``engine``, ``make_session`` or 

154 ``session_generator``. Pass both sets if the application uses both. 

155 

156 A URL is the one form Restly builds an engine from, and that engine gets 

157 defaults suited to a web application: ``StaticPool`` for in-memory SQLite, 

158 ``PRAGMA foreign_keys=ON`` on every SQLite connection, and on PostgreSQL 

159 ``pool_pre_ping``, ``pool_recycle`` and each session in UTC. Pool sizing is 

160 left alone, and so is anything written into the database itself, which is 

161 why ``journal_mode=WAL`` is not among them. Every other form is used as 

162 given, so passing ``engine=`` declines all of this. 

163 

164 Restly owns the commit: the CRUD handlers and ``write_action`` run 

165 ``before_action_commit`` -> commit -> ``after_action_commit`` around your domain logic. A 

166 custom session generator constructs, yields, and cleans up, and must not 

167 commit. A custom write route brackets its mutation with ``write_action(...)`` 

168 or commits the session itself. 

169 

170 Configure custom generators before registering routes that use ``SessionDep`` 

171 or ``AsyncSessionDep``. FastAPI resolves the generator as a sub-dependency, 

172 sharing its cached session with the application's ``Depends(get_db)``. 

173 Explicit view dependencies remain as declared. Generators used outside a 

174 request through ``open_session()`` or ``open_async_session()`` must be callable 

175 without arguments. 

176 

177 :func:`fastapi_restly.testing.configure_tests` freezes the database sources 

178 for the rest of that pytest process, so configure the application before 

179 enabling managed testing; changing them afterwards raises. 

180 

181 :param app: Application to install the health route on. Restly also 

182 checks its OpenAPI spec for two classes with the same name (see 

183 :class:`~fastapi_restly.exc.RestlyDuplicateSchemaNameWarning`). 

184 :param async_database_url: Async URL to build an 

185 :class:`~sqlalchemy.ext.asyncio.AsyncEngine` from. 

186 :param async_engine: Async engine to use as given. 

187 :param async_make_session: ``async_sessionmaker`` to use as given. 

188 :param database_url: Sync URL to build an 

189 :class:`~sqlalchemy.engine.Engine` from. 

190 :param engine: Sync engine to use as given. 

191 :param make_session: ``sessionmaker`` to use as given. 

192 :param async_session_generator: Callable yielding the 

193 :class:`~sqlalchemy.ext.asyncio.AsyncSession` for each request. 

194 :param session_generator: Callable yielding the 

195 :class:`~sqlalchemy.orm.Session` for each request. 

196 :param warn_on_misuse: Emit 

197 :class:`~fastapi_restly.exc.RestlyMisuseWarning` when ``include_view`` 

198 registers a view with an endpoint method override that calls neither 

199 its ``handle_<verb>`` handler nor the endpoint method of its base, a 

200 direct ``session.commit()`` in a CRUD view, a scalar foreign key typed as an 

201 ``IDRef`` / ``IDSchema`` reference instead of ``fr.MustExist``, or a 

202 writable field on a column that the model sets (``init=False`` with a 

203 default). It also warns when a view is registered twice on the same 

204 parent. Off by default; set it before registering views. 

205 :param warn_on_uncommitted: Emit 

206 :class:`~fastapi_restly.exc.RestlyUncommittedChangesWarning` when a 

207 request finishes with uncommitted changes. On by default. Suppress one 

208 deliberate case with ``session.info["_fr_suppress_uncommitted"] = True`` 

209 rather than turning the check off. 

210 :param health: Path to mount a liveness endpoint on, such as ``"/health"``. 

211 It answers ``200`` with ``{"status": "ok"}``, appears in the OpenAPI 

212 schema, and makes no database round-trip. Off unless set, and requires 

213 ``app``. A route already mounted at that path is left in place. 

214 Readiness is a separate endpoint of your own, not a mode of this one. 

215 :raises TypeError: No setup argument was given, or a generator was passed 

216 to the parameter of the other kind: async to ``session_generator`` or 

217 sync to ``async_session_generator``. 

218 :raises RestlyConfigurationError: ``health`` is not an absolute path or was 

219 passed without ``app``, a generator changed after route registration, or 

220 the database configuration changed after ``configure_tests()`` recorded it. 

221 """ 

222 configures_database = any( 

223 ( 

224 async_database_url is not None, 

225 async_engine is not None, 

226 async_make_session is not None, 

227 database_url is not None, 

228 engine is not None, 

229 make_session is not None, 

230 async_session_generator is not None, 

231 session_generator is not None, 

232 ) 

233 ) 

234 if configures_database and _fr_config.database_configuration_locked: 

235 raise RestlyConfigurationError( 

236 "Restly's database configuration cannot be changed after " 

237 "fr.testing.configure_tests() recorded it. This is often a " 

238 "per-test factory fixture (e.g. a @pytest.fixture that calls " 

239 "create_app(...) again for every test) calling fr.configure() " 

240 "after collection. Build the application once in conftest.py " 

241 "before calling configure_tests(), and do not reconfigure its " 

242 "database later during collection or application lifespan " 

243 "startup." 

244 ) 

245 

246 if not any( 

247 ( 

248 configures_database, 

249 warn_on_misuse is not None, 

250 warn_on_uncommitted is not None, 

251 health is not None, 

252 app is not None, 

253 ) 

254 ): 

255 raise TypeError("fr.configure() requires at least one setup argument.") 

256 

257 # Before 0.13, session_generator was the async parameter. An async 

258 # generator passed to it now would otherwise fail only at the first request. 

259 if _is_generator(session_generator, isasyncgenfunction): 

260 raise TypeError( 

261 "fr.configure(session_generator=...) got an async generator. " 

262 "session_generator takes a sync generator that yields a Session. " 

263 "Pass an async generator as async_session_generator. Before 0.13, " 

264 "session_generator was the async parameter." 

265 ) 

266 if _is_generator(async_session_generator, isgeneratorfunction): 

267 raise TypeError( 

268 "fr.configure(async_session_generator=...) got a sync generator. " 

269 "async_session_generator takes an async generator that yields an " 

270 "AsyncSession. Pass a sync generator as session_generator." 

271 ) 

272 

273 for name, generator in ( 

274 ("async_session_generator", async_session_generator), 

275 ("session_generator", session_generator), 

276 ): 

277 if ( 

278 generator is not None 

279 and name in _fr_config.registered_session_dependencies 

280 and generator is not getattr(_fr_config, name) 

281 ): 

282 raise RestlyConfigurationError( 

283 f"Configure {name} before registering routes that use Restly's " 

284 "session dependency. FastAPI has already built their dependency " 

285 "graphs. Move fr.configure() before route registration. For " 

286 "tests, use app.dependency_overrides instead." 

287 ) 

288 

289 # Validate before applying anything, so a bad health path cannot leave a 

290 # half-configured process behind. 

291 if health is not None: 

292 if not health.startswith("/"): 

293 raise RestlyConfigurationError( 

294 f"fr.configure(health={health!r}) needs a path starting with " 

295 "'/', such as '/health'." 

296 ) 

297 if app is None: 

298 raise RestlyConfigurationError( 

299 f"fr.configure(health={health!r}) also needs the app to mount " 

300 "the route on: fr.configure(app, health=...)." 

301 ) 

302 

303 if warn_on_misuse is not None: 

304 _fr_config.warn_on_misuse = warn_on_misuse 

305 if warn_on_uncommitted is not None: 

306 _fr_config.warn_on_uncommitted = warn_on_uncommitted 

307 if ( 

308 async_database_url is not None 

309 or async_engine is not None 

310 or async_make_session is not None 

311 ): 

312 _setup_async_database_connection( 

313 async_database_url=async_database_url, 

314 async_engine=async_engine, 

315 async_make_session=async_make_session, 

316 ) 

317 if database_url is not None or engine is not None or make_session is not None: 

318 _setup_database_connection( 

319 database_url=database_url, engine=engine, make_session=make_session 

320 ) 

321 if async_session_generator is not None: 

322 _fr_config.async_session_generator = async_session_generator 

323 if session_generator is not None: 

324 _fr_config.session_generator = session_generator 

325 if app is not None: 

326 from ..views._openapi_names import _ensure_patched 

327 

328 # The check for two classes with the same name in OpenAPI. 

329 _ensure_patched(app) 

330 if health is not None: 

331 _register_health_route(app, health) 

332 

333 

334def _active_make_session(): 

335 """The sync factory in force: a test's, if one installed it.""" 

336 return _fr_config.test_make_session or _fr_config.make_session 

337 

338 

339def _active_async_make_session(): 

340 """The async factory in force: a test's, if one installed it.""" 

341 return _fr_config.test_async_make_session or _fr_config.async_make_session 

342 

343 

344def get_async_engine() -> AsyncEngine: 

345 """Return the async engine registered via configure().""" 

346 if _fr_config.async_make_session is None: 

347 raise RestlyConfigurationError( 

348 "Call fr.configure() before using get_async_engine()." 

349 ) 

350 # This is a read-only lookup of application configuration. Test overrides may 

351 # be bound to a pinned connection or deliberately refuse session creation; 

352 # neither changes the engine that configure() registered. 

353 bind = _fr_config.async_make_session.kw["bind"] 

354 if isinstance(bind, AsyncConnection): 354 ↛ 355line 354 didn't jump to line 355 because the condition on line 354 was never true

355 return bind.engine 

356 return bind 

357 

358 

359def get_engine() -> Engine: 

360 """Return the sync engine registered via configure().""" 

361 if _fr_config.make_session is None: 

362 raise RestlyConfigurationError("Call fr.configure() before using get_engine().") 

363 bind = _active_make_session().kw["bind"] 

364 # Under restly_session the factory is bound to a pinned Connection; resolve 

365 # its engine so this keeps returning the real Engine. 

366 if isinstance(bind, Connection): 

367 return bind.engine 

368 return bind 

369 

370 

371def _resolve_metadata(base_or_metadata: type[DeclarativeBase] | MetaData) -> MetaData: 

372 if isinstance(base_or_metadata, MetaData): 

373 return base_or_metadata 

374 metadata = getattr(base_or_metadata, "metadata", None) 

375 if isinstance(metadata, MetaData): 

376 return metadata 

377 raise TypeError( 

378 "create_all() expects a DeclarativeBase subclass or a MetaData; got " 

379 f"{base_or_metadata!r}" 

380 ) 

381 

382 

383def create_all(base_or_metadata: type[DeclarativeBase] | MetaData) -> None: 

384 """Create all tables for ``base_or_metadata`` on the configured sync engine. 

385 

386 A dev/demo convenience over ``metadata.create_all(engine)`` so a quickstart 

387 can create its schema without reaching for the raw engine:: 

388 

389 fr.db.create_all(Base) # or fr.db.create_all(Base.metadata) 

390 

391 Accepts a ``DeclarativeBase`` subclass (its ``.metadata`` is used) or a 

392 ``MetaData``. Requires :func:`configure` first. Use Alembic migrations in 

393 production. 

394 """ 

395 metadata = _resolve_metadata(base_or_metadata) 

396 if _fr_config.make_session is None: 

397 raise RestlyConfigurationError("Call fr.configure() before using create_all().") 

398 # Create against the configured bind: the engine in production, or the pinned 

399 # Connection under restly_session so the schema is visible to the test's 

400 # isolated sessions instead of silently landing on a throwaway connection. 

401 metadata.create_all(_active_make_session().kw["bind"]) 

402 

403 

404async def async_create_all(base_or_metadata: type[DeclarativeBase] | MetaData) -> None: 

405 """Async equivalent of :func:`create_all`, on the configured async engine. 

406 

407 Usage:: 

408 

409 await fr.db.async_create_all(Base) 

410 """ 

411 metadata = _resolve_metadata(base_or_metadata) 

412 if _fr_config.async_make_session is None: 

413 raise RestlyConfigurationError( 

414 "Call fr.configure() before using async_create_all()." 

415 ) 

416 bind = _active_async_make_session().kw["bind"] 

417 if isinstance(bind, AsyncConnection): 

418 # Under restly_async_session: create on the pinned connection, inside the 

419 # outer transaction, so the tables are visible to the test's sessions. 

420 await bind.run_sync(metadata.create_all) 

421 else: 

422 async with bind.begin() as conn: 

423 await conn.run_sync(metadata.create_all) 

424 

425 

426def _should_warn_uncommitted() -> bool: 

427 """The uncommitted-changes check applies whenever ``warn_on_uncommitted`` is 

428 on. Restly owns the commit, so changes still pending when a request ends are 

429 the tell of a custom write route that never committed. 

430 """ 

431 return _fr_config.warn_on_uncommitted 

432 

433 

434#: The flag of a session that flushed changes and did not commit them yet. 

435_UNCOMMITTED = "_fr_uncommitted" 

436#: The value of the flag when each open savepoint began. 

437_UNCOMMITTED_AT_SAVEPOINT = "_fr_uncommitted_at_savepoint" 

438 

439 

440def _mark_uncommitted(session: SA_Session, flush_context: Any = None) -> None: 

441 session.info[_UNCOMMITTED] = True 

442 

443 

444def _remember_uncommitted(session: SA_Session, transaction: SessionTransaction) -> None: 

445 """Keep the flag when a savepoint begins, for its rollback. 

446 

447 ``begin_nested()`` flushes what is pending before SQLAlchemy calls this, 

448 so the flag includes that flush. 

449 """ 

450 if transaction.nested: 

451 saved = session.info.setdefault( 

452 _UNCOMMITTED_AT_SAVEPOINT, weakref.WeakKeyDictionary() 

453 ) 

454 saved[transaction] = session.info.get(_UNCOMMITTED, False) 

455 

456 

457def _clear_committed(session: SA_Session) -> None: 

458 """The commit leaves nothing uncommitted. The release of a savepoint is 

459 not a commit: its changes are still uncommitted.""" 

460 if not session.in_nested_transaction(): 

461 session.info.pop(_UNCOMMITTED, None) 

462 

463 

464def _restore_rolled_back(session: SA_Session, transaction: SessionTransaction) -> None: 

465 """The rollback of the transaction leaves nothing uncommitted. The 

466 rollback of a savepoint undoes only what was flushed in it, so the flag 

467 gets its value from when the savepoint began.""" 

468 # A failed flush reports its own transaction, inside the one that it 

469 # rolled back. 

470 while transaction.parent is not None and not transaction.nested: 

471 transaction = transaction.parent 

472 saved = session.info.get(_UNCOMMITTED_AT_SAVEPOINT, {}) 

473 if transaction.nested and saved.get(transaction): 

474 session.info[_UNCOMMITTED] = True 

475 else: 

476 session.info.pop(_UNCOMMITTED, None) 

477 

478 

479def _arm_uncommitted_warning(session: SA_AsyncSession | SA_Session) -> None: 

480 """Register flush/commit/rollback listeners so an uncommitted flush at the 

481 end of a request can be detected. Async sessions delegate to a sync 

482 ``Session``; that is where ORM events fire (and whose ``info`` is shared). 

483 """ 

484 if not _should_warn_uncommitted(): 

485 return 

486 target = getattr(session, "sync_session", session) 

487 try: 

488 event.listen(target, "after_flush", _mark_uncommitted) 

489 event.listen(target, "after_transaction_create", _remember_uncommitted) 

490 event.listen(target, "after_commit", _clear_committed) 

491 event.listen(target, "after_soft_rollback", _restore_rolled_back) 

492 except Exception: 

493 # Best-effort dev aid: unusual sessions (test stubs, or session types 

494 # without ORM flush events) opt out. Never break a request. 

495 pass 

496 

497 

498def _warn_if_uncommitted(session: SA_AsyncSession | SA_Session) -> None: 

499 """Warn if the request is ending with changes that were flushed but never 

500 committed (the ``_fr_uncommitted`` flag), or added but never flushed 

501 (``new``/``dirty``/``deleted``) -- all about to be rolled back. Called only 

502 on the success path; an endpoint that raised never reaches this point. 

503 """ 

504 if not _should_warn_uncommitted(): 

505 return 

506 target = getattr(session, "sync_session", session) 

507 try: 

508 if target.info.get("_fr_suppress_uncommitted"): 

509 return 

510 uncommitted = bool( 

511 target.info.get(_UNCOMMITTED) 

512 or target.new 

513 or target.dirty 

514 or target.deleted 

515 ) 

516 except Exception: 

517 return # unusual session -> opt out silently 

518 if uncommitted: 

519 warnings.warn( 

520 "Request finished with uncommitted changes in the database session; " 

521 "they will be rolled back when the session closes. A custom write " 

522 "route must commit its changes -- bracket the mutation with " 

523 "write_action(...) (the framework then commits), or reuse " 

524 "handle_<verb>(). Only if the rollback is intentional (e.g. a " 

525 "validate-then-rollback dry run), suppress the warning for that " 

526 'route with session.info["_fr_suppress_uncommitted"] = True.', 

527 RestlyUncommittedChangesWarning, 

528 stacklevel=2, 

529 ) 

530 

531 

532async def _async_generate_session() -> AsyncIterator[SA_AsyncSession]: 

533 """FastAPI dependency for async database session.""" 

534 if _fr_config.test_async_make_session is not None: 

535 async with _fr_config.test_async_make_session() as session: 

536 yield session 

537 return 

538 if _fr_config.async_session_generator is not None: 

539 async for session in _fr_config.async_session_generator(): 

540 yield session 

541 return 

542 if _fr_config.async_make_session is None: 

543 raise RestlyConfigurationError( 

544 "Call fr.configure() before using AsyncSessionDep." 

545 ) 

546 

547 # FastAPI does not support contextmanagers as dependency directly, 

548 # but it does support generators. Restly owns the commit (the handle 

549 # design runs it inside ``handle_<verb>`` / ``write_action``), so this 

550 # dependency only manages the session lifecycle: the context manager rolls 

551 # back and closes on the way out, and any change a custom route flushed but 

552 # never committed is discarded (and warned about). 

553 async with _fr_config.async_make_session() as session: 

554 yield session 

555 

556 

557def _session_dependency(dependency: Callable[..., Any]) -> Any: 

558 depends = cast(Callable[..., Any], Depends) 

559 if "scope" in signature(Depends).parameters: 559 ↛ 561line 559 didn't jump to line 561 because the condition on line 559 was always true

560 return depends(dependency, scope="function") 

561 return depends(dependency) 

562 

563 

564def _generate_session() -> Iterator[SA_Session]: 

565 """FastAPI dependency for sync database session.""" 

566 # A test's session source wins over everything, including a generator and 

567 # anything reconfigured after the test started. 

568 if _fr_config.test_make_session is not None: 

569 with _fr_config.test_make_session() as session: 

570 yield session 

571 return 

572 if _fr_config.session_generator is not None: 

573 for session in _fr_config.session_generator(): 

574 yield session 

575 return 

576 if _fr_config.make_session is None: 

577 raise RestlyConfigurationError("Call fr.configure() before using SessionDep.") 

578 

579 with _fr_config.make_session() as session: 

580 yield session 

581 

582 

583class _SyncSessionDependency: 

584 @property 

585 def __signature__(self) -> Signature: 

586 return _session_signature("session_generator", _generate_session, SA_Session) 

587 

588 def __call__(self, session: SA_Session) -> Iterator[SA_Session]: 

589 _arm_uncommitted_warning(session) 

590 yield session 

591 _warn_if_uncommitted(session) 

592 

593 

594class _AsyncSessionDependency: 

595 @property 

596 def __signature__(self) -> Signature: 

597 return _session_signature( 

598 "async_session_generator", _async_generate_session, SA_AsyncSession 

599 ) 

600 

601 async def __call__( 

602 self, session: SA_AsyncSession 

603 ) -> AsyncIterator[SA_AsyncSession]: 

604 _arm_uncommitted_warning(session) 

605 yield session 

606 _warn_if_uncommitted(session) 

607 

608 

609def _session_signature( 

610 generator_name: str, default: Callable[..., Any], session_type: type 

611) -> Signature: 

612 """Bind the source when FastAPI builds a route's dependency graph. 

613 

614 The public alias keeps one callable identity. Its source is a sub-dependency, 

615 so an application's Depends(get_db) shares the same cached session. Reading 

616 the active context here also keeps app factories from mutating a global 

617 function signature when they configure different generators. 

618 """ 

619 _fr_config.registered_session_dependencies.add(generator_name) 

620 source = getattr(_fr_config, generator_name) 

621 dependency = Depends(source) if source is not None else _session_dependency(default) 

622 return Signature( 

623 [ 

624 Parameter( 

625 "session", 

626 Parameter.KEYWORD_ONLY, 

627 default=dependency, 

628 annotation=session_type, 

629 ) 

630 ] 

631 ) 

632 

633 

634SessionDep = Annotated[SA_Session, _session_dependency(_SyncSessionDependency())] 

635AsyncSessionDep = Annotated[ 

636 SA_AsyncSession, _session_dependency(_AsyncSessionDependency()) 

637]