Tech Stack Advisor - Code Viewer

← Back to File Tree

streamlit_with_health.py

Language: python | Path: streamlit_with_health.py | Lines: 63
#!/usr/bin/env python3
"""Run Streamlit with a simple health check endpoint on the same port."""
import os
import sys
import subprocess
import threading
import time
from http.server import HTTPServer, BaseHTTPRequestHandler
import socket

PORT = int(os.environ.get('PORT', 8080))

class HealthCheckHandler(BaseHTTPRequestHandler):
    """Simple health check that returns 200 immediately."""

    def do_GET(self):
        # Only handle health check paths
        if self.path in ['/_stcore/health', '/health', '/healthz']:
            self.send_response(200)
            self.send_header('Content-type', 'text/plain')
            self.end_headers()
            self.wfile.write(b'OK')
        else:
            # For all other paths, return 404 and let Streamlit handle it
            self.send_response(404)
            self.end_headers()

    def log_message(self, format, *args):
        # Suppress logging
        pass

def run_health_server():
    """Run health check server on port+1."""
    health_port = PORT + 1
    server = HTTPServer(('127.0.0.1', health_port), HealthCheckHandler)
    print(f"Health check server running on 127.0.0.1:{health_port}")
    server.serve_forever()

def main():
    print(f"PORT: {PORT}")

    # Start health check server in background thread
    health_thread = threading.Thread(target=run_health_server, daemon=True)
    health_thread.start()

    # Give health server time to start
    time.sleep(1)

    # Start Streamlit
    print(f"Starting Streamlit on port {PORT}...")
    cmd = [
        "streamlit", "run",
        "frontend/streamlit_app.py",
        f"--server.port={PORT}",
        "--server.address=0.0.0.0",
        "--server.headless=true",
    ]

    print(f"Command: {' '.join(cmd)}")
    sys.exit(subprocess.call(cmd))

if __name__ == "__main__":
    main()