From 61138f7fcbf11a3368a3242e07da3c81b8b3e78e Mon Sep 17 00:00:00 2001 From: Drew Bednar Date: Sat, 28 Oct 2023 19:00:27 -0400 Subject: [PATCH] Simple todo --- learn_litestar/app.py | 54 ++++++++++++++++++++++++++++++++++++++++--- tasks.py | 4 ++-- 2 files changed, 53 insertions(+), 5 deletions(-) diff --git a/learn_litestar/app.py b/learn_litestar/app.py index 4f552a0..c30818a 100644 --- a/learn_litestar/app.py +++ b/learn_litestar/app.py @@ -1,10 +1,58 @@ +from dataclasses import dataclass + from litestar import Litestar from litestar import get +from litestar import post +from litestar import put +from litestar.exceptions import NotFoundException + + +@dataclass +class TodoItem: + title: str + + done: bool + + +TODO_LIST: list[TodoItem] = [ + TodoItem(title="Start writing TODO list", done=True), + TodoItem(title="???", done=False), + TodoItem(title="Profit", done=False), +] + + +def get_todo_by_title(todo_name) -> TodoItem: + for item in TODO_LIST: + if item.title == todo_name: + return item + + raise NotFoundException(detail=f"TODO {todo_name!r} not found") @get("/") -async def index() -> str: - return "

Hello Litestar

" +async def get_list(done: bool | None = None) -> list[TodoItem]: + if done is None: + return TODO_LIST + + return [item for item in TODO_LIST if item.done == done] + + +@post("/") +async def add_item(data: TodoItem) -> list[TodoItem]: + TODO_LIST.append(data) + + return TODO_LIST + + +@put("/{item_title:str}") +async def update_item(item_title: str, data: TodoItem) -> list[TodoItem]: + todo_item = get_todo_by_title(item_title) + + todo_item.title = data.title + + todo_item.done = data.done + + return TODO_LIST -app = Litestar([index]) +app = Litestar([get_list, add_item, update_item]) diff --git a/tasks.py b/tasks.py index 8f47fb7..8e6f292 100644 --- a/tasks.py +++ b/tasks.py @@ -1,11 +1,11 @@ from invoke import task -@task +@task(name="dev") def serve_dev(c): """Runs the development server of this litestar project""" c.run("echo 'Starting dev server'") - c.run("LITESTAR_APP=learn_litestar.app:app litestar run") + c.run("LITESTAR_APP=learn_litestar.app:app litestar run --reload") @task