Debian Codegraph @

docs/examples/todo_app/full_app.py

raw
1 from dataclasses import dataclass
2 from typing import List, Optional
3
4 from litestar import Litestar, get, post, put
5 from litestar.exceptions import NotFoundException
6 from litestar.params import FromPath, FromQuery
7
8
9 @dataclass
10 class TodoItem:
11 title: str
12 done: bool
13
14
15 TODO_LIST: List[TodoItem] = [
16 TodoItem(title="Start writing TODO list", done=True),
17 TodoItem(title="???", done=False),
18 TodoItem(title="Profit", done=False),
19 ]
20
21
22 def get_todo_by_title(todo_name: str) -> TodoItem:
23 for item in TODO_LIST:
24 if item.title == todo_name:
25 return item
26 raise NotFoundException(detail=f"TODO {todo_name!r} not found")
27
28
29 @get("/")
30 async def get_list(done: FromQuery[Optional[bool]] = None) -> List[TodoItem]:
31 if done is None:
32 return TODO_LIST
33 return [item for item in TODO_LIST if item.done == done]
34
35
36 @post("/")
37 async def add_item(data: TodoItem) -> List[TodoItem]:
38 TODO_LIST.append(data)
39 return TODO_LIST
40
41
42 @put("/{item_title:str}")
43 async def update_item(item_title: FromPath[str], data: TodoItem) -> List[TodoItem]:
44 todo_item = get_todo_by_title(item_title)
45 todo_item.title = data.title
46 todo_item.done = data.done
47 return TODO_LIST
48
49
50 app = Litestar([get_list, add_item, update_item])