Skip to content

Commit b8c45fc

Browse files
committed
feat: Add Middleware for ASGI applications
1 parent a453939 commit b8c45fc

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

sqlalchemy_database/_abc_async_database.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,19 @@ def __init__(self) -> None:
2727
if not asyncio.iscoroutinefunction(func):
2828
func = functools.partial(to_thread, func)
2929
setattr(self, f"async_{func_name}", func)
30+
31+
async def asgi_dispatch(self, request, call_next):
32+
"""Middleware for ASGI applications, such as: Starlette, FastAPI, Quart, Sanic, Hug, Responder, etc.
33+
Bind a SQLAlchemy session connection to the incoming HTTP request session context,
34+
you can access the session object through `self.session`.
35+
The instance shortcut method will also try to use this `session` object by default.
36+
Example:
37+
```Python
38+
app = FastAPI()
39+
db = Database.create("sqlite:///test.db")
40+
app.add_middleware(BaseHTTPMiddleware, db.asgi_dispatch)
41+
```
42+
"""
43+
async with self:
44+
response = await call_next(request)
45+
return response

sqlalchemy_database/_abc_async_database.pyi

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,3 +91,4 @@ class AbcAsyncDatabase(metaclass=abc.ABCMeta):
9191
executor: Union[Session, Connection, AsyncSession, AsyncConnection, None] = None,
9292
**kwargs: _P.kwargs,
9393
) -> Union[_T, _R]: ...
94+
async def asgi_dispatch(self, request, call_next): ...

0 commit comments

Comments
 (0)