Skip to content

_report_viewer

create_server_script(directory, port)

Creates a script to start the server.

Parameters:

Name Type Description Default
directory Path

Directory to serve

required
port int

Port number to use

required

Returns:

Name Type Description
Path Path

Path to the created server script

Raises:

Type Description
Exception

If script creation fails

Source code in libs\cafex_core\src\cafex_core\reporting_\_report_viewer\_server_scripts\_server_generator.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def create_server_script(directory: Path, port: int) -> Path:
    """Creates a script to start the server.

    Args:
        directory (Path): Directory to serve
        port (int): Port number to use

    Returns:
        Path: Path to the created server script

    Raises:
        Exception: If script creation fails
    """
    try:
        # Save server info
        _save_server_info(directory, port)

        if os.name == "nt":  # Windows
            script_content = f"""@echo off
echo Starting server...
cd /d "{directory}"
echo.
echo Server running at http://localhost:{port}
echo.
echo To stop the server, close this window
echo.
python -m http.server {port} --bind localhost --directory "{directory}"
del /f .server_info
"""
            script_file = directory / "start_report_server.bat"
        else:  # Unix
            script_content = f"""#!/bin/bash
echo "Starting server..."
cd "{directory}"
echo "Server running at http://localhost:{port}"
echo ""
echo "To stop the server, press Ctrl+C"
python3 -m http.server {port} --bind localhost --directory "{directory}"
rm -f .server_info
"""
            script_file = directory / "start_report_server.sh"

        with open(script_file, "w", newline="\n") as f:
            f.write(script_content)

        if not os.name == "nt":
            os.chmod(script_file, 0o755)  # Make executable on Unix

        return script_file

    except Exception as e:
        logger.error(f"Error creating server script: {e}")
        raise

launch_server_and_browser(script_file, port)

Launches the server and opens the browser.

Parameters:

Name Type Description Default
script_file Path

Path to the server script to execute

required
port int

Port number the server will use

required

Raises:

Type Description
Exception

If server launch fails

Source code in libs\cafex_core\src\cafex_core\reporting_\_report_viewer\_server_scripts\_server_launcher.py
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
def launch_server_and_browser(script_file: Path, port: int) -> None:
    """Launches the server and opens the browser.

    Args:
        script_file (Path): Path to the server script to execute
        port (int): Port number the server will use

    Raises:
        Exception: If server launch fails
    """
    try:
        if os.name == "nt":  # Windows
            os.startfile(script_file)
        else:  # Unix
            subprocess.Popen(["xterm", "-e", f"bash {script_file}"])

        # Give the server a moment to start
        time.sleep(1)

        # Open browser
        url = f"http://localhost:{port}/report.html"
        webbrowser.open(url)

    except Exception as e:
        logger.error(f"Error launching server: {e}")
        raise

stop_server(directory)

Stop any running server for the given directory.

Parameters:

Name Type Description Default
directory Path

Directory whose server should be stopped

required
Source code in libs\cafex_core\src\cafex_core\reporting_\_report_viewer\_server_scripts\_server_launcher.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
def stop_server(directory: Path) -> None:
    """Stop any running server for the given directory.

    Args:
        directory (Path): Directory whose server should be stopped
    """
    try:
        info = _get_server_info(directory)
        port = info.get("port")

        if not port:
            return

        for proc in psutil.process_iter(attrs=["pid", "name"]):
            try:
                connections = proc.connections(kind="inet")  # Only check network connections
                for conn in connections:
                    if conn.laddr.port == port:
                        logger.info(f"Stopping server (PID: {proc.pid}) running on port {port}")
                        proc.terminate()  # Gracefully terminate first
                        proc.wait(timeout=2)  # Wait for 2 seconds
                        if proc.is_running():
                            proc.kill()  # Force kill if still running
                        time.sleep(0.5)  # Give time to shut down
                        break
            except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
                continue  # Skip processes we can't access

        # Clean up server info file
        info_file = directory / ".server_info"
        if info_file.exists():
            info_file.unlink()

    except Exception as e:
        logger.warning(f"Error stopping server: {e}")