Open qcdyx opened 1 week ago
The focus is not just on replacing the global engine but also on managing session lifecycle per request. To achieve this, I applied a context manager to ensure sessions are properly closed after each request. This approach also aligns with my investigation in May into using FastAPI dependency injection with connection pooling for better session handling.
Refactor the code to use a shared engine upon open and close session per request, avoiding redundant engine/pool creation. A global engine is safe to share across threads because SQLAlchemy's Engine object is designed to be thread-safe. Using a global engine ensures that all database interactions reuse the same pool of connections without creating redundant engines.