Comments (3)
Can you try SQLAlchemyPlugin
instead of SQLAlchemyInitPlugin
?
from litestar.
Allright, the following code, using SQLAlchemyPlugin works:
from datetime import date
from typing import TYPE_CHECKING
from uuid import UUID
from sqlalchemy import ForeignKey, select
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, SQLAlchemyPlugin
from litestar.testing import create_test_client
if TYPE_CHECKING:
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession
# 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")
# The `AuditBase` class includes the same UUID` based primary key (`id`) and 2
# additional columns: `created_at` and `updated_at`. `created_at` is a timestamp of when the
# record created, and `updated_at` is the last time the record was modified.
class Book(UUIDAuditBase):
title: Mapped[str]
author_id: Mapped[UUID] = mapped_column(ForeignKey("author.id"))
author: Mapped[Author] = relationship(lazy="joined", innerjoin=True, viewonly=True)
session_config = AsyncSessionConfig(expire_on_commit=False)
sqlalchemy_config = SQLAlchemyAsyncConfig(
connection_string="sqlite+aiosqlite:///testb.sqlite", session_config=session_config
) # Create 'async_session' dependency.
sqlalchemy_plugin = SQLAlchemyPlugin(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)
async with sqlalchemy_config.get_session() as session:
session.add(Author(name="author1",dob=date(1990,1,1),id=UUID("00000000-0000-0000-0000-000000000001") ))
session.add(Book(title="blaat",author_id=UUID("00000000-0000-0000-0000-000000000001")))
await session.commit()
@get(path="/authors")
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=[SQLAlchemyPlugin(config=sqlalchemy_config)],
debug=True
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8001, log_level="debug")
A change in the documentation would be nice
from litestar.
@JorenSix Feel free to PR if you want to, if not someone else will pick this up as per their availability
from litestar.
Related Issues (20)
- Bug(OpenAPI): Schema generation doesn't resolve signature types for "nested" objects
- Bug: OpenAPI error: type object '<MyInputModel>' has no attribute '__parameters__'
- Enhancement: Celery integration HOT 1
- Enhancement: Provide test client that can handle infinite SSE generators
- Bug: missing computed_fields for pydantic dto models
- Enhancement: Get api endpoint description from a docstring HOT 1
- Bug: tag_field not presented on swagger schemas when using Union
- Bug: OpenTelemetry Middleware Doesn't Capture Exceptions Raised Before Route Handler HOT 6
- Bug: Generic Controller SQLAlchemyDTO SerializationException: Unsupported type HOT 1
- Bug: Generic Controller OpenAPI broken (models not generated) HOT 1
- Bug: handler kwargs name affect request validator HOT 5
- Bug: `request.session` may be Empty but it typed as `dict[str, Any]` HOT 5
- Enhancement: Allow streaming Templates to serve very large content
- Bug: Using DTOData with the codegen backend decodes data incorrectly HOT 3
- Enhancement: Support attrs converters HOT 1
- bug: inconsistent behavior between `signature_namespace` and `signature_types` HOT 2
- Enhancement: need a way to update csrf token if secret changed HOT 2
- Enhancement: no way to disable csrf and session middleware on some router HOT 3
- Bug: can't reload app on windows HOT 2
- Bug: `Request.url.scheme` doesn't match `scope['scheme']` HOT 3
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from litestar.