Encapsulates all Tortoise ORM state for a single execution context. Each TortoiseContext instance owns: - A ConnectionHandler with database connections - An Apps registry with model definitions - Initialization state tracking Use cases: - Isolated test environments (py
| 117 | |
| 118 | |
| 119 | class TortoiseContext: |
| 120 | """ |
| 121 | Encapsulates all Tortoise ORM state for a single execution context. |
| 122 | |
| 123 | Each TortoiseContext instance owns: |
| 124 | - A ConnectionHandler with database connections |
| 125 | - An Apps registry with model definitions |
| 126 | - Initialization state tracking |
| 127 | |
| 128 | Use cases: |
| 129 | - Isolated test environments (pytest fixtures) |
| 130 | - Parallel test execution with pytest-xdist |
| 131 | - Multiple database configurations in the same process |
| 132 | - Scoped database sessions with automatic cleanup |
| 133 | |
| 134 | The context is tracked via contextvars, allowing async code to |
| 135 | automatically resolve the correct connections without explicit passing. |
| 136 | |
| 137 | Example: |
| 138 | async with TortoiseContext() as ctx: |
| 139 | await ctx.init( |
| 140 | db_url="sqlite://:memory:", |
| 141 | modules={"models": ["myapp.models"]} |
| 142 | ) |
| 143 | await ctx.generate_schemas() |
| 144 | # Models use this context's connections automatically |
| 145 | user = await User.create(name="test") |
| 146 | """ |
| 147 | |
| 148 | def __init__(self) -> None: |
| 149 | self._connections: ConnectionHandler | None = None |
| 150 | self._apps: Apps | None = None |
| 151 | self._inited: bool = False |
| 152 | self._token: contextvars.Token[TortoiseContext | None] | None = None |
| 153 | self._table_name_generator: Callable[[type[Model]], str] | None = None |
| 154 | self._default_connection: str | None = None |
| 155 | # Timezone settings |
| 156 | self._use_tz: bool = True |
| 157 | self._timezone: str = "UTC" |
| 158 | # Routers |
| 159 | self._routers: list[type] = [] |
| 160 | |
| 161 | @property |
| 162 | def connections(self) -> ConnectionHandler: |
| 163 | """ |
| 164 | Get the ConnectionHandler for this context. |
| 165 | |
| 166 | Creates a new ConnectionHandler on first access (lazy initialization). |
| 167 | The handler uses instance-level storage for true isolation between contexts. |
| 168 | |
| 169 | Returns: |
| 170 | The ConnectionHandler instance owned by this context. |
| 171 | """ |
| 172 | if self._connections is None: |
| 173 | # ConnectionHandler always uses instance storage for isolation |
| 174 | self._connections = ConnectionHandler() |
| 175 | return self._connections |
| 176 |
no outgoing calls
searching dependent graphs…