-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
84 lines (61 loc) · 2.29 KB
/
Copy pathapp.py
File metadata and controls
84 lines (61 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import json
import os
import uuid
from datetime import datetime, timezone
from flask import Flask, jsonify, request, render_template
app = Flask(__name__)
# Where notes are stored. Override with the NOTES_FILE env var if you like.
DATA_FILE = os.environ.get("NOTES_FILE", os.path.join(os.path.dirname(__file__), "notes.json"))
def _read_notes():
"""Load notes from disk, returning a list. Never crashes on a missing/empty file."""
if not os.path.exists(DATA_FILE):
return []
try:
with open(DATA_FILE, "r", encoding="utf-8") as f:
data = json.load(f)
return data if isinstance(data, list) else []
except (json.JSONDecodeError, OSError):
return []
def _write_notes(notes):
"""Persist the full notes list to disk."""
with open(DATA_FILE, "w", encoding="utf-8") as f:
json.dump(notes, f, indent=2, ensure_ascii=False)
@app.route("/")
def index():
"""Serve the single-page frontend."""
return render_template("index.html")
@app.route("/notes", methods=["GET"])
def get_notes():
"""Return all notes, newest first."""
notes = _read_notes()
notes.sort(key=lambda n: n.get("created_at", ""), reverse=True)
return jsonify(notes)
@app.route("/notes", methods=["POST"])
def create_note():
"""Create a new note from JSON body { "text": "..." }."""
payload = request.get_json(silent=True) or {}
text = (payload.get("text") or "").strip()
if not text:
return jsonify({"error": "Note text cannot be empty."}), 400
note = {
"id": uuid.uuid4().hex,
"text": text,
"created_at": datetime.now(timezone.utc).isoformat(),
}
notes = _read_notes()
notes.append(note)
_write_notes(notes)
return jsonify(note), 201
@app.route("/notes/<note_id>", methods=["DELETE"])
def delete_note(note_id):
"""Delete a note by id."""
notes = _read_notes()
remaining = [n for n in notes if n.get("id") != note_id]
if len(remaining) == len(notes):
return jsonify({"error": "Note not found."}), 404
_write_notes(remaining)
return jsonify({"deleted": note_id})
if __name__ == "__main__":
# Local dev server. In production, gunicorn runs the app (see Procfile).
port = int(os.environ.get("PORT", 5000))
app.run(host="0.0.0.0", port=port, debug=True)