"""{{TITLE}}: counts its visits in its PostgreSQL database. Settings come from the environment (.env on the Core): DB_HOST, DB_PORT, DB_NAME, DB_USER, DB_PASSWORD, APP_URL. """ import html import os import time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import psycopg DB = { "host": os.environ["DB_HOST"], "port": os.environ.get("DB_PORT", "5432"), "dbname": os.environ["DB_NAME"], "user": os.environ["DB_USER"], "password": os.environ["DB_PASSWORD"], "connect_timeout": 5, } def connect(): return psycopg.connect(**DB, autocommit=True) def setup(): # PostgreSQL may still be starting (after a reboot): keep trying for attempt in range(60): try: with connect() as db: db.execute( "CREATE TABLE IF NOT EXISTS visits (" " id bigserial PRIMARY KEY," " at timestamptz NOT NULL DEFAULT now())" ) return except psycopg.OperationalError as error: print(f"Waiting for the database ({error})", flush=True) time.sleep(5) raise SystemExit("The database didn't answer for 5 minutes") class Handler(BaseHTTPRequestHandler): def do_GET(self): if self.path == "/health": self.reply(200, "text/plain", "ok\n") return try: with connect() as db: db.execute("INSERT INTO visits DEFAULT VALUES") count = db.execute("SELECT count(*) FROM visits").fetchone()[0] except psycopg.Error as error: self.reply(503, "text/plain", f"Database error: {error}\n") return page = f"""
Running on Federated Core, deployed with coreapp-dev.
Visits, counted in PostgreSQL: {count}
{html.escape(os.environ.get("APP_URL", ""))}
""" self.reply(200, "text/html; charset=utf-8", page) def reply(self, status, content_type, body): data = body.encode() self.send_response(status) self.send_header("Content-Type", content_type) self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data) if __name__ == "__main__": setup() print("Listening on port 8080", flush=True) ThreadingHTTPServer(("", 8080), Handler).serve_forever()