|
| 1 | +import os |
| 2 | +from fastapi import FastAPI, Request, Form |
| 3 | +from fastapi.templating import Jinja2Templates |
| 4 | +from fastapi.responses import RedirectResponse |
| 5 | +import asyncpg |
| 6 | +from contextlib import asynccontextmanager |
| 7 | +from pydantic import BaseModel |
| 8 | +from databases import Database |
| 9 | +from dotenv import load_dotenv |
| 10 | + |
| 11 | +load_dotenv() |
| 12 | + |
| 13 | +database_url = os.getenv("DATABASE_URL") |
| 14 | +print(f"Connecting to database at: {database_url}") |
| 15 | +database = Database(database_url) |
| 16 | + |
| 17 | + |
| 18 | +class TodoItem(BaseModel): |
| 19 | + id: int |
| 20 | + task: str |
| 21 | + completed: bool = False |
| 22 | + |
| 23 | +@asynccontextmanager |
| 24 | +async def lifespan(app: FastAPI): |
| 25 | + await database.connect() |
| 26 | + conn = await asyncpg.connect(database_url) |
| 27 | + await conn.execute(''' |
| 28 | + CREATE TABLE IF NOT EXISTS todos ( |
| 29 | + id SERIAL PRIMARY KEY, |
| 30 | + task VARCHAR(255) NOT NULL, |
| 31 | + completed BOOLEAN DEFAULT FALSE |
| 32 | + ); |
| 33 | + ''') |
| 34 | + await conn.close() |
| 35 | + yield |
| 36 | + await database.disconnect() |
| 37 | + |
| 38 | +app = FastAPI(lifespan=lifespan) |
| 39 | +templates = Jinja2Templates(directory="templates") |
| 40 | + |
| 41 | + |
| 42 | +@app.get("/") |
| 43 | +async def get_todos(request: Request): |
| 44 | + query = "SELECT * FROM todos" |
| 45 | + todos = await database.fetch_all(query) |
| 46 | + return templates.TemplateResponse("index.html", {"request": request, "todos": todos}) |
| 47 | + |
| 48 | +@app.post("/add") |
| 49 | +async def create_todo(task: str = Form(...)): |
| 50 | + query = "INSERT INTO todos(task, completed) VALUES (:task, :completed)" |
| 51 | + values = {"task": task, "completed": False} |
| 52 | + await database.execute(query, values) |
| 53 | + return RedirectResponse(url="/", status_code=303) |
| 54 | + |
| 55 | +@app.post("/delete/{todo_id}") |
| 56 | +async def delete_todo(todo_id: int): |
| 57 | + query = "DELETE FROM todos WHERE id = :todo_id" |
| 58 | + await database.execute(query, {"todo_id": todo_id}) |
| 59 | + return RedirectResponse(url="/", status_code=303) |
0 commit comments