Skip to content

Commit

Permalink
docs: SQLAlchemyInitPlugin to SQLAlchemyPlugin fixes SerializationExc…
Browse files Browse the repository at this point in the history
…eption for docs (#3475)

* Update sqlalchemy_declarative_models.py

Now uses the SQLAlchemyPlugin in stead of SQLAlchemyInitPlugin, see #3464

* Update sqlalchemy_declarative_models.py

Ruff lint fixes

* Update docs/examples/contrib/sqlalchemy/sqlalchemy_declarative_models.py

create_all flag

Co-authored-by: Cody Fincher <[email protected]>

* Update docs/examples/contrib/sqlalchemy/sqlalchemy_declarative_models.py

Co-authored-by: Peter Schutt <[email protected]>

* Update docs/examples/contrib/sqlalchemy/sqlalchemy_declarative_models.py

Further documentation

Co-authored-by: Peter Schutt <[email protected]>

* Update docs/examples/contrib/sqlalchemy/sqlalchemy_declarative_models.py

Co-authored-by: Peter Schutt <[email protected]>

* Update docs/examples/contrib/sqlalchemy/sqlalchemy_declarative_models.py

Co-authored-by: Cody Fincher <[email protected]>

* Unit test for sqlalchemy_declarative_models.

* Now using option create_all=True for meta-data, on_startup for dummy data

* Lint ruff-format compatibility

* Fix for 3.9 and 3.10 wrt class declarations/typing

* Ruff format check

* Removed comments which might be heavy for example code

* For 3.8 compatibility wrt typing now using List in stead of list

* Replaced incorrect use of List instead of List

---------

Co-authored-by: Cody Fincher <[email protected]>
Co-authored-by: Peter Schutt <[email protected]>
  • Loading branch information
3 people committed May 17, 2024
1 parent 142bfe3 commit 5afa40f
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 14 deletions.
35 changes: 21 additions & 14 deletions docs/examples/contrib/sqlalchemy/sqlalchemy_declarative_models.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,25 @@
from __future__ import annotations

import uuid
from datetime import date
from typing import TYPE_CHECKING
from typing import List
from uuid import UUID

from sqlalchemy import ForeignKey, select
from sqlalchemy import ForeignKey, func, select
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession
from sqlalchemy.orm import Mapped, mapped_column, relationship

from litestar import Litestar, get
from litestar.contrib.sqlalchemy.base import UUIDAuditBase, UUIDBase
from litestar.contrib.sqlalchemy.plugins import AsyncSessionConfig, SQLAlchemyAsyncConfig, SQLAlchemyInitPlugin

if TYPE_CHECKING:
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession
from litestar.contrib.sqlalchemy.plugins import AsyncSessionConfig, SQLAlchemyAsyncConfig, SQLAlchemyPlugin


# the SQLAlchemy base includes a declarative model for you to use in your models.
# The `Base` class includes a `UUID` based primary key (`id`)
class Author(UUIDBase):
name: Mapped[str]
dob: Mapped[date]
books: Mapped[list["Book"]] = relationship(back_populates="author", lazy="selectin")
books: Mapped[List[Book]] = relationship(back_populates="author", lazy="selectin")


# The `AuditBase` class includes the same UUID` based primary key (`id`) and 2
Expand All @@ -32,25 +33,31 @@ class Book(UUIDAuditBase):

session_config = AsyncSessionConfig(expire_on_commit=False)
sqlalchemy_config = SQLAlchemyAsyncConfig(
connection_string="sqlite+aiosqlite:///test.sqlite", session_config=session_config
connection_string="sqlite+aiosqlite:///test.sqlite", session_config=session_config, create_all=True
) # Create 'async_session' dependency.
sqlalchemy_plugin = SQLAlchemyInitPlugin(config=sqlalchemy_config)


async def on_startup() -> None:
"""Initializes the database."""
async with sqlalchemy_config.get_engine().begin() as conn:
await conn.run_sync(UUIDBase.metadata.create_all)
"""Adds some dummy data if no data is present."""
async with sqlalchemy_config.get_session() as session:
statement = select(func.count()).select_from(Author)
count = await session.execute(statement)
if not count.scalar():
author_id = uuid.uuid4()
session.add(Author(name="Stephen King", dob=date(1954, 9, 21), id=author_id))
session.add(Book(title="It", author_id=author_id))
await session.commit()


@get(path="/authors")
async def get_authors(db_session: "AsyncSession", db_engine: "AsyncEngine") -> list[Author]:
async def get_authors(db_session: AsyncSession, db_engine: AsyncEngine) -> List[Author]:
"""Interact with SQLAlchemy engine and session."""
return list(await db_session.scalars(select(Author)))


app = Litestar(
route_handlers=[get_authors],
on_startup=[on_startup],
plugins=[SQLAlchemyInitPlugin(config=sqlalchemy_config)],
debug=True,
plugins=[SQLAlchemyPlugin(config=sqlalchemy_config)],
)
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,7 @@ known-first-party = ["litestar", "tests", "examples"]
"docs/examples/application_hooks/before_send_hook.py" = ["UP006"]
"docs/examples/contrib/sqlalchemy/plugins/**/*.*" = ["UP006"]
"docs/examples/data_transfer_objects**/*.*" = ["UP006"]
"docs/examples/contrib/sqlalchemy/sqlalchemy_declarative_models.py" = ["UP006"]
"litestar/_openapi/schema_generation/schema.py" = ["C901"]
"litestar/exceptions/*.*" = ["N818"]
"litestar/handlers/**/*.*" = ["N801"]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import pytest

from litestar.testing import TestClient

pytestmark = pytest.mark.xdist_group("sqlalchemy_examples")


def test_sqlalchemy_declarative_models() -> None:
from docs.examples.contrib.sqlalchemy.sqlalchemy_declarative_models import app

with TestClient(app) as client:
response = client.get("/authors")
assert response.status_code == 200
assert len(response.json()) > 0

0 comments on commit 5afa40f

Please sign in to comment.