Skip to content

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.

feat: add support for --base-url from marimo run (#748)

Myles Scolnick5eb8585849b4
diff --git a/frontend/index.html b/frontend/index.html
index 34767cd6a5..c715fe31c4 100644
--- a/frontend/index.html
+++ b/frontend/index.html
@@ -1,6 +1,7 @@
<!DOCTYPE html>
<html lang="en">
<head>
+ <base href='{{ base_url }}/' />
<meta charset="utf-8" />
<link rel="icon" href="/favicon.ico" />
<!-- Preload is necessary because we show these images when we disconnect from the server,
diff --git a/frontend/playwright.config.ts b/frontend/playwright.config.ts
index b04df0924c..f128a380f8 100644
--- a/frontend/playwright.config.ts
+++ b/frontend/playwright.config.ts
@@ -7,6 +7,7 @@ import { exec } from "node:child_process";
export interface ServerOptions {
command: "edit" | "run";
port: number;
+ baseUrl?: string | undefined;
}
// Read environment variables from file. See https://github.com/motdotla/dotenv
@@ -34,20 +35,25 @@ const appToOptions = {
"layout_grid.py//edit": { port: port(), command: "edit" },
"layout_grid.py//run": { port: port(), command: "run" },
"layout_grid_max_width.py//run": { port: port(), command: "run" },
- "output.py//run": { port: port(), command: "run" },
+ "output.py//run": {
+ port: port(),
+ command: "run",
+ baseUrl: "/foo",
+ },
"kitchen_sink.py//edit": { port: port(), command: "edit" },
"stdin.py//edit": { port: port(), command: "edit" },
} satisfies Record<string, ServerOptions>;
export type ApplicationNames = keyof typeof appToOptions;
-function getUrl(port: number): string {
- return `http://127.0.0.1:${port}`;
+function getUrl(port: number, baseUrl = ""): string {
+ return `http://127.0.0.1:${port}${baseUrl}`;
}
// For tests to lookup their url/server
export function getAppUrl(app: ApplicationNames): string {
- return getUrl(appToOptions[app].port);
+ const options: ServerOptions = appToOptions[app];
+ return getUrl(options.port, options.baseUrl);
}
// Reset file via git checkout
@@ -127,13 +133,16 @@ const config: PlaywrightTestConfig = {
webServer: Object.entries(appToOptions).map(([app, options]) => {
app = app.replace("//edit", "").replace("//run", "");
- const { command, port } = options;
+ const { command, port, baseUrl } = options as ServerOptions;
const pathToApp = path.join(pydir, app);
- const marimoCmd = `marimo -q ${command} ${pathToApp} -p ${port} --headless`;
+ let marimoCmd = `marimo -q ${command} ${pathToApp} -p ${port} --headless`;
+ if (baseUrl) {
+ marimoCmd += ` --base-url=${baseUrl}`;
+ }
return {
command: marimoCmd,
- url: getUrl(port),
+ url: getUrl(port, baseUrl),
reuseExistingServer: false,
};
}),
diff --git a/frontend/src/core/network/api.ts b/frontend/src/core/network/api.ts
index 60491e6473..f9f8b632f4 100644
--- a/frontend/src/core/network/api.ts
+++ b/frontend/src/core/network/api.ts
@@ -9,8 +9,6 @@ export function getXsrfCookie(): string {
return r ? r[1] : "";
}
-const BASE_URL = "/api";
-
const getServerTokenOnce = once(() => {
return getMarimoServerToken();
});
@@ -21,6 +19,8 @@ const getServerTokenOnce = once(() => {
*/
export const API = {
post<REQ, RESP = null>(url: string, body: REQ): Promise<RESP> {
+ const BASE_URL = `${document.baseURI}api`;
+
const fullUrl = BASE_URL + url;
return fetch(fullUrl, {
method: "POST",
diff --git a/frontend/src/core/static/__tests__/__snapshots__/download-html.test.ts.snap b/frontend/src/core/static/__tests__/__snapshots__/download-html.test.ts.snap
index 11c9b1914c..6c95d736e4 100644
--- a/frontend/src/core/static/__tests__/__snapshots__/download-html.test.ts.snap
+++ b/frontend/src/core/static/__tests__/__snapshots__/download-html.test.ts.snap
@@ -4,6 +4,8 @@ exports[`download-html > should construct html correctly 1`] = `
"<!doctype html>
<html>
<head>
+ <base href="/" />
+
<meta charset="utf-8" />
<link
rel="icon"
diff --git a/frontend/src/core/static/__tests__/download-html.test.ts b/frontend/src/core/static/__tests__/download-html.test.ts
index 9c37ec8f40..1b63cc3655 100644
--- a/frontend/src/core/static/__tests__/download-html.test.ts
+++ b/frontend/src/core/static/__tests__/download-html.test.ts
@@ -1,12 +1,14 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { describe, expect, it } from "vitest";
-import { constructHTML } from "../download-html";
+import { constructHTML, visibleForTesting } from "../download-html";
import { CellId } from "@/core/cells/ids";
import { createCell, createCellRuntimeState } from "@/core/cells/types";
import { JSDOM } from "jsdom";
import prettier from "prettier";
import { Base64String } from "@/utils/json/base64";
+const { updateAssetUrl } = visibleForTesting;
+
const DOC = `
<html lang="en">
<head>
@@ -109,3 +111,39 @@ describe("download-html", () => {
expect(formattedResult).toMatchSnapshot();
});
});
+
+describe("updateAssetUrl", () => {
+ const assetBaseUrl =
+ "https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist";
+
+ it('should convert relative URL starting with "./"', () => {
+ const existingUrl = "./assets/index-c78b8d10.js";
+ const expected = `${assetBaseUrl}/assets/index-c78b8d10.js`;
+ expect(updateAssetUrl(existingUrl, assetBaseUrl)).toBe(expected);
+ });
+
+ it('should convert relative URL starting with "/"', () => {
+ const existingUrl = "/assets/index-c78b8d10.js";
+ const expected = `${assetBaseUrl}/assets/index-c78b8d10.js`;
+ expect(updateAssetUrl(existingUrl, assetBaseUrl)).toBe(expected);
+ });
+
+ it("should convert absolute URL from a different origin", () => {
+ const existingUrl = "https://localhost:8080/assets/index-c78b8d10.js";
+ const expected = `${assetBaseUrl}/assets/index-c78b8d10.js`;
+ expect(updateAssetUrl(existingUrl, assetBaseUrl)).toBe(expected);
+ });
+
+ it("should not modify URL from the same origin", () => {
+ // Assuming window.location.origin is 'https://localhost:8080'
+ const existingUrl = "https://localhost:8080/assets/index-c78b8d10.js";
+ // Mock window.location.origin to match the existingUrl's origin
+ Object.defineProperty(window, "location", {
+ value: {
+ origin: "https://localhost:8080",
+ },
+ });
+
+ expect(updateAssetUrl(existingUrl, assetBaseUrl)).toBe(existingUrl);
+ });
+});
diff --git a/frontend/src/core/static/download-html.ts b/frontend/src/core/static/download-html.ts
index 68de360b16..e5c05b2d07 100644
--- a/frontend/src/core/static/download-html.ts
+++ b/frontend/src/core/static/download-html.ts
@@ -96,6 +96,7 @@ export function constructHTML(opts: {
<!DOCTYPE html>
<html>
<head>
+ <base href="/">
${staticHead.innerHTML}
</head>
@@ -200,9 +201,16 @@ export function constructHTML(opts: {
function updateAssetUrl(existingUrl: string, assetBaseUrl: string) {
// Will convert: https://localhost:8080/assets/index-c78b8d10.js
+ // Or will convert ./assets/index-c78b8d10.js
+ // Or will convert /assets/index-c78b8d10.js
// into: https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index-c78b8d10.js
- // relative path
+ // relative './...'
+ if (existingUrl.startsWith("./")) {
+ return `${assetBaseUrl}${existingUrl.slice(1)}`;
+ }
+
+ // relative '/...'
if (existingUrl.startsWith("/")) {
return `${assetBaseUrl}${existingUrl}`;
}
@@ -216,3 +224,7 @@ function updateAssetUrl(existingUrl: string, assetBaseUrl: string) {
// otherwise, leave as is
return existingUrl;
}
+
+export const visibleForTesting = {
+ updateAssetUrl,
+};
diff --git a/frontend/vite.config.mts b/frontend/vite.config.mts
index 1373e5919a..e74a21d774 100644
--- a/frontend/vite.config.mts
+++ b/frontend/vite.config.mts
@@ -28,6 +28,7 @@ const htmlDevPlugin = (): Plugin => {
// copies these elements from server to dev
const copyElements = [
+ "base",
"title",
"marimo-filename",
"marimo-version",
@@ -62,6 +63,8 @@ const htmlDevPlugin = (): Plugin => {
// https://vitejs.dev/config/
export default defineConfig({
+ // This allows for a dynamic <base> tag in index.html
+ base: "./",
server: {
host: "localhost",
port: 3000,
diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.py
index de94c8b46b..e57ea379aa 100644
--- a/marimo/_cli/cli.py
+++ b/marimo/_cli/cli.py
@@ -10,6 +10,7 @@ from typing import Any, Literal, Optional
import click
+import marimo._cli.cli_validators as validators
from marimo import __version__, _loggers
from marimo._ast import codegen
from marimo._cli import ipynb_to_marimo
@@ -267,6 +268,14 @@ Example:
type=bool,
help="Include notebook code in the app.",
)
+ "--base-url",
+ default="",
+ show_default=True,
+ type=str,
+ help="Base URL for the server. Should start with a /.",
+ callback=validators.base_url,
+)
@click.argument("name", required=True)
def run(
port: Optional[int],
@@ -274,6 +283,7 @@ def run(
headless: bool,
include_code: bool,
name: str,
+ base_url: str,
) -> None:
# Validate name, or download from URL
# The second return value is an optional temporary directory. It is unused,
@@ -293,6 +303,7 @@ def run(
filename=name,
mode=SessionMode.RUN,
include_code=include_code,
+ base_url=base_url,
)
diff --git a/marimo/_cli/cli_validators.py b/marimo/_cli/cli_validators.py
new file mode 100644
index 0000000000..a8c9134b0e
--- /dev/null
+++ b/marimo/_cli/cli_validators.py
@@ -0,0 +1,15 @@
+# Copyright 2024 Marimo. All rights reserved.
+from typing import Any, Optional
+
+import click
+
+
+def base_url(ctx: Any, param: Any, value: Optional[str]) -> str:
+ del ctx
+ del param
+ if value is None or value == "":
+ return ""
+
+ if not value.startswith("/"):
+ raise click.BadParameter("Must start with /")
+ return value
diff --git a/marimo/_runtime/virtual_file.py b/marimo/_runtime/virtual_file.py
index 9a874fffc2..6a2568599e 100644
--- a/marimo/_runtime/virtual_file.py
+++ b/marimo/_runtime/virtual_file.py
@@ -44,7 +44,9 @@ class VirtualFile:
# Create a file URL with the buffer size
# This is a hack so when we pull from shared memory we know how
# many bytes to read.
- self.url = url or f"/@file/{len(buffer)}-{filename}"
+ # Also, URL is intentionally relative, so it can be resolved with
+ # different base URLs.
+ self.url = url or f"./@file/{len(buffer)}-{filename}"
@staticmethod
def from_external_url(url: str) -> VirtualFile:
@@ -57,7 +59,9 @@ class VirtualFile:
EMPTY_VIRTUAL_FILE = VirtualFile(
filename="empty.txt",
- url="/@file/0-empty.txt",
+ # URL is intentionally relative, so it can be resolved with
+ # different base URLs.
+ url="@file/0-empty.txt",
buffer=b"",
)
diff --git a/marimo/_server/api/deps.py b/marimo/_server/api/deps.py
index 8c554d72ca..d8f571c044 100644
--- a/marimo/_server/api/deps.py
+++ b/marimo/_server/api/deps.py
@@ -34,6 +34,9 @@ class AppState:
assert request.app.state.server is not None, "Server not initialized"
assert request.app.state.host is not None, "Host not initialized"
assert request.app.state.port is not None, "Port not initialized"
+ assert (
+ request.app.state.base_url is not None
+ ), "Base URL not initialized"
self.session_manager: SessionManager = (
request.app.state.session_manager
@@ -42,6 +45,7 @@ class AppState:
self._server: Server = request.app.state.server
self._host: str = request.app.state.host
self._port: int = request.app.state.port
+ self._base_url: str = request.app.state.base_url
def get_current_session_id(self) -> Optional[SessionId]:
"""Get the current session."""
@@ -97,6 +101,10 @@ class AppState:
def port(self) -> int:
return self._port
+ @property
+ def base_url(self) -> str:
+ return self._base_url
+
@property
def server_token(self) -> str:
return self.session_manager.server_token
diff --git a/marimo/_server/api/endpoints/assets.py b/marimo/_server/api/endpoints/assets.py
index c5bcc2287f..8065e82617 100644
--- a/marimo/_server/api/endpoints/assets.py
+++ b/marimo/_server/api/endpoints/assets.py
@@ -49,6 +49,7 @@ async def index(request: Request) -> HTMLResponse:
index_html = os.path.join(root, "index.html")
with open(index_html, "r") as f:
html = f.read()
+ html = html.replace("{{ base_url }}", app_state.base_url)
html = html.replace("{{ title }}", title)
html = html.replace("{{ user_config }}", json.dumps(user_config))
html = html.replace("{{ app_config }}", json.dumps(app_config))
diff --git a/marimo/_server/api/endpoints/files.py b/marimo/_server/api/endpoints/files.py
index 937e11ee6f..d3426d0ddd 100644
--- a/marimo/_server/api/endpoints/files.py
+++ b/marimo/_server/api/endpoints/files.py
@@ -175,8 +175,11 @@ async def open_file(
mgr.rename(filename)
host = app_state.host
port = app_state.port
+ base_url = app_state.base_url
run = app_state.mode == SessionMode.RUN
- print_startup(filename=filename, url=f"http://{host}:{port}", run=run)
+ print_startup(
+ filename=filename, url=f"http://{host}:{port}{base_url}", run=run
+ )
return SuccessResponse()
diff --git a/marimo/_server/api/lifespans.py b/marimo/_server/api/lifespans.py
index 573905af72..9f92b2b580 100644
--- a/marimo/_server/api/lifespans.py
+++ b/marimo/_server/api/lifespans.py
@@ -104,7 +104,8 @@ async def lsp(app: Starlette) -> AsyncIterator[None]:
async def open_browser(app: Starlette) -> AsyncIterator[None]:
host = app.state.host
port = app.state.port
- url = f"http://{host}:{port}"
+ base_url = app.state.base_url
+ url = f"http://{host}:{port}{base_url}"
user_config = get_configuration()
headless = app.state.headless
if not headless:
@@ -122,12 +123,13 @@ async def logging(app: Starlette) -> AsyncIterator[None]:
manager = get_manager()
host = app.state.host
port = app.state.port
+ base_url = app.state.base_url
# Startup message
if not manager.quiet:
print_startup(
manager.filename,
- f"http://{host}:{port}",
+ f"http://{host}:{port}{base_url}",
manager.mode == SessionMode.RUN,
)
diff --git a/marimo/_server/api/middleware.py b/marimo/_server/api/middleware.py
index 587682c4f6..96bc8440c4 100644
--- a/marimo/_server/api/middleware.py
+++ b/marimo/_server/api/middleware.py
@@ -9,8 +9,8 @@ from starlette.authentication import (
BaseUser,
SimpleUser,
)
-from starlette.exceptions import HTTPException
from starlette.requests import HTTPConnection, Request
+from starlette.responses import JSONResponse
from starlette.types import ASGIApp, Receive, Scope, Send
from marimo._server.model import SessionMode
@@ -55,7 +55,48 @@ class ValidateServerTokensMiddleware:
server_token = request.headers.get("Marimo-Server-Token")
if server_token != expected_server_token:
- raise HTTPException(401, "Invalid server token")
+ response = JSONResponse(
+ {"error": "Invalid server token"}, status_code=401
+ )
+ return await response(scope, receive, send)
# Passed
return await self.app(scope, receive, send)
+
+
+ALLOWED_BASE_URLS = set(["/health", "/healthz", "/metrics", "/"])
+
+
+class StripBaseURLMiddleware:
+ def __init__(self, app: ASGIApp, base_url: str) -> None:
+ self.app = app
+ self.base_url = base_url
+
+ async def __call__(
+ self, scope: Scope, receive: Receive, send: Send
+ ) -> None:
+ # If not HTTP, skip
+ if scope["type"] != "http":
+ return await self.app(scope, receive, send)
+
+ # If base URL is empty, skip
+ if self.base_url == "" or self.base_url == "/":
+ return await self.app(scope, receive, send)
+
+ request = Request(scope)
+
+ # If under common infra routes, allow
+ if request.url.path in ALLOWED_BASE_URLS:
+ return await self.app(scope, receive, send)
+
+ # If not under base URL or under infra routes, return 404
+ # Otherwise, this may hide real issues
+ if not request.url.path.startswith(self.base_url):
+ response = JSONResponse({"error": "Not found"}, status_code=404)
+ return await response(scope, receive, send)
+
+ # Strip base URL
+ scope["path"] = scope["path"][len(self.base_url) :]
+ if not scope["path"].startswith("/"):
+ scope["path"] = "/" + scope["path"]
+ return await self.app(scope, receive, send)
diff --git a/marimo/_server/main.py b/marimo/_server/main.py
index c99298e65e..387a53bc5b 100644
--- a/marimo/_server/main.py
+++ b/marimo/_server/main.py
@@ -12,23 +12,11 @@ from starlette.responses import JSONResponse
from marimo._server.api.lifespans import LIFESPANS
from marimo._server.api.middleware import (
AuthBackend,
+ StripBaseURLMiddleware,
ValidateServerTokensMiddleware,
)
from marimo._server.api.router import ROUTES
-# CORS
-middleware = [
- Middleware(
- CORSMiddleware,
- allow_origins=["*"],
- allow_credentials=True,
- allow_methods=["*"],
- allow_headers=["*"],
- ),
- Middleware(AuthenticationMiddleware, backend=AuthBackend()),
- Middleware(ValidateServerTokensMiddleware),
-]
-
# Convert exceptions to JSON responses
async def handle_error(request: Request, response: Any) -> Any:
@@ -45,12 +33,31 @@ async def handle_error(request: Request, response: Any) -> Any:
# Create app
-app = Starlette(
- routes=ROUTES,
- middleware=middleware,
- lifespan=LIFESPANS,
- exception_handlers={
- Exception: handle_error,
- HTTPException: handle_error,
- },
-)
+def create_starlette_app(
+ base_url: str,
+) -> Starlette:
+ middleware = [
+ Middleware(
+ CORSMiddleware,
+ allow_origins=["*"],
+ allow_credentials=True,
+ allow_methods=["*"],
+ allow_headers=["*"],
+ ),
+ Middleware(
+ StripBaseURLMiddleware,
+ base_url=base_url,
+ ),
+ Middleware(AuthenticationMiddleware, backend=AuthBackend()),
+ Middleware(ValidateServerTokensMiddleware),
+ ]
+
+ return Starlette(
+ routes=ROUTES,
+ middleware=middleware,
+ lifespan=LIFESPANS,
+ exception_handlers={
+ Exception: handle_error,
+ HTTPException: handle_error,
+ },
+ )
diff --git a/marimo/_server/router.py b/marimo/_server/router.py
index 8dc5bd96a6..fe0b6b0ac0 100644
--- a/marimo/_server/router.py
+++ b/marimo/_server/router.py
@@ -20,10 +20,8 @@ DecoratedCallable = TypeVar("DecoratedCallable", bound=Callable[..., Any])
@dataclass
class APIRouter(Router):
- # Prefix to append to routes
- prefix: str = ""
-
- def __init__(self) -> None:
+ def __init__(self, prefix: str = "") -> None:
+ self.prefix = prefix
super().__init__()
def __post_init__(self) -> None:
@@ -120,4 +118,4 @@ class APIRouter(Router):
route.routes.extend(router.routes)
return
- self.mount(path=prefix, app=router, name=name)
+ self.mount(path=self.prefix + prefix, app=router, name=name)
diff --git a/marimo/_server/start.py b/marimo/_server/start.py
index c1100ac284..7c3d3ceac9 100644
--- a/marimo/_server/start.py
+++ b/marimo/_server/start.py
@@ -5,7 +5,7 @@ from typing import Optional
import uvicorn
from marimo._config.config import get_configuration
-from marimo._server.main import app
+from marimo._server.main import create_starlette_app
from marimo._server.model import SessionMode
from marimo._server.sessions import initialize_manager
from marimo._server.utils import (
@@ -26,6 +26,7 @@ def start(
headless: bool,
port: Optional[int],
host: str,
+ base_url: str = "",
) -> None:
"""
Start the server.
@@ -46,10 +47,13 @@ def start(
log_level = "info" if development_mode else "error"
+ app = create_starlette_app(base_url=base_url)
+
app.state.headless = headless
app.state.port = port
app.state.host = host or "localhost"
app.state.session_manager = session_manager
+ app.state.base_url = base_url
app.state.user_config = get_configuration()
server = uvicorn.Server(
diff --git a/tests/_server/api/test_middleware.py b/tests/_server/api/test_middleware.py
new file mode 100644
index 0000000000..20c604373d
--- /dev/null
+++ b/tests/_server/api/test_middleware.py
@@ -0,0 +1,56 @@
+# Copyright 2024 Marimo. All rights reserved.
+import uvicorn
+from starlette.testclient import TestClient
+
+from marimo import __version__
+from marimo._config.config import get_configuration
+from marimo._server.main import create_starlette_app
+from tests._server.mocks import get_mock_session_manager
+
+
+def test_base_url() -> None:
+ app = create_starlette_app(base_url="/foo")
+ app.state.session_manager = get_mock_session_manager()
+ app.state.user_config = get_configuration()
+ app.state.session_manager = get_mock_session_manager()
+ app.state.user_config = get_configuration()
+ client = TestClient(app)
+
+ # Mock out the server
+ uvicorn_server = uvicorn.Server(uvicorn.Config(app))
+ uvicorn_server.servers = []
+
+ app.state.server = uvicorn_server
+ app.state.host = "localhost"
+ app.state.port = 1234
+ app.state.base_url = "/foo"
+
+ client = TestClient(app)
+
+ # Infra routes, allows fallback
+ response = client.get("/foo/health")
+ assert response.status_code == 200, response.text
+ response = client.get("/foo/healthz")
+ assert response.status_code == 200, response.text
+ response = client.get("/health")
+ assert response.status_code == 200, response.text
+ response = client.get("/healthz")
+ assert response.status_code == 200, response.text
+
+ # Index, allows fallback
+ response = client.get("/foo/")
+ assert response.status_code == 200, response.text
+ response = client.get("/")
+ assert response.status_code == 200, response.text
+
+ # Favicon, fails when missing base_url
+ response = client.get("/foo/favicon.ico")
+ assert response.status_code == 200, response.text
+ response = client.get("/favicon.ico")
+ assert response.status_code == 404, response.text
+
+ # API, fails when missing base_url
+ response = client.get("/foo/api/status")
+ assert response.status_code == 200, response.text
+ response = client.get("/api/status")
+ assert response.status_code == 404, response.text
diff --git a/tests/_server/conftest.py b/tests/_server/conftest.py
index b271df59c7..b6fcc0e7be 100644
--- a/tests/_server/conftest.py
+++ b/tests/_server/conftest.py
@@ -6,11 +6,13 @@ import uvicorn
from starlette.testclient import TestClient
from marimo._config.config import get_configuration
-from marimo._server.main import app
+from marimo._server.main import create_starlette_app
from marimo._server.sessions import SessionManager
from marimo._server.utils import initialize_asyncio
from tests._server.mocks import get_mock_session_manager
+app = create_starlette_app(base_url="")
+
@pytest.fixture(scope="session", autouse=True)
def init() -> None:
@@ -36,6 +38,7 @@ def client() -> TestClient:
app.state.server = uvicorn_server
app.state.host = "localhost"
app.state.port = 1234
+ app.state.base_url = ""
return client