Skip to content

Instantly share code, notes, and snippets.

@johnowhitaker
Created May 30, 2024 21:53
Show Gist options
  • Save johnowhitaker/1a9d63f640cf01bb6c6f41fb97b28e67 to your computer and use it in GitHub Desktop.
Save johnowhitaker/1a9d63f640cf01bb6c6f41fb97b28e67 to your computer and use it in GitHub Desktop.
No htmx todo app
from starlette.responses import FileResponse, RedirectResponse
from fastcore.utils import *
from fastcore.xml import *
from fasthtml import *
from sqlite_utils import Database
from fastlite import *
from fastlite.kw import *
db = Database('todos.db')
todos = db['todos']
Todo = todos.dataclass()
@patch
def __xt__(self:Todo):
name = S(self.title) if self.done else B(self.title)
delete = A('delete', href=f'/delete_todo/{self.id}')
edit = A('edit', href=f'/edit/{self.id}')
done = '✓' if self.done else A('mark as done', href=f'/complete_todo/{self.id}')
return Li(name, ' | ', done, ' | ', edit, ' | ', delete)
app = FastHTML(hdrs=(picolink,picolink))
@app.get("/{fname:path}.{ext:static}")
async def static(fname:str, ext:str): return FileResponse(f'{fname}.{ext}')
@app.get("/")
async def get_todos():
add = Form(Group(
Input(id="new-title", name="title", placeholder="New Todo"),
Button("Add")), action="/add_todo")
card = Card(Ul(*todos()), header=add),
title = "TODO List"
return title, Main(H1(title), card, cls='container')
@app.get("/add_todo")
async def add_item(title:str):
todos.insert(Todo(title))
return RedirectResponse("/")
@app.get("/delete_todo/{id}")
async def del_todo(id:int):
todos.delete(id)
return RedirectResponse("/")
@app.get("/complete_todo/{id}")
async def complete_todo(id:int):
todo = todos.get(id)
todo.done = True
todos.upsert(todo)
return RedirectResponse("/")
@app.get("/update_todo")
async def update_todo(id:int, title:str, done:bool):
todo = Todo(id=id, title=title, done=done)
print("Updating", todo)
todos.upsert(todo)
return RedirectResponse("/")
@app.get("/edit/{id}")
async def edit_item(id:int):
f = Form(Group(Input(id="title"), Button("Save")),
Hidden(id="id"), Checkbox(id="done", label='Done'),
action = f'/update_todo')
f = fill_form(f, todos.get(id))
return "Editing TODO", Main(H1(f'Edit TODO {id}'), f, cls='container')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment