Skip to content

Commit

Permalink
refactor(launch): Replace thread with lifespan event for opening the …
Browse files Browse the repository at this point in the history
…browser
  • Loading branch information
augustebaum committed Oct 1, 2024
1 parent d0f0b83 commit af96ad8
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 12 deletions.
19 changes: 9 additions & 10 deletions src/skore/cli/launch_dashboard.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
"""Implement the "launch" command."""

import threading
import time
import webbrowser
from contextlib import asynccontextmanager
from pathlib import Path

import uvicorn
from fastapi import FastAPI

from skore.cli import logger
from skore.project import load
Expand All @@ -18,11 +18,6 @@ class ProjectNotFound(Exception):
project_path: Path


def __open_browser(port: int):
time.sleep(0.5)
webbrowser.open(f"http://localhost:{port}")


def __launch(project_name: str | Path, port: int, open_browser: bool):
"""Launch the UI to visualize a project.
Expand All @@ -36,10 +31,14 @@ def __launch(project_name: str | Path, port: int, open_browser: bool):
Whether to automatically open a browser tab showing the UI.
"""
project = load(project_name)
app = create_app(project=project)

if open_browser:
threading.Thread(target=lambda: __open_browser(port=port)).start()
@asynccontextmanager
async def lifespan(app: FastAPI):
if open_browser:
webbrowser.open(f"http://localhost:{port}")
yield

app = create_app(project=project, lifespan=lifespan)

try:
# TODO: check port is free
Expand Down
7 changes: 5 additions & 2 deletions src/skore/ui/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,18 @@
from fastapi import APIRouter, FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from starlette.types import Lifespan

from skore.project import Project, load
from skore.ui.dependencies import get_static_path
from skore.ui.report import router as report_router


def create_app(project: Project | None = None) -> FastAPI:
def create_app(
project: Project | None = None, lifespan: Lifespan | None = None
) -> FastAPI:
"""FastAPI factory used to create the API to interact with `stores`."""
app = FastAPI()
app = FastAPI(lifespan=lifespan)

# Give the app access to the project
if not project:
Expand Down

0 comments on commit af96ad8

Please sign in to comment.