fireup / example-guestbook read public
fireme example: a Flask + SQLite guestbook with no Dockerfile
| 1 | import html |
| 2 | import os |
| 3 | import sqlite3 |
| 4 | |
| 5 | from flask import Flask, redirect, request |
| 6 | |
| 7 | DB = os.environ.get("GUESTBOOK_DB", "guestbook.db") |
| 8 | app = Flask(__name__) |
| 9 | |
| 10 | |
| 11 | def db(): |
| 12 | conn = sqlite3.connect(DB) |
| 13 | conn.execute( |
| 14 | "CREATE TABLE IF NOT EXISTS entries " |
| 15 | "(id INTEGER PRIMARY KEY, name TEXT, message TEXT, at TEXT DEFAULT CURRENT_TIMESTAMP)" |
| 16 | ) |
| 17 | return conn |
| 18 | |
| 19 | |
| 20 | @app.get("/") |
| 21 | def index(): |
| 22 | with db() as conn: |
| 23 | rows = conn.execute("SELECT name, message, at FROM entries ORDER BY id DESC LIMIT 50").fetchall() |
| 24 | items = "".join( |
| 25 | f"<li><b>{html.escape(n)}</b>: {html.escape(m)} <small>{a}</small></li>" for n, m, a in rows |
| 26 | ) |
| 27 | return ( |
| 28 | "<!doctype html><title>Guestbook</title><h1>Guestbook</h1>" |
| 29 | "<form method=post action=/sign>" |
| 30 | "<input name=name placeholder=Name required> " |
| 31 | "<input name=message placeholder=Message required> " |
| 32 | "<button>Sign</button></form>" |
| 33 | f"<ul>{items}</ul>" |
| 34 | ) |
| 35 | |
| 36 | |
| 37 | @app.post("/sign") |
| 38 | def sign(): |
| 39 | with db() as conn: |
| 40 | conn.execute( |
| 41 | "INSERT INTO entries (name, message) VALUES (?, ?)", |
| 42 | (request.form["name"][:80], request.form["message"][:500]), |
| 43 | ) |
| 44 | return redirect("/", code=303) |
| 45 | |
| 46 | |
| 47 | if __name__ == "__main__": |
| 48 | app.run(host="0.0.0.0", port=int(os.environ.get("PORT", "5000"))) |