|
1 | 1 | import math |
2 | 2 | import os |
3 | 3 | from collections.abc import AsyncGenerator, Awaitable, Callable, Iterable |
4 | | -from contextlib import asynccontextmanager |
| 4 | +from contextlib import _AsyncGeneratorContextManager, asynccontextmanager |
5 | 5 | from typing import Annotated, Generic, TypeVar, TypedDict |
6 | 6 |
|
7 | 7 | from fastapi import Depends, FastAPI, Query |
@@ -78,79 +78,118 @@ class State(TypedDict): |
78 | 78 | fastsqla_engine: AsyncEngine |
79 | 79 |
|
80 | 80 |
|
81 | | -@asynccontextmanager |
82 | | -async def lifespan(app: FastAPI) -> AsyncGenerator[State, None]: |
83 | | - """Use `fastsqla.lifespan` to set up SQLAlchemy. |
84 | | -
|
85 | | - In an ASGI application, [lifespan events](https://asgi.readthedocs.io/en/latest/specs/lifespan.html) |
86 | | - are used to communicate startup & shutdown events. |
| 81 | +def new_lifespan( |
| 82 | + url: str | None = None, **kw |
| 83 | +) -> Callable[[FastAPI], _AsyncGeneratorContextManager[State, None]]: |
| 84 | + """Create a new lifespan async context manager. |
87 | 85 |
|
88 | | - The [`lifespan`](https://fastapi.tiangolo.com/advanced/events/#lifespan) parameter of |
89 | | - the `FastAPI` app can be assigned to a context manager, which is opened when the app |
90 | | - starts and closed when the app stops. |
| 86 | + It expects the exact same parameters as |
| 87 | + [`sqlalchemy.ext.asyncio.create_async_engine`][sqlalchemy.ext.asyncio.create_async_engine] |
91 | 88 |
|
92 | | - In order for `FastSQLA` to setup `SQLAlchemy` before the app is started, set |
93 | | - `lifespan` parameter to `fastsqla.lifespan`: |
| 89 | + Example: |
94 | 90 |
|
95 | 91 | ```python |
96 | 92 | from fastapi import FastAPI |
97 | | - from fastsqla import lifespan |
| 93 | + from fastsqla import new_lifespan |
98 | 94 |
|
| 95 | + lifespan = new_lifespan( |
| 96 | + "sqlite+aiosqlite:///app/db.sqlite", connect_args={"autocommit": False} |
| 97 | + ) |
99 | 98 |
|
100 | 99 | app = FastAPI(lifespan=lifespan) |
101 | 100 | ``` |
102 | 101 |
|
103 | | - If multiple lifespan contexts are required, create an async context manager function |
104 | | - to handle them and set it as the app's lifespan: |
| 102 | + Args: |
| 103 | + url (str): Database url. |
| 104 | + kw (dict): Configuration parameters as expected by [`sqlalchemy.ext.asyncio.create_async_engine`][sqlalchemy.ext.asyncio.create_async_engine] |
| 105 | + """ |
105 | 106 |
|
106 | | - ```python |
107 | | - from collections.abc import AsyncGenerator |
108 | | - from contextlib import asynccontextmanager |
| 107 | + has_config = url is not None |
109 | 108 |
|
110 | | - from fastapi import FastAPI |
111 | | - from fastsqla import lifespan as fastsqla_lifespan |
112 | | - from this_other_library import another_lifespan |
| 109 | + @asynccontextmanager |
| 110 | + async def lifespan(app: FastAPI) -> AsyncGenerator[State, None]: |
| 111 | + if has_config: |
| 112 | + prefix = "" |
| 113 | + sqla_config = {**kw, **{"url": url}} |
113 | 114 |
|
| 115 | + else: |
| 116 | + prefix = "sqlalchemy_" |
| 117 | + sqla_config = {k.lower(): v for k, v in os.environ.items()} |
114 | 118 |
|
115 | | - @asynccontextmanager |
116 | | - async def lifespan(app:FastAPI) -> AsyncGenerator[dict, None]: |
117 | | - async with AsyncExitStack() as stack: |
118 | | - yield { |
119 | | - **stack.enter_async_context(lifespan(app)), |
120 | | - **stack.enter_async_context(another_lifespan(app)), |
121 | | - } |
| 119 | + try: |
| 120 | + engine = async_engine_from_config(sqla_config, prefix=prefix) |
122 | 121 |
|
| 122 | + except KeyError as exc: |
| 123 | + raise Exception(f"Missing {prefix}{exc.args[0]} in environ.") from exc |
123 | 124 |
|
124 | | - app = FastAPI(lifespan=lifespan) |
125 | | - ``` |
| 125 | + async with engine.begin() as conn: |
| 126 | + await conn.run_sync(Base.prepare) |
126 | 127 |
|
127 | | - To learn more about lifespan protocol: |
| 128 | + SessionFactory.configure(bind=engine) |
128 | 129 |
|
129 | | - * [Lifespan Protocol](https://asgi.readthedocs.io/en/latest/specs/lifespan.html) |
130 | | - * [Use Lifespan State instead of `app.state`](https://github.com/Kludex/fastapi-tips?tab=readme-ov-file#6-use-lifespan-state-instead-of-appstate) |
131 | | - * [FastAPI lifespan documentation](https://fastapi.tiangolo.com/advanced/events/) |
132 | | - """ |
133 | | - prefix = "sqlalchemy_" |
134 | | - sqla_config = {k.lower(): v for k, v in os.environ.items()} |
135 | | - try: |
136 | | - engine = async_engine_from_config(sqla_config, prefix=prefix) |
| 130 | + await logger.ainfo("Configured SQLAlchemy.") |
137 | 131 |
|
138 | | - except KeyError as exc: |
139 | | - raise Exception(f"Missing {prefix}{exc.args[0]} in environ.") from exc |
| 132 | + yield {"fastsqla_engine": engine} |
140 | 133 |
|
141 | | - async with engine.begin() as conn: |
142 | | - await conn.run_sync(Base.prepare) |
| 134 | + SessionFactory.configure(bind=None) |
| 135 | + await engine.dispose() |
143 | 136 |
|
144 | | - SessionFactory.configure(bind=engine) |
| 137 | + await logger.ainfo("Cleared SQLAlchemy config.") |
145 | 138 |
|
146 | | - await logger.ainfo("Configured SQLAlchemy.") |
| 139 | + return lifespan |
147 | 140 |
|
148 | | - yield {"fastsqla_engine": engine} |
149 | 141 |
|
150 | | - SessionFactory.configure(bind=None) |
151 | | - await engine.dispose() |
| 142 | +lifespan = new_lifespan() |
| 143 | +"""Use `fastsqla.lifespan` to set up SQLAlchemy directly from environment variables. |
152 | 144 |
|
153 | | - await logger.ainfo("Cleared SQLAlchemy config.") |
| 145 | +In an ASGI application, [lifespan events](https://asgi.readthedocs.io/en/latest/specs/lifespan.html) |
| 146 | +are used to communicate startup & shutdown events. |
| 147 | +
|
| 148 | +The [`lifespan`](https://fastapi.tiangolo.com/advanced/events/#lifespan) parameter of |
| 149 | +the `FastAPI` app can be assigned to a context manager, which is opened when the app |
| 150 | +starts and closed when the app stops. |
| 151 | +
|
| 152 | +In order for `FastSQLA` to setup `SQLAlchemy` before the app is started, set |
| 153 | +`lifespan` parameter to `fastsqla.lifespan`: |
| 154 | +
|
| 155 | +```python |
| 156 | +from fastapi import FastAPI |
| 157 | +from fastsqla import lifespan |
| 158 | +
|
| 159 | +
|
| 160 | +app = FastAPI(lifespan=lifespan) |
| 161 | +``` |
| 162 | +
|
| 163 | +If multiple lifespan contexts are required, create an async context manager function |
| 164 | +to handle them and set it as the app's lifespan: |
| 165 | +
|
| 166 | +```python |
| 167 | +from collections.abc import AsyncGenerator |
| 168 | +from contextlib import asynccontextmanager |
| 169 | +
|
| 170 | +from fastapi import FastAPI |
| 171 | +from fastsqla import lifespan as fastsqla_lifespan |
| 172 | +from this_other_library import another_lifespan |
| 173 | +
|
| 174 | +
|
| 175 | +@asynccontextmanager |
| 176 | +async def lifespan(app:FastAPI) -> AsyncGenerator[dict, None]: |
| 177 | + async with AsyncExitStack() as stack: |
| 178 | + yield { |
| 179 | + **stack.enter_async_context(lifespan(app)), |
| 180 | + **stack.enter_async_context(another_lifespan(app)), |
| 181 | + } |
| 182 | +
|
| 183 | +
|
| 184 | +app = FastAPI(lifespan=lifespan) |
| 185 | +``` |
| 186 | +
|
| 187 | +To learn more about lifespan protocol: |
| 188 | +
|
| 189 | +* [Lifespan Protocol](https://asgi.readthedocs.io/en/latest/specs/lifespan.html) |
| 190 | +* [Use Lifespan State instead of `app.state`](https://github.com/Kludex/fastapi-tips?tab=readme-ov-file#6-use-lifespan-state-instead-of-appstate) |
| 191 | +* [FastAPI lifespan documentation](https://fastapi.tiangolo.com/advanced/events/) |
| 192 | +""" |
154 | 193 |
|
155 | 194 |
|
156 | 195 | @asynccontextmanager |
|
0 commit comments