import os import subprocess import sys import tempfile # Set up temp directories FIRST, before any imports that might use temp files def setup_early_temp_directories(): """Set up temp directories before Flask imports.""" backend_dir = os.path.dirname(os.path.abspath(__file__)) temp_dir = os.path.join(backend_dir, 'temp') try: os.makedirs(temp_dir, exist_ok=True) os.chmod(temp_dir, 0o755) # Test write permissions test_file = os.path.join(temp_dir, 'test_write_early') with open(test_file, 'w') as f: f.write('test') os.remove(test_file) # Set environment variables BEFORE any imports that use tempfile os.environ['TMPDIR'] = temp_dir os.environ['TEMP'] = temp_dir os.environ['TMP'] = temp_dir tempfile.tempdir = temp_dir print(f"✓ Early temp directory setup: {temp_dir}") return temp_dir except Exception as e: print(f"Warning: Early temp directory setup failed: {e}") return None # Set up temp directories before importing app setup_early_temp_directories() from app import create_app from app.models.user import User # Create the Flask app flask_app = create_app() @flask_app.before_first_request def initialize_database(): # Create default user if it doesn't exist User.create_default_user() # Wrap Flask app for ASGI compatibility with hypercorn try: from hypercorn.middleware import WSGIMiddleware app = WSGIMiddleware(flask_app) except ImportError: # Fallback for when hypercorn isn't installed yet app = flask_app if __name__ == '__main__': # Check if hypercorn is available try: import hypercorn except ImportError: print("Hypercorn not found. Installing it...") subprocess.check_call([sys.executable, "-m", "pip", "install", "hypercorn"]) # Start with hypercorn using command line arguments cmd = [ sys.executable, "-m", "hypercorn", "--bind", "0.0.0.0:5137", "--workers", "4", "--worker-class", "asyncio", "--keep-alive", "65", "--access-log", "/dev/null", "--error-log", "-", "--log-level", "info", "run:app" ] print("Starting Flask app with Hypercorn...") try: subprocess.run(cmd) except KeyboardInterrupt: print("\nShutting down...") sys.exit(0)