Skip to content

Single Database Session Per FastAPI Request Lifecycle #728

Open
@Trinkes

Description

@Trinkes

Hello,
I would like to implement a mechanism that ensures only one database session is created and tied to the FastAPI request lifecycle. The goal is to have a single shared database session across all resources/classes within a request, allowing easy rollback of operations in case of any request-related issues.

Here's the current code example:

import os

from dependency_injector import containers, providers
from dependency_injector.wiring import Provide, inject
from fastapi import FastAPI, Depends
from sqlalchemy import create_engine
from sqlalchemy.orm import declarative_base, sessionmaker
import uvicorn

engine = create_engine("sqlite://")

Base = declarative_base()
Base.metadata.create_all(engine)
SessionLocal = sessionmaker(bind=engine)


class ApplicationContainer(containers.DeclarativeContainer):
    wiring_config = containers.WiringConfiguration(modules=[__name__])
    database: SessionLocal = providers.Factory(SessionLocal)


app = FastAPI()


@app.get("/")
@inject
async def root(
    session_1=Depends(Provide[ApplicationContainer.database]),
    session_2=Depends(Provide[ApplicationContainer.database]),
):
    return {"session_1_id": id(session_1), "session_2_id": id(session_2)}


container = ApplicationContainer()

if __name__ == "__main__":
    uvicorn.run(
        os.path.basename(__file__).replace(".py", "") + ":app",
        host="127.0.0.1",
        port=5000,
        log_level="info",
        reload=True,
    )

Currently, when calling the root endpoint, two separate database sessions are created, resulting in different session IDs:

{
  "session_1_id": 4347665504,
  "session_2_id": 4347668912
}

However, the desired behavior is to have both arguments (arg and arg2) hold references to the same database session for each request. Therefore, if we call the request again, the ID would change, indicating that a new session was created:

{
  "session_1_id": 4347665504,
  "session_2_id": 4347665504
}

The ultimate objective is to achieve a single database session per request, which would simplify the rollback process for any issues that might arise during the request.

Thank you for your attention to this matter, and I look forward to your guidance and suggestions.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions