|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +A small Flask app that displays the current local date and time. |
| 4 | +
|
| 5 | +Provides an application factory `create_app()` for easy testing and WSGI |
| 6 | +integration. The root route `/` renders a simple template showing the |
| 7 | +current timestamp. |
| 8 | +""" |
| 9 | +from __future__ import annotations |
| 10 | +import os |
| 11 | +from datetime import datetime |
| 12 | +from flask import Flask, render_template, jsonify |
| 13 | + |
| 14 | + |
| 15 | +def create_app(debug: bool = False) -> Flask: |
| 16 | + """Create and configure the Flask application. |
| 17 | +
|
| 18 | + Args: |
| 19 | + debug: Enable Flask debug mode when True. |
| 20 | +
|
| 21 | + Returns: |
| 22 | + Configured Flask app instance. |
| 23 | + """ |
| 24 | + app = Flask(__name__, template_folder="templates") |
| 25 | + app.debug = debug |
| 26 | + |
| 27 | + @app.route("/") |
| 28 | + |
| 29 | + def index() -> str: |
| 30 | + """Render the index template with the current datetime.""" |
| 31 | + now = datetime.now().astimezone() |
| 32 | + # ISO-like compact timestamp and human-friendly format |
| 33 | + iso_ts = now.isoformat(sep=" ", timespec="seconds") |
| 34 | + human_ts = now.strftime("%Y-%m-%d %H:%M:%S %Z%z") |
| 35 | + return render_template("index.html", iso=iso_ts, human=human_ts) |
| 36 | + |
| 37 | + @app.route('/api/time') |
| 38 | + |
| 39 | + def api_time(): |
| 40 | + """Return the current datetime as JSON (iso and human-readable). |
| 41 | +
|
| 42 | + This endpoint is polled by the client every second to update the |
| 43 | + displayed time without reloading the page. |
| 44 | + """ |
| 45 | + now = datetime.now().astimezone() |
| 46 | + iso_ts = now.isoformat(sep=" ", timespec="seconds") |
| 47 | + human_ts = now.strftime("%Y-%m-%d %H:%M:%S %Z%z") |
| 48 | + return jsonify({"iso": iso_ts, "human": human_ts}) |
| 49 | + |
| 50 | + return app |
| 51 | + |
| 52 | + |
| 53 | +# Module-level app for WSGI servers / convenience imports |
| 54 | +app: Flask = create_app() |
| 55 | + |
| 56 | + |
| 57 | +def _env_bool(name: str, default: bool = False) -> bool: |
| 58 | + val = os.getenv(name) |
| 59 | + if val is None: |
| 60 | + return default |
| 61 | + return val.lower() in ("1", "true", "yes", "on") |
| 62 | + |
| 63 | + |
| 64 | +if __name__ == "__main__": |
| 65 | + host = os.environ.get("FLASK_RUN_HOST", "127.0.0.1") |
| 66 | + port = int(os.environ.get("PORT", "5000")) |
| 67 | + debug = _env_bool("FLASK_DEBUG", False) |
| 68 | + |
| 69 | + app = create_app(debug=debug) |
| 70 | + app.run(host=host, port=port, debug=debug) |
0 commit comments