"""A small web app that keeps its data in RasterizedDB. Every request is recorded in the table `visits`, and the page answers with how many there have been. The connection settings come from the standard libpq environment variables (PGHOST, PGPORT, PGUSER, PGPASSWORD, PGDATABASE, PGSSLMODE), which compose.yaml sets. """ import time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import psycopg def connect(): """One connection, configured from the environment.""" return psycopg.connect(autocommit=True) def wait_for_database(attempts=30, delay=2.0): """The database may still be starting: try for a minute before giving up.""" for attempt in range(1, attempts + 1): try: with connect() as conn: conn.execute( "CREATE TABLE IF NOT EXISTS visits (" " id BIGSERIAL PRIMARY KEY," " path TEXT NOT NULL)" ) return except psycopg.OperationalError as error: print(f"database not ready (attempt {attempt}): {error}", flush=True) time.sleep(delay) raise SystemExit("could not reach the database") class Handler(BaseHTTPRequestHandler): def do_GET(self): try: with connect() as conn: conn.execute("INSERT INTO visits (path) VALUES (%s)", (self.path,)) (count,) = conn.execute("SELECT COUNT(*) FROM visits").fetchone() body = f"{count} visits so far\n".encode() self.send_response(200) except psycopg.Error as error: body = f"database error: {error}\n".encode() self.send_response(503) self.send_header("Content-Type", "text/plain; charset=utf-8") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) if __name__ == "__main__": wait_for_database() print("listening on :8000", flush=True) ThreadingHTTPServer(("0.0.0.0", 8000), Handler).serve_forever()