EduardSchwarzkopf / pecuny

Pecuny written with fastapi
5 stars 2 forks source link

handling database sessions #75

Closed EduardSchwarzkopf closed 8 months ago

EduardSchwarzkopf commented 9 months ago

In your FastAPI application, using db.engine.dispose() at the end of each request to manage database sessions is not the recommended approach. Instead, you should manage database sessions using context managers or dependency injection, which ensures that the session is properly closed after use, even if an error occurs. This is a more robust and error-resistant way to handle database sessions.

The recommended approach involves creating a dependency function that yields a database session. This function can be used in your route functions via FastAPI's dependency injection system. Here's an example based on the provided sources:

from fastapi import Depends, FastAPI, HTTPException
from sqlalchemy.orm import Session
from . import crud, models, schemas
from .database import SessionLocal, engine

models.Base.metadata.create_all(bind=engine)

app = FastAPI()

# Dependency
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

In this setup, get_db is a dependency function that creates a new database session, yields it for use in the route function, and then ensures the session is closed after the route function completes. This pattern is demonstrated in the provided examples from Source 0 and Source 4, where get_db is used to inject a database session into route functions.

Using this approach, you don't need to manually call db.engine.dispose() at the end of each request. Instead, the finally block in the get_db function ensures that the session is properly closed, regardless of whether the request was successful or an exception was raised. This method is more aligned with the best practices for managing database sessions in FastAPI applications, as it leverages the framework's dependency injection system to handle session lifecycle management.

Reference:

  1. https://dev.to/uponthesky/python-post-reviewhow-to-implement-a-transactional-decorator-in-fastapi-sqlalchemy-ein
  2. https://medium.com/@konstantine.dvalishvil/transactional-methods-fastapi-sqlalchemy-6f33370b95dd
  3. https://hackernoon.com/efficient-session-handling-using-the-repository-pattern-in-fastapi
  4. https://fastapi.tiangolo.com/tutorial/sql-databases/
EduardSchwarzkopf commented 8 months ago

this is done with https://github.com/EduardSchwarzkopf/pecuny/pull/76