From 7a3b11dc32e382ca44c8353302c1604002246d98 Mon Sep 17 00:00:00 2001 From: Yaro Kasear Date: Thu, 25 Sep 2025 09:32:07 -0500 Subject: [PATCH] Minor change to service. --- crudkit/core/service.py | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/crudkit/core/service.py b/crudkit/core/service.py index 5f713ed..262499d 100644 --- a/crudkit/core/service.py +++ b/crudkit/core/service.py @@ -1,6 +1,7 @@ from __future__ import annotations from collections.abc import Iterable +from flask import current_app from typing import Any, Callable, Type, TypeVar, Generic, Optional, Protocol, runtime_checkable, cast from sqlalchemy import and_, func, inspect, or_, text from sqlalchemy.engine import Engine, Connection @@ -133,24 +134,25 @@ class CRUDService(Generic[T]): self.polymorphic = polymorphic self.supports_soft_delete = hasattr(model, 'is_deleted') - # Derive engine WITHOUT leaking a session/connection - bind = getattr(session_factory, "bind", None) - if bind is None: - tmp_sess = session_factory() - try: - bind = tmp_sess.get_bind() - finally: - try: - tmp_sess.close() - except Exception: - pass - - eng: Engine = bind.engine if isinstance(bind, Connection) else cast(Engine, bind) - self.backend = backend or make_backend_info(eng) + self._backend: Optional[BackendInfo] = backend @property def session(self) -> Session: - return self._session_factory() + """Always return the Flask-scoped Session if available; otherwise the provided factory.""" + try: + sess = current_app.extensions["crudkit"]["Session"] + return sess + except Exception: + return self._session_factory() + + @property + def backend(self) -> BackendInfo: + """Resolve backend info lazily against the active session's engine.""" + if self._backend is None: + bind = self.session.get_bind() + eng: Engine = bind.engine if isinstance(bind, Connection) else cast(Engine, bind) + self._backend = make_backend_info(eng) + return self._backend def get_query(self): if self.polymorphic: