Refactor hit count so it is consistent in all 3 endpoints, match more paths on api...
authorJacob <jobs@jacobcasper.com>
Sun, 7 Sep 2025 18:18:24 +0000 (13:18 -0500)
committerJacob <jobs@jacobcasper.com>
Sun, 7 Sep 2025 18:18:24 +0000 (13:18 -0500)
main.py

diff --git a/main.py b/main.py
index aaa84a1646cb0e60b229fd7b3e14318fc8759d61..f9cdaa056399b19c5668a05d3a0cbb393cd7bf5e 100644 (file)
--- a/main.py
+++ b/main.py
@@ -1,23 +1,29 @@
 import logging
 import json
 
+from typing import Optional
+
 from flask import Flask, Response, request
 from redis import Redis
 
-r = Redis(host="redis", port=6379, decode_responses=True)
+redis_client = Redis(host="redis", port=6379, decode_responses=True)
 
 logging.basicConfig(level=logging.DEBUG)
 app = Flask(__name__)
 
+def increment_hits(url: str) -> int:
+    return redis_client.incr(f"hits:{url}")
+
 
-@app.route("/stats", methods=["GET"])
+@app.route("/stats/", methods=["GET"])
 def stats():
+    increment_hits("stats")
     try:
-        stats = r.scan_iter(match="hits:*")
+        stats = redis_client.scan_iter(match="hits:*")
         if stats is None:
             app.logger.debug("Uninitialized stats object")
             return {}
-        return {"stats": [{stat: r.get(stat)} for stat in stats]}
+        return {"stats": [{stat: redis_client.get(stat)} for stat in stats]}
     except redis.exceptions.ConnectionError as e:
         app.logger.exception(e)
         return Response("Internal Server Error", 500)
@@ -27,11 +33,11 @@ def stats():
     return {}
 
 
+@app.route("/api/", methods=["GET"])
 @app.route("/api/<path:subpath>", methods=["GET"])
-def api(subpath):
+def api(subpath: Optional[str] = None):
     app.logger.debug("subpath %s", subpath)
-    path_parts = subpath.split("/")
-    if len(path_parts) < 1 or len(path_parts) > 6:
+    if subpath is None or len(path_parts := subpath.split("/")) > 6:
         return Response(
             response=json.dumps(
                 {
@@ -50,5 +56,10 @@ def api(subpath):
             status=400,
         )
     # TODO check that the subpath contains no more than 3 unique subpath strings
-    hits = r.incr(f"hits:{subpath}")
+    hits = increment_hits(subpath)
     return {"hits": hits}
+
+@app.route("/test/<int:num_requests>/", methods=["POST"])
+def test(num_requests: int):
+    increment_hits("test")
+    return {}