From ece918e5780043e7913fec338349122c7c179cd3 Mon Sep 17 00:00:00 2001 From: Jacob Date: Sun, 7 Sep 2025 13:18:24 -0500 Subject: [PATCH] Refactor hit count so it is consistent in all 3 endpoints, match more paths on api route --- main.py | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/main.py b/main.py index aaa84a1..f9cdaa0 100644 --- 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/", 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//", methods=["POST"]) +def test(num_requests: int): + increment_hits("test") + return {} -- 2.30.2