| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from typing import TYPE_CHECKING |
| 4 |
|
| 5 |
from sqlalchemy import text |
| 6 |
|
| 7 |
from litestar import Litestar, get |
| 8 |
from litestar.di import NamedDependency |
| 9 |
from litestar.plugins.sqlalchemy import SQLAlchemyInitPlugin, SQLAlchemySyncConfig |
| 10 |
|
| 11 |
if TYPE_CHECKING: |
| 12 |
from sqlalchemy import Engine |
| 13 |
from sqlalchemy.orm import Session |
| 14 |
|
| 15 |
|
| 16 |
@get(path="/sqlalchemy-app", sync_to_thread=True) |
| 17 |
def async_sqlalchemy_init(db_session: NamedDependency[Session], db_engine: NamedDependency[Engine]) -> str: |
| 18 |
"""Interact with SQLAlchemy engine and session.""" |
| 19 |
one = db_session.execute(text("SELECT 1")).scalar_one() |
| 20 |
|
| 21 |
with db_engine.connect() as conn: |
| 22 |
two = conn.execute(text("SELECT 2")).scalar_one() |
| 23 |
|
| 24 |
return f"{one} {two}" |
| 25 |
|
| 26 |
|
| 27 |
sqlalchemy_config = SQLAlchemySyncConfig(connection_string="sqlite:///test.sqlite") |
| 28 |
|
| 29 |
app = Litestar( |
| 30 |
route_handlers=[async_sqlalchemy_init], |
| 31 |
plugins=[SQLAlchemyInitPlugin(config=sqlalchemy_config)], |
| 32 |
) |