From ab473a10aca22715e5d1c5a41c944bbd933e79bc Mon Sep 17 00:00:00 2001 From: Jacob Date: Sun, 7 Sep 2025 12:54:26 -0500 Subject: [PATCH] Implement request based error handling --- main.py | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/main.py b/main.py index 88664d0..1391c54 100644 --- 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/", 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} -- 2.30.2