From 158f529e1ca0ed04ddb52eaf12ff70373282c20a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pablo=20P=C3=A9rez=20Arcas?= Date: Mon, 30 Mar 2026 08:21:48 +0000 Subject: [PATCH] =?UTF-8?q?A=C3=B1adir=20z1/backend/app.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- z1/backend/app.py | 93 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 z1/backend/app.py diff --git a/z1/backend/app.py b/z1/backend/app.py new file mode 100644 index 0000000..0a80829 --- /dev/null +++ b/z1/backend/app.py @@ -0,0 +1,93 @@ +from flask import Flask, request, jsonify +from flask_cors import CORS +import os +import psycopg2 +import time + +app = Flask(__name__) +CORS(app) + +DB_HOST = os.getenv("DB_HOST", "db") +DB_NAME = os.getenv("DB_NAME", "notesdb") +DB_USER = os.getenv("DB_USER", "notesuser") +DB_PASSWORD = os.getenv("DB_PASSWORD", "notessecret") +DB_PORT = os.getenv("DB_PORT", "5432") + +def get_connection(): + return psycopg2.connect( + host=DB_HOST, + database=DB_NAME, + user=DB_USER, + password=DB_PASSWORD, + port=DB_PORT + ) + +def init_db(): + for _ in range(20): + try: + conn = get_connection() + cur = conn.cursor() + cur.execute(""" + CREATE TABLE IF NOT EXISTS notes ( + id SERIAL PRIMARY KEY, + content TEXT NOT NULL + ); + """) + conn.commit() + cur.close() + conn.close() + return + except Exception: + time.sleep(2) + raise Exception("Database not ready") + +@app.route("/api/health", methods=["GET"]) +def health(): + return jsonify({"status": "ok"}) + +@app.route("/api/notes", methods=["GET"]) +def get_notes(): + conn = get_connection() + cur = conn.cursor() + cur.execute("SELECT id, content FROM notes ORDER BY id DESC;") + rows = cur.fetchall() + cur.close() + conn.close() + return jsonify([{"id": r[0], "content": r[1]} for r in rows]) + +@app.route("/api/notes", methods=["POST"]) +def add_note(): + data = request.get_json() + content = data.get("content", "").strip() + + if not content: + return jsonify({"error": "Content is required"}), 400 + + conn = get_connection() + cur = conn.cursor() + cur.execute("INSERT INTO notes (content) VALUES (%s) RETURNING id;", (content,)) + note_id = cur.fetchone()[0] + conn.commit() + cur.close() + conn.close() + + return jsonify({"id": note_id, "content": content}), 201 + +@app.route("/api/notes/", methods=["DELETE"]) +def delete_note(note_id): + conn = get_connection() + cur = conn.cursor() + cur.execute("DELETE FROM notes WHERE id = %s RETURNING id;", (note_id,)) + deleted = cur.fetchone() + conn.commit() + cur.close() + conn.close() + + if deleted is None: + return jsonify({"error": "Note not found"}), 404 + + return jsonify({"message": "Note deleted successfully"}) + +if __name__ == "__main__": + init_db() + app.run(host="0.0.0.0", port=5000) \ No newline at end of file