import os import psycopg2 from flask import Flask, request, redirect, url_for, render_template_string app = Flask(__name__) DB_HOST = os.environ.get("DB_HOST", "postgres-service") DB_PORT = os.environ.get("DB_PORT", "5432") DB_NAME = os.environ.get("DB_NAME", "notesdb") DB_USER = os.environ.get("DB_USER", "notesuser") DB_PASS = os.environ.get("DB_PASS", "notespass") HTML = """
{{ error }}
{% endif %}{{ note[1] }}
{{ note[2] }}No notes yet.
{% endif %} """ def get_conn(): return psycopg2.connect( host=DB_HOST, port=DB_PORT, dbname=DB_NAME, user=DB_USER, password=DB_PASS ) def init_db(): conn = get_conn() cur = conn.cursor() cur.execute(""" CREATE TABLE IF NOT EXISTS notes ( id SERIAL PRIMARY KEY, content TEXT NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) conn.commit() cur.close() conn.close() @app.route("/") def index(): try: init_db() conn = get_conn() cur = conn.cursor() cur.execute("SELECT id, content, created_at FROM notes ORDER BY created_at DESC") notes = cur.fetchall() cur.close() conn.close() return render_template_string(HTML, notes=notes, error=None) except Exception as e: return render_template_string(HTML, notes=[], error=f"DB error: {e}") @app.route("/add", methods=["POST"]) def add(): content = request.form.get("content", "").strip() if content: conn = get_conn() cur = conn.cursor() cur.execute("INSERT INTO notes (content) VALUES (%s)", (content,)) conn.commit() cur.close() conn.close() return redirect(url_for("index")) @app.route("/delete/