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
feat: add asset URL support for templates and server (#6204)
Myles Scolnick771988ce10fa
diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.pyindex 2264847c59..ca8a221582 100644--- a/marimo/_cli/cli.py+++ b/marimo/_cli/cli.py@@ -445,6 +445,13 @@ https://github.com/marimo-team/marimo/issues/5219.""",hidden=True,help="When opening a .py file, enable fallback conversion from pypercent, script, or text.",)+ "--asset-url",+ default=None,+ type=str,+ hidden=True,+ help="Custom asset URL for loading static resources. Can include {version} placeholder.",+)@click.option("--timeout",required=False,@@ -476,6 +483,7 @@ def edit(skew_protection: bool,remote_url: Optional[str],convert: bool,+ asset_url: Optional[str],timeout: Optional[float],name: Optional[str],args: tuple[str, ...],@@ -604,6 +612,7 @@ def edit(redirect_console_to_browser=True,ttl_seconds=None,remote_url=remote_url,+ asset_url=asset_url,timeout=timeout,)@@ -923,6 +932,13 @@ Example:type=bool,help=sandbox_message,)+ "--asset-url",+ default=None,+ type=str,+ hidden=True,+ help="Custom asset URL for loading static resources. Can include {version} placeholder.",+)@click.argument("name",required=True,@@ -944,6 +960,7 @@ def run(allow_origins: tuple[str, ...],redirect_console_to_browser: bool,sandbox: Optional[bool],+ asset_url: Optional[str],name: str,args: tuple[str, ...],) -> None:@@ -1000,6 +1017,7 @@ def run(argv=list(args),auth_token=_resolve_token(token, token_password),redirect_console_to_browser=redirect_console_to_browser,+ asset_url=asset_url,)diff --git a/marimo/_server/api/deps.py b/marimo/_server/api/deps.pyindex 38ee98dfb7..c0c5e46b2f 100644--- a/marimo/_server/api/deps.py+++ b/marimo/_server/api/deps.py@@ -101,6 +101,10 @@ class AppStateBase:def remote_url(self) -> Optional[str]:return getattr(self.state, "remote_url", None)+ @property+ def asset_url(self) -> Optional[str]:+ return getattr(self.state, "asset_url", 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 a7dc189f8f..f78e3c1631 100644--- a/marimo/_server/api/endpoints/assets.py+++ b/marimo/_server/api/endpoints/assets.py@@ -93,6 +93,7 @@ async def index(request: Request) -> HTMLResponse:user_config=app_state.config_manager.get_user_config(),config_overrides=app_state.config_manager.get_config_overrides(),server_token=app_state.skew_protection_token,+ asset_url=app_state.asset_url,)else:config_manager = app_state.config_manager_at_file(file_key)@@ -112,6 +113,7 @@ async def index(request: Request) -> HTMLResponse:filename=app_manager.filename,mode=app_state.mode,remote_url=app_state.remote_url,+ asset_url=app_state.asset_url,)# Inject service worker registration with the notebook IDdiff --git a/marimo/_server/start.py b/marimo/_server/start.pyindex 9b95dd9bb9..b4c487d2b9 100644--- a/marimo/_server/start.py+++ b/marimo/_server/start.py@@ -90,6 +90,7 @@ def start(redirect_console_to_browser: bool,skew_protection: bool,remote_url: Optional[str] = None,+ asset_url: Optional[str] = None,timeout: Optional[float] = None,) -> None:"""@@ -193,6 +194,7 @@ def start(app.state.watch = watchapp.state.session_manager = session_managerapp.state.base_url = base_url+ app.state.asset_url = asset_urlapp.state.config_manager = config_readerapp.state.remote_url = remote_urldiff --git a/marimo/_server/templates/templates.py b/marimo/_server/templates/templates.pyindex 228334f3aa..757f03832c 100644--- a/marimo/_server/templates/templates.py+++ b/marimo/_server/templates/templates.py@@ -89,6 +89,7 @@ def home_page_template(user_config: MarimoConfig,config_overrides: PartialMarimoConfig,server_token: SkewProtectionToken,+ asset_url: Optional[str] = None,) -> str:html = html.replace("{{ base_url }}", base_url)html = html.replace("{{ title }}", "marimo")@@ -100,7 +101,8 @@ def home_page_template("{{ user_config }}", _html_escape(json.dumps(user_config)))html = html.replace("{{ server_token }}", str(server_token))- # /TODO++ html = _replace_asset_urls(html, asset_url)html = html.replace(MOUNT_CONFIG_TEMPLATE,@@ -131,6 +133,7 @@ def notebook_page_template(filename: Optional[str],mode: SessionMode,remote_url: Optional[str] = None,+ asset_url: Optional[str] = None,) -> str:html = html.replace("{{ base_url }}", base_url)@@ -152,7 +155,8 @@ def notebook_page_template("{{ user_config }}", _html_escape(json.dumps(user_config)))html = html.replace("{{ server_token }}", str(server_token))- # /TODO++ html = _replace_asset_urls(html, asset_url)html = html.replace(MOUNT_CONFIG_TEMPLATE,@@ -301,12 +305,7 @@ def static_notebook_template()# Replace all relative href and src with absolute URL- html = (- html.replace("href='./", f"crossorigin='anonymous' href='{asset_url}/")- .replace("src='./", f"crossorigin='anonymous' src='{asset_url}/")- .replace('href="./', f'crossorigin="anonymous" href="{asset_url}/')- .replace('src="./', f'crossorigin="anonymous" src="{asset_url}/')- )+ html = _replace_asset_urls(html, asset_url)# Append to headhtml = html.replace("</head>", f"{static_block}</head>")@@ -472,3 +471,25 @@ def _inject_custom_css_for_config(css_block = "\n".join(css_contents)return html.replace("</head>", f"{css_block}</head>")+++def _replace_asset_urls(html: str, asset_url: Optional[str]) -> str:+ """Replace asset URLs with the given asset URL.++ These are naturally relative URLs. This can be used to load assets+ from a CDN instead of from the marimo server.++ The asset URL can be parameterized with {version}+ """+ if asset_url is None:+ return html++ if "{version}" in asset_url:+ asset_url = asset_url.replace("{version}", __version__)++ return (+ html.replace("href='./", f"crossorigin='anonymous' href='{asset_url}/")+ .replace("src='./", f"crossorigin='anonymous' src='{asset_url}/")+ .replace('href="./', f'crossorigin="anonymous" href="{asset_url}/')+ .replace('src="./', f'crossorigin="anonymous" src="{asset_url}/')+ )diff --git a/tests/_server/templates/test_templates.py b/tests/_server/templates/test_templates.pyindex 0bc02bf0f0..4c95da0b5d 100644--- a/tests/_server/templates/test_templates.py+++ b/tests/_server/templates/test_templates.py@@ -270,6 +270,28 @@ class TestNotebookPageTemplate(unittest.TestCase):assert "<style title='marimo-custom'>" not in result_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}"++ result = templates.notebook_page_template(+ self.html,+ self.base_url,+ self.user_config,+ self.config_overrides,+ self.server_token,+ self.app_config,+ str(self.filename),+ self.mode,+ asset_url=asset_url,+ )++ # Asset URLs should be replaced+ assert 'href="https://cdn.example.com/' in result+ assert 'src="https://cdn.example.com/' in result+ assert 'crossorigin="anonymous"' in result+ _assert_no_leftover_replacements(result)+class TestHomePageTemplate(unittest.TestCase):def setUp(self) -> None:@@ -306,6 +328,25 @@ class TestHomePageTemplate(unittest.TestCase):assert "home" in result_assert_no_leftover_replacements(result)+ def test_home_page_template_with_asset_url(self) -> None:+ """Test home page template with custom asset URL."""+ asset_url = "https://cdn.example.com/v{version}"++ result = templates.home_page_template(+ self.html,+ self.base_url,+ self.user_config,+ self.config_overrides,+ self.server_token,+ asset_url=asset_url,+ )++ # Asset URLs should be replaced+ assert 'href="https://cdn.example.com/' in result+ assert 'src="https://cdn.example.com/' in result+ assert 'crossorigin="anonymous"' in result+ _assert_no_leftover_replacements(result)+class TestStaticNotebookTemplate(unittest.TestCase):def setUp(self) -> None:@@ -768,3 +809,44 @@ class TestWasmNotebookTemplate(unittest.TestCase):assert "#filename-input" in resultassert "<title>My App</title>" in result_assert_no_leftover_replacements(result)+++class TestReplaceAssetUrls(unittest.TestCase):+ """Test the _replace_asset_urls function."""++ def test_replace_asset_urls_basic(self) -> None:+ """Test basic asset URL replacement."""+ html = """<link href="./assets/style.css" rel="stylesheet">+<script src="./assets/app.js"></script>"""++ result = templates._replace_asset_urls(html, "https://cdn.example.com")++ assert (+ result+ == """<link crossorigin="anonymous" href="https://cdn.example.com/assets/style.css" rel="stylesheet">+<script crossorigin="anonymous" src="https://cdn.example.com/assets/app.js"></script>"""+ )++ def test_replace_asset_urls_with_version(self) -> None:+ """Test asset URL replacement with version placeholder."""+ from marimo._version import __version__++ html = """<link href="./assets/style.css" rel="stylesheet">"""++ result = templates._replace_asset_urls(+ html, "https://cdn.example.com/v{version}"+ )++ expected = f"""<link crossorigin="anonymous" href="https://cdn.example.com/v{__version__}/assets/style.css" rel="stylesheet">"""+ assert result == expected++ def test_replace_asset_urls_double_quotes(self) -> None:+ """Test asset URL replacement with double quotes."""+ html = '<link href="./assets/style.css" rel="stylesheet">'++ result = templates._replace_asset_urls(html, "https://cdn.example.com")++ assert (+ result+ == '<link crossorigin="anonymous" href="https://cdn.example.com/assets/style.css" rel="stylesheet">'+ )