framework.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #!/usr/bin/env python3
  2. from __future__ import annotations
  3. import time
  4. from pathlib import Path
  5. from flask import Flask, Response, render_template
  6. _START_TIME = time.time()
  7. def create_app(app_name: str, *, title: str | None = None) -> Flask:
  8. """Create a Flask app with shared web defaults for this monorepo."""
  9. template_dir = Path(__file__).with_name("templates")
  10. app = Flask(app_name, template_folder=str(template_dir))
  11. app.config["APP_TITLE"] = title or app_name
  12. register_default_routes(app)
  13. return app
  14. def register_default_routes(app: Flask) -> None:
  15. @app.get("/")
  16. def index() -> str:
  17. return render_template("index.html", app_title=app.config["APP_TITLE"])
  18. @app.get("/healthz")
  19. def healthz() -> Response:
  20. uptime_seconds = max(0.0, time.time() - _START_TIME)
  21. lines = [
  22. "# HELP app_health Application health status (1 = healthy).",
  23. "# TYPE app_health gauge",
  24. f'app_health{{service="{app.name}"}} 1',
  25. "# HELP app_uptime_seconds Application uptime in seconds.",
  26. "# TYPE app_uptime_seconds gauge",
  27. f'app_uptime_seconds{{service="{app.name}"}} {uptime_seconds:.3f}',
  28. "",
  29. ]
  30. body = "\n".join(lines)
  31. return Response(body, status=200, headers={"Content-Type": "text/plain; version=0.0.4; charset=utf-8"})