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)
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(
{
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 {}