| 1 |
from datetime import datetime |
| 2 |
|
| 3 |
from sqlalchemy.orm import Mapped, mapped_column |
| 4 |
|
| 5 |
from litestar import Litestar, post |
| 6 |
from litestar.dto import dto_field |
| 7 |
from litestar.plugins.sqlalchemy import SQLAlchemyDTO |
| 8 |
|
| 9 |
from .my_lib import Base |
| 10 |
|
| 11 |
|
| 12 |
class User(Base): |
| 13 |
# `Base` defines `id` field as: |
| 14 |
# id: Mapped[UUID] = mapped_column(default=uuid4, primary_key=True) |
| 15 |
name: Mapped[str] |
| 16 |
password: Mapped[str] = mapped_column(info=dto_field("private")) |
| 17 |
created_at: Mapped[datetime] = mapped_column(info=dto_field("read-only")) |
| 18 |
|
| 19 |
|
| 20 |
UserDTO = SQLAlchemyDTO[User] |
| 21 |
|
| 22 |
|
| 23 |
@post("/users", dto=UserDTO, sync_to_thread=False) |
| 24 |
def create_user(data: User) -> User: |
| 25 |
# even though the client did not send the id field, |
| 26 |
# since it is a primary key it is autogenerated |
| 27 |
assert "id" in vars(data) |
| 28 |
# even though the client sent the password and created_at field, it is not in the data object |
| 29 |
assert "password" not in vars(data) |
| 30 |
assert "created_at" not in vars(data) |
| 31 |
# normally the database would set the created_at timestamp |
| 32 |
data.created_at = datetime.min |
| 33 |
return data # the response includes the created_at field |
| 34 |
|
| 35 |
|
| 36 |
app = Litestar(route_handlers=[create_user]) |
| 37 |
|
| 38 |
# run: /users -H "Content-Type: application/json" -d '{"name":"Litestar User","password":"xyz","created_at":"2023-04-24T00:00:00Z"}' |