A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
add `html_head` parameter to `create_asgi_app()` (#8302)
Florian Verdonck54489168f028
diff --git a/marimo/_server/api/deps.py b/marimo/_server/api/deps.pyindex d0d9c75b56..0591814ee1 100644--- a/marimo/_server/api/deps.py+++ b/marimo/_server/api/deps.py@@ -110,6 +110,12 @@ class AppStateBase:return self.state.enable_authreturn True+ @property+ def html_head(self) -> Optional[str]:+ if hasattr(self.state, "html_head"):+ return cast(Optional[str], self.state.html_head)+ return None+class AppState(AppStateBase):"""The app state with a request."""diff --git a/marimo/_server/api/endpoints/assets.py b/marimo/_server/api/endpoints/assets.pyindex 762b649da1..46b9e8096e 100644--- a/marimo/_server/api/endpoints/assets.py+++ b/marimo/_server/api/endpoints/assets.py@@ -283,6 +283,7 @@ async def index(request: Request) -> HTMLResponse:if app_state.remote_urlelse None,asset_url=app_state.asset_url,+ html_head=app_state.html_head,)# Inject service worker registration with the notebook IDdiff --git a/marimo/_server/asgi.py b/marimo/_server/asgi.pyindex 5271536d36..95ec6d509e 100644--- a/marimo/_server/asgi.py+++ b/marimo/_server/asgi.py@@ -295,6 +295,7 @@ def create_asgi_app(session_ttl: Optional[int] = None,asset_url: Optional[str] = None,redirect_console_to_browser: bool = False,+ html_head: Optional[str] = None,) -> ASGIAppBuilder:"""Public API to create an ASGI app that can serve multiple notebooks.This only works for application that are in Run mode.@@ -311,6 +312,10 @@ def create_asgi_app(e.g. https://cdn.jsdelivr.net/npm/@marimo-team/frontend@{version}/distredirect_console_to_browser (bool, optional): Whether to redirect console output (stdout/stderr) to the browser.When True, console output will be displayed in the browser. Defaults to False.+ html_head (str, optional): Custom HTML string to inject into the <head> of every notebook page.+ This is useful for adding global analytics scripts, custom stylesheets, meta tags, etc.+ When a notebook also has its own `html_head_file` config, the global `html_head` is injected first,+ followed by the per-notebook content.Returns:ASGIAppBuilder: A builder object to create multiple ASGI apps@@ -402,6 +407,7 @@ def create_asgi_app(config_reader = get_default_config_manager(current_path=None)base_app = Starlette()base_app.state.asset_url = asset_url+ base_app.state.html_head = html_head# Default to an empty token# If a user is using the create_asgi_app API,@@ -491,6 +497,7 @@ def create_asgi_app(app.state.asset_url = asset_urlapp.state.config_manager = config_readerapp.state.enable_auth = enable_auth+ app.state.html_head = html_headreturn appdef build(self) -> ASGIApp:diff --git a/marimo/_server/templates/templates.py b/marimo/_server/templates/templates.pyindex e52a3cb52f..c865e17812 100644--- a/marimo/_server/templates/templates.py+++ b/marimo/_server/templates/templates.py@@ -223,6 +223,7 @@ def notebook_page_template(notebook_snapshot: Optional[NotebookV1] = None,runtime_config: Optional[list[dict[str, Any]]] = None,asset_url: Optional[str] = None,+ html_head: Optional[str] = None,) -> str:html = html.replace("{{ base_url }}", base_url)@@ -296,7 +297,11 @@ def notebook_page_template(html = _inject_custom_css_for_config(html, user_config, filename)html = _inject_custom_css_for_config(html, config_overrides, filename)- # Add HTML head file contents if specified+ # Add global HTML head contents if specified (from create_asgi_app)+ if html_head:+ html = html.replace("</head>", f"{html_head}</head>")++ # Add per-notebook HTML head file contents if specifiedif app_config.html_head_file:head_contents = read_html_head_file(app_config.html_head_file, filename=filenamediff --git a/tests/_server/templates/test_templates.py b/tests/_server/templates/test_templates.pyindex f62367b582..92dd52ee4c 100644--- a/tests/_server/templates/test_templates.py+++ b/tests/_server/templates/test_templates.py@@ -270,6 +270,58 @@ class TestNotebookPageTemplate(unittest.TestCase):assert "<style title='marimo-custom'>" not in result_assert_no_leftover_replacements(result)+ def test_notebook_page_template_global_html_head(self) -> None:+ global_head = (+ '<script src="https://analytics.example.com/tracker.js"></script>'+ )++ result = templates.notebook_page_template(+ html=self.html,+ base_url=self.base_url,+ user_config=self.user_config,+ config_overrides=self.config_overrides,+ server_token=self.server_token,+ app_config=self.app_config,+ filename=str(self.filename),+ mode=self.mode,+ html_head=global_head,+ )++ assert global_head in result.split("</head>", 1)[0]+ _assert_no_leftover_replacements(result)++ def test_notebook_page_template_global_and_per_notebook_html_head(+ self,+ ) -> None:+ global_head = (+ '<script src="https://analytics.example.com/tracker.js"></script>'+ )++ per_notebook_head = "<style>.notebook-specific { color: red; }</style>"+ head_file = self.filename.parent / "head.html"+ head_file.write_text(per_notebook_head)++ result = templates.notebook_page_template(+ html=self.html,+ base_url=self.base_url,+ user_config=self.user_config,+ config_overrides=self.config_overrides,+ server_token=self.server_token,+ app_config=_AppConfig(html_head_file="head.html"),+ filename=str(self.filename),+ mode=self.mode,+ html_head=global_head,+ )++ head_section = result.split("</head>", 1)[0]+ assert global_head in head_section+ assert per_notebook_head in head_section+ # Global should appear before per-notebook+ assert head_section.index(global_head) < head_section.index(+ per_notebook_head+ )+ _assert_no_leftover_replacements(result)+def test_notebook_page_template_with_asset_url(self) -> None:"""Test notebook page template with custom asset URL."""asset_url = "https://cdn.example.com/v{version}"diff --git a/tests/_server/test_asgi.py b/tests/_server/test_asgi.pyindex fb59893f3b..6a58649446 100644--- a/tests/_server/test_asgi.py+++ b/tests/_server/test_asgi.py@@ -333,6 +333,44 @@ class TestASGIAppBuilder(unittest.TestCase):session_manager = starlette_app.state.session_managerassert session_manager.redirect_console_to_browser is False+ def test_html_head_parameter(self):+ """Test that html_head parameter is passed to app state."""+ custom_head = (+ '<script src="https://analytics.example.com/tracker.js"></script>'+ )+ builder = create_asgi_app(+ quiet=True, include_code=True, html_head=custom_head+ )+ builder = builder.with_app(path="/app1", root=self.app1)+ builder.build()++ starlette_app = builder._app_cache[self.app1]+ assert starlette_app.state.html_head == custom_head++ def test_html_head_none_by_default(self):+ """Test that html_head is None when not specified."""+ builder = create_asgi_app(quiet=True, include_code=True)+ builder = builder.with_app(path="/app1", root=self.app1)+ builder.build()++ starlette_app = builder._app_cache[self.app1]+ assert starlette_app.state.html_head is None++ def test_html_head_injected_in_response(self):+ """Test that html_head content appears in the served page."""+ custom_head = (+ '<script src="https://analytics.example.com/tracker.js"></script>'+ )+ builder = create_asgi_app(+ quiet=True, include_code=True, html_head=custom_head+ )+ builder = builder.with_app(path="/app1", root=self.app1)+ app = builder.build()+ client = TestClient(app)+ response = client.get("/app1")+ assert response.status_code == 200+ assert custom_head in response.text+class TestDynamicDirectoryMiddleware(unittest.TestCase):def setUp(self):