Implement request based error handling
authorJacob <jobs@jacobcasper.com>
Sun, 7 Sep 2025 17:54:26 +0000 (12:54 -0500)
committerJacob <jobs@jacobcasper.com>
Sun, 7 Sep 2025 17:54:26 +0000 (12:54 -0500)
main.py

diff --git a/main.py b/main.py
index 88664d036fe07e1819e82b8249455a00d7f9d65e..1391c546db1041bb006ae431fc6c47f95edcb4b6 100644 (file)
--- a/main.py
+++ b/main.py
@@ -1,6 +1,8 @@
+import logging
+import json
+
 from flask import Flask, Response, request
 from redis import Redis
-import logging
 
 r = Redis(host="redis", port=6379, decode_responses=True)
 
@@ -11,7 +13,7 @@ app = Flask(__name__)
 @app.route("/stats", methods=["GET"])
 def stats():
     try:
-        stats = r.scan_iter()
+        stats = r.scan_iter(match="hits:*")
         if stats is None:
             app.logger.debug("Uninitialized stats object")
             return {}
@@ -27,6 +29,26 @@ def stats():
 @app.route("/api/<path:subpath>", methods=["GET"])
 def api(subpath):
     app.logger.debug("subpath %s", subpath)
+    path_parts = subpath.split("/")
+    if len(path_parts) < 1 or len(path_parts) > 6:
+        return Response(
+            response=json.dumps(
+                {
+                    "error": f"Invalid API path ({subpath}). Path must contain 1 to 6 segments."
+                }
+            ),
+            status=400,
+        )
+    if any([len(part) != 3 for part in path_parts]):
+        return Response(
+            response=json.dumps(
+                {
+                    "error": f"Invalid API path ({subpath}). All segments must be 3 characters long."
+                }
+            ),
+            status=400,
+        )
+    # TODO check that the subpath contains no more than 3 unique subpath strings
     hits = r.incr(f"hits:{subpath}")
     return {"hits": hits}