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.

improvement: add marimo.create_asgi_app().with_dynamic_directory (#3057)

Myles Scolnickb2a71c63088b
diff --git a/docs/guides/deploying/programmatically.md b/docs/guides/deploying/programmatically.md
index be9e47ab72..19e698b04d 100644
--- a/docs/guides/deploying/programmatically.md
+++ b/docs/guides/deploying/programmatically.md
@@ -37,3 +37,30 @@ if __name__ == "__main__":
```
For a more complete example, see the [FastAPI example](https://github.com/marimo-team/marimo/tree/main/examples/frameworks/fastapi).
+
+## Dynamic directory
+
+If you'd like to create a server to dynamically load marimo notebooks from a directory, you can use the `with_dynamic_directory` method. This is useful if the contents of the directory change often, such as a directory of notebooks for a dashboard, without restarting the server.
+
+```python
+server = (
+ marimo.create_asgi_app()
+ .with_dynamic_directory(path="/dashboard", directory="./notebooks")
+)
+```
+
+If the notebooks in the directory are expected to be static, it is better to use the `with_app` method and loop through the directory contents.
+
+```python
+from pathlib import Path
+server = marimo.create_asgi_app()
+app_names: list[str] = []
+
+notebooks_dir = Path(__file__).parent / "notebooks"
+
+for filename in sorted(notebooks_dir.iterdir()):
+ if filename.suffix == ".py":
+ app_name = filename.stem
+ server = server.with_app(path=f"/{app_name}", root=filename)
+ app_names.append(app_name)
+```
diff --git a/marimo/_server/asgi.py b/marimo/_server/asgi.py
index ce293465b9..1a35b07d48 100644
--- a/marimo/_server/asgi.py
+++ b/marimo/_server/asgi.py
@@ -2,22 +2,232 @@
from __future__ import annotations
import abc
-from typing import TYPE_CHECKING, List, Optional, Tuple
+import logging
+from pathlib import Path
+from typing import TYPE_CHECKING, Callable, Dict, List, Optional, Tuple
if TYPE_CHECKING:
- from starlette.types import ASGIApp
+ from starlette.requests import Request
+ from starlette.responses import Response
+ from starlette.types import ASGIApp, Receive, Scope, Send
+
+LOGGER = logging.getLogger(__name__)
class ASGIAppBuilder(abc.ABC):
+ """
+ Class for building ASGI applications.
+
+ Methods:
+ with_app(path: str, root: str) -> ASGIAppBuilder:
+ Adds a static application to the ASGI app at the specified path.
+
+ with_dynamic_directory(path: str, directory: str) -> ASGIAppBuilder:
+ Adds a dynamic directory to the ASGI app, allowing for dynamic loading of applications from the specified directory.
+
+ build() -> ASGIApp:
+ Builds and returns the final ASGI application.
+ """
+
@abc.abstractmethod
def with_app(self, *, path: str, root: str) -> "ASGIAppBuilder":
+ """
+ Adds a static application to the ASGI app at the specified path.
+
+ Args:
+ path (str): The URL path where the application will be mounted.
+ root (str): The root directory of the application.
+
+ Returns:
+ ASGIAppBuilder: The builder instance for chaining.
+ """
+ pass
+
+ @abc.abstractmethod
+ def with_dynamic_directory(
+ self, *, path: str, directory: str
+ ) -> "ASGIAppBuilder":
+ """
+ Adds a dynamic directory to the ASGI app, allowing for dynamic loading of applications from the specified directory.
+
+ Args:
+ path (str): The URL path where the dynamic directory will be mounted.
+ directory (str): The directory containing the applications.
+
+ Returns:
+ ASGIAppBuilder: The builder instance for chaining.
+ """
pass
@abc.abstractmethod
def build(self) -> "ASGIApp":
+ """
+ Builds and returns the final ASGI application.
+
+ Returns:
+ ASGIApp: The built ASGI application.
+ """
pass
+class DynamicDirectoryMiddleware:
+ def __init__(
+ self,
+ app: ASGIApp,
+ base_path: str,
+ directory: str,
+ app_builder: Callable[[str, str], ASGIApp],
+ ) -> None:
+ self.app = app
+ self.base_path = base_path.rstrip("/")
+ self.directory = Path(directory)
+ self.app_builder = app_builder
+ self._app_cache: Dict[str, ASGIApp] = {}
+ LOGGER.debug(
+ f"Initialized DynamicDirectoryMiddleware with base_path={self.base_path}, "
+ f"directory={self.directory} (exists={self.directory.exists()}, "
+ f"is_dir={self.directory.is_dir()})"
+ )
+
+ def _redirect_response(self, scope: Scope) -> Response:
+ from starlette.requests import Request
+ from starlette.responses import RedirectResponse
+
+ request = Request(scope)
+
+ # Get the path and query string
+ path = request.url.path
+ query_string = request.url.query
+
+ # Build the redirect URL with query params
+ redirect_url = f"{path}/"
+ if query_string:
+ redirect_url = f"{redirect_url}?{query_string}"
+
+ LOGGER.debug(f"Redirecting to: {redirect_url}")
+ return RedirectResponse(url=redirect_url, status_code=307)
+
+ def _find_matching_file(
+ self, relative_path: str
+ ) -> Optional[Tuple[Path, str]]:
+ """Find a matching Python file in the directory structure.
+ Returns tuple of (matching file, remaining path) if found, None otherwise."""
+ # Try direct match first, skip if relative path has an extension
+ if not Path(relative_path).suffix:
+ direct_match = self.directory / f"{relative_path}.py"
+ if not direct_match.name.startswith("_") and direct_match.exists():
+ return (direct_match, "")
+
+ # Try nested path by progressively checking each part
+ parts = relative_path.split("/")
+ for i in range(len(parts), 0, -1):
+ prefix = parts[:i]
+ remaining = parts[i:]
+
+ # Try as a Python file
+ potential_path = self.directory.joinpath(*prefix)
+ cache_key = str(potential_path.with_suffix(".py"))
+ if (
+ cache_key in self._app_cache
+ and not potential_path.name.startswith("_")
+ ):
+ return (potential_path.with_suffix(".py"), "/".join(remaining))
+
+ return None
+
+ async def __call__(
+ self, scope: Scope, receive: Receive, send: Send
+ ) -> None:
+ path = scope["path"]
+
+ if scope["type"] not in ("http", "websocket"):
+ LOGGER.debug(
+ f"Non-HTTP/WS request type: {scope['type']}, passing through"
+ )
+ await self.app(scope, receive, send)
+ return
+
+ # Only handle requests starting with the base_path
+ if not path.startswith(f"{self.base_path}/"):
+ LOGGER.debug(
+ f"Path {path} doesn't start with base_path {self.base_path}/, passing through"
+ )
+ await self.app(scope, receive, send)
+ return
+
+ # Extract the relative path after the base_path
+ relative_path = path[len(self.base_path) + 1 :]
+ if not relative_path:
+ LOGGER.debug("Empty relative_path, passing through")
+ await self.app(scope, receive, send)
+ return
+
+ # Remove trailing slash for file lookup
+ relative_path = relative_path.rstrip("/")
+
+ LOGGER.debug(
+ f"Received dynamic request for path: {path}. Relative path: {relative_path}"
+ )
+
+ match_result = self._find_matching_file(relative_path)
+ if not match_result:
+ LOGGER.debug(
+ f"No matching file found for {relative_path}, passing through"
+ )
+ await self.app(scope, receive, send)
+ return
+
+ potential_file, remaining_path = match_result
+ LOGGER.debug(
+ f"Found matching file: {potential_file} with remaining path: {remaining_path}"
+ )
+
+ # For HTTP requests without trailing slash, redirect only if there's no remaining path
+ if (
+ scope["type"] == "http"
+ and not path.endswith("/")
+ and not remaining_path
+ ):
+ LOGGER.debug(
+ "Path matches file but missing trailing slash, redirecting"
+ )
+ response = self._redirect_response(scope)
+ await response(scope, receive, send)
+ return
+
+ # Create or get cached app
+ cache_key = str(potential_file)
+ if cache_key not in self._app_cache:
+ LOGGER.debug(f"Creating new app for {cache_key}")
+ try:
+ self._app_cache[cache_key] = self.app_builder(
+ cache_key, cache_key
+ )
+ LOGGER.debug(f"Successfully created app for {cache_key}")
+ except Exception as e:
+ LOGGER.exception(f"Failed to create app for {cache_key}: {e}")
+ await self.app(scope, receive, send)
+ return
+
+ # Update scope to use the remaining path
+ new_scope = dict(scope)
+ old_path = new_scope["path"]
+ new_scope["path"] = f"/{remaining_path}" if remaining_path else "/"
+ LOGGER.debug(f"Updated path: {old_path} -> {new_scope['path']}")
+
+ try:
+ await self._app_cache[cache_key](new_scope, receive, send)
+ LOGGER.debug(
+ f"Successfully handled {scope['type']} request for {cache_key}"
+ )
+ except Exception as e:
+ LOGGER.exception(
+ f"Error handling {scope['type']} request for {cache_key}: {e}"
+ )
+ # If the app fails, fall back to the main app
+ await self.app(scope, receive, send)
+
+
def create_asgi_app(
*,
quiet: bool = False,
@@ -81,6 +291,22 @@ def create_asgi_app(
uvicorn.run(app, port=8000)
```
+ You may also want to dynamically load notebooks from a directory. To do
+ this, use the `with_dynamic_directory` method. This is useful if the
+ contents of the directory change often without requiring a server restart.
+
+ ```python
+ import uvicorn
+
+ builder = create_asgi_app().with_dynamic_directory(
+ path="/notebooks", directory="./notebooks"
+ )
+ app = builder.build()
+
+ if __name__ == "__main__":
+ uvicorn.run(app, port=8000)
+ ```
+
**Args.**
- quiet (bool, optional): Suppress standard out
@@ -121,14 +347,23 @@ def create_asgi_app(
class Builder(ASGIAppBuilder):
def __init__(self) -> None:
self._mount_configs: List[Tuple[str, str]] = []
+ self._dynamic_directory_configs: List[Tuple[str, str]] = []
+ self._app_cache: Dict[str, ASGIApp] = {}
def with_app(self, *, path: str, root: str) -> "ASGIAppBuilder":
self._mount_configs.append((path, root))
return self
- def _build_app(self, path: str, root: str) -> "ASGIAppBuilder":
+ def with_dynamic_directory(
+ self, *, path: str, directory: str
+ ) -> "ASGIAppBuilder":
+ self._dynamic_directory_configs.append((path, directory))
+ return self
+
+ @staticmethod
+ def _create_app_for_file(base_url: str, file_path: str) -> ASGIApp:
session_manager = SessionManager(
- file_router=AppFileRouter.from_filename(MarimoPath(root)),
+ file_router=AppFileRouter.from_filename(MarimoPath(file_path)),
mode=SessionMode.RUN,
development_mode=False,
quiet=quiet,
@@ -156,35 +391,52 @@ def create_asgi_app(
allow_origins=("*",),
)
app.state.session_manager = session_manager
- app.state.base_url = path
+ app.state.base_url = base_url
app.state.config_manager = user_config_mgr
-
- base_app.mount(path, app)
-
- # If path is not empty,
- # add a redirect from /{path} to /{path}/
- # otherwise, we get a 404
- if path:
- base_app.add_route(
- path,
- lambda _: RedirectResponse(
- url=f"{path}/", status_code=301
- ),
- )
-
- return self
+ return app
def build(self) -> "ASGIApp":
- # First sort the mount configs by path length
- # This is to ensure that the root app is mounted last
+ # Handle individual app mounts first
+ # Sort to ensure the root app is mounted last
self._mount_configs = sorted(
self._mount_configs, key=lambda x: -len(x[0])
)
+ def create_redirect_to_slash(
+ base_url: str,
+ ) -> Callable[[Request], Response]:
+ redirect_path = f"{base_url}/"
+ return lambda _: RedirectResponse(
+ url=redirect_path, status_code=301
+ )
+
for path, root in self._mount_configs:
- self._build_app(path, root)
+ if root not in self._app_cache:
+ self._app_cache[root] = self._create_app_for_file(
+ base_url=path, file_path=root
+ )
+ base_app.mount(path, self._app_cache[root])
+
+ # If path is not empty,
+ # add a redirect from /{path} to /{path}/
+ # otherwise, we get a 404
+ if path and not path.endswith("/"):
+ base_app.add_route(
+ path,
+ create_redirect_to_slash(path),
+ )
+
+ # Add dynamic directory middleware for each directory config
+ app: ASGIApp = base_app
+ for path, directory in self._dynamic_directory_configs:
+ app = DynamicDirectoryMiddleware(
+ app=app,
+ base_path=path,
+ directory=directory,
+ app_builder=self._create_app_for_file,
+ )
- return base_app
+ return app
initialize_asyncio()
return Builder()
diff --git a/marimo/_smoke_tests/custom_server/my_server.py b/marimo/_smoke_tests/custom_server/my_server.py
index 8e8d4cfbaf..fa7c89c0ba 100644
--- a/marimo/_smoke_tests/custom_server/my_server.py
+++ b/marimo/_smoke_tests/custom_server/my_server.py
@@ -11,6 +11,11 @@ server = (
.with_app(path="/dataframes", root="../dataframe.py")
# Mount the ansi app at /ansi
.with_app(path="/ansi", root="../ansi.py")
+ # Mount directory at /data
+ # You can visit /charts/altair_brush/
+ # You can visit /charts/altair_polars/
+ .with_dynamic_directory(path="/chart", directory="../altair")
+ .with_dynamic_directory(path="/smoke_tests", directory="../")
# Mount the buttons app at the root
.with_app(path="", root="../buttons.py")
)
diff --git a/tests/_server/test_asgi.py b/tests/_server/test_asgi.py
index eefa13f0fc..84e06f80c4 100644
--- a/tests/_server/test_asgi.py
+++ b/tests/_server/test_asgi.py
@@ -1,10 +1,19 @@
import os
import tempfile
import unittest
+from pathlib import Path
+from starlette.applications import Starlette
+from starlette.requests import Request
+from starlette.responses import PlainTextResponse, Response
from starlette.testclient import TestClient
+from starlette.websockets import WebSocket
-from marimo._server.asgi import ASGIAppBuilder, create_asgi_app
+from marimo._server.asgi import (
+ ASGIAppBuilder,
+ DynamicDirectoryMiddleware,
+ create_asgi_app,
+)
contents = """
import marimo
@@ -77,10 +86,10 @@ class TestASGIAppBuilder(unittest.TestCase):
client = TestClient(app)
response = client.get("/app1")
assert response.status_code == 200, response.text
- assert "app1.py" in response.text
+ assert "app1" in response.text
response = client.get("/app2")
assert response.status_code == 200, response.text
- assert "app2.py" in response.text
+ assert "app2" in response.text
response = client.get("/")
assert response.status_code == 404, response.text
response = client.get("/app3")
@@ -130,3 +139,265 @@ class TestASGIAppBuilder(unittest.TestCase):
assert response.status_code == 404, response.text
response = client.get("/app1/health")
assert response.status_code == 200, response.text
+
+
+class TestDynamicDirectoryMiddleware(unittest.TestCase):
+ def setUp(self):
+ # Create a temporary directory for test files
+ self.temp_dir = tempfile.mkdtemp()
+
+ # Create some test files
+ self.test_file = Path(self.temp_dir) / "test_app.py"
+ self.test_file.write_text(contents)
+
+ # Create nested directory structure
+ nested_dir = Path(self.temp_dir) / "nested"
+ nested_dir.mkdir()
+ self.nested_file = nested_dir / "nested_app.py"
+ self.nested_file.write_text(contents)
+
+ # Create deeper nested structure
+ deep_dir = nested_dir / "deep"
+ deep_dir.mkdir()
+ self.deep_file = deep_dir / "deep_app.py"
+ self.deep_file.write_text("# Deep nested app")
+
+ self.hidden_file = Path(self.temp_dir) / "_hidden.py"
+ self.hidden_file.write_text(contents)
+
+ # Create a base app that returns 404
+ self.base_app = Starlette()
+
+ async def catch_all(request: Request) -> Response:
+ del request
+ return PlainTextResponse("Not Found", status_code=404)
+
+ self.base_app.add_route("/{path:path}", catch_all)
+
+ # Create a simple app builder
+ def app_builder(base_url: str, file_path: str) -> Starlette:
+ del base_url
+ app = Starlette()
+
+ async def handle_assets(request: Request) -> Response:
+ return PlainTextResponse(
+ f"Asset of {request.path_params['path']}"
+ )
+
+ app.add_route("/assets/{path:path}", handle_assets)
+
+ async def handle(request: Request) -> Response:
+ del request
+ return PlainTextResponse(f"App from {Path(file_path).stem}")
+
+ app.add_route("/{path:path}", handle)
+ return app
+
+ # Create the middleware
+ self.app_with_middleware = DynamicDirectoryMiddleware(
+ app=self.base_app,
+ base_path="/apps",
+ directory=self.temp_dir,
+ app_builder=app_builder,
+ )
+
+ self.client = TestClient(self.app_with_middleware)
+
+ def tearDown(self):
+ # Clean up temp directory
+ for root, dirs, files in os.walk(self.temp_dir, topdown=False):
+ for name in files:
+ os.remove(os.path.join(root, name))
+ for name in dirs:
+ os.rmdir(os.path.join(root, name))
+ os.rmdir(self.temp_dir)
+
+ def test_non_matching_path_passes_through(self):
+ response = self.client.get("/other/path")
+ assert response.status_code == 404
+ assert response.text == "Not Found"
+
+ def test_missing_file_passes_through(self):
+ response = self.client.get("/apps/nonexistent")
+ assert response.status_code == 404
+ assert response.text == "Not Found"
+
+ def test_hidden_file_passes_through(self):
+ response = self.client.get("/apps/_hidden")
+ assert response.status_code == 404
+ assert response.text == "Not Found"
+
+ def test_valid_app_path(self):
+ response = self.client.get("/apps/test_app/")
+ assert response.status_code == 200
+ assert response.text == "App from test_app"
+
+ def test_missing_trailing_slash_redirects(self):
+ response = self.client.get("/apps/test_app", follow_redirects=False)
+ assert response.status_code == 307
+ assert response.headers["location"] == "/apps/test_app/"
+
+ def test_loading_assets(self):
+ # Should not work before the app is created
+ response = self.client.get("/apps/test_app/assets/marimo.css")
+ assert response.status_code == 404
+
+ # First request should create the app
+ response = self.client.get("/apps/test_app/")
+ assert response.status_code == 200
+
+ response = self.client.get("/apps/test_app/assets/marimo.css")
+ assert response.status_code == 200
+ assert response.text == "Asset of marimo.css"
+
+ def test_websocket_path_rewriting(self):
+ # Create a WebSocket test app
+ def ws_app_builder(base_url: str, file_path: str) -> Starlette:
+ del base_url
+ app = Starlette()
+
+ async def websocket_endpoint(websocket: WebSocket) -> None:
+ await websocket.accept()
+ await websocket.send_text(f"WS from {Path(file_path).stem}")
+ await websocket.close()
+
+ app.add_websocket_route("/ws", websocket_endpoint)
+
+ async def handle(request: Request) -> Response:
+ del request
+ return PlainTextResponse(f"App from {Path(file_path).stem}")
+
+ app.add_route("/", handle)
+ return app
+
+ # Create middleware with WebSocket support
+ ws_middleware = DynamicDirectoryMiddleware(
+ app=self.base_app,
+ base_path="/apps",
+ directory=self.temp_dir,
+ app_builder=ws_app_builder,
+ )
+ ws_client = TestClient(ws_middleware)
+
+ # First request should create the app
+ response = ws_client.get("/apps/test_app/")
+ assert response.status_code == 200
+
+ with ws_client.websocket_connect("/apps/test_app/ws") as websocket:
+ data = websocket.receive_text()
+ assert data == "WS from test_app"
+
+ def test_app_caching(self):
+ # First request should create the app
+ response1 = self.client.get("/apps/test_app/")
+ assert response1.status_code == 200
+
+ # Get the cached app
+ cached_app = self.app_with_middleware._app_cache[str(self.test_file)]
+
+ # Second request should use the same app
+ response2 = self.client.get("/apps/test_app/")
+ assert response2.status_code == 200
+
+ # Verify the app is still the same instance
+ assert (
+ self.app_with_middleware._app_cache[str(self.test_file)]
+ is cached_app
+ )
+
+ def test_dynamic_file_addition(self):
+ # Add a new file after middleware creation
+ new_file = Path(self.temp_dir) / "new_app.py"
+ new_file.write_text("# New app")
+
+ # Should work with the new file
+ response = self.client.get("/apps/new_app/")
+ assert response.status_code == 200
+ assert response.text == "App from new_app"
+
+ def test_subpath_handling(self):
+ # First request should create the app
+ response = self.client.get("/apps/test_app/")
+ assert response.status_code == 200
+ assert response.text == "App from test_app"
+
+ # Subpath should work
+ response = self.client.get("/apps/test_app/subpath")
+ assert response.status_code == 200
+ assert response.text == "App from test_app"
+
+ def test_query_params_preserved_in_redirect(self):
+ response = self.client.get(
+ "/apps/test_app?param=value", follow_redirects=False
+ )
+ assert response.status_code == 307
+ assert response.headers["location"] == "/apps/test_app/?param=value"
+
+ def test_nested_file_access(self):
+ response = self.client.get("/apps/nested/nested_app/")
+ assert response.status_code == 200
+ assert response.text == "App from nested_app"
+
+ def test_deep_nested_file_access(self):
+ response = self.client.get("/apps/nested/deep/deep_app/")
+ assert response.status_code == 200
+ assert response.text == "App from deep_app"
+
+ def test_nested_file_redirect(self):
+ response = self.client.get(
+ "/apps/nested/nested_app", follow_redirects=False
+ )
+ assert response.status_code == 307
+ assert response.headers["location"] == "/apps/nested/nested_app/"
+
+ def test_nested_file_with_query_params(self):
+ response = self.client.get(
+ "/apps/nested/nested_app?param=value", follow_redirects=False
+ )
+ assert response.status_code == 307
+ assert (
+ response.headers["location"]
+ == "/apps/nested/nested_app/?param=value"
+ )
+
+ def test_nested_file_websocket(self):
+ def ws_app_builder(base_url: str, file_path: str) -> Starlette:
+ del base_url
+ app = Starlette()
+
+ async def websocket_endpoint(websocket: WebSocket) -> None:
+ await websocket.accept()
+ await websocket.send_text(f"WS from {Path(file_path).stem}")
+ await websocket.close()
+
+ app.add_websocket_route("/ws", websocket_endpoint)
+
+ async def handle(request: Request) -> Response:
+ del request
+ return PlainTextResponse(f"App from {Path(file_path).stem}")
+
+ app.add_route("/", handle)
+ return app
+
+ ws_middleware = DynamicDirectoryMiddleware(
+ app=self.base_app,
+ base_path="/apps",
+ directory=self.temp_dir,
+ app_builder=ws_app_builder,
+ )
+ ws_client = TestClient(ws_middleware)
+
+ # First request should create the app
+ response = ws_client.get("/apps/nested/nested_app/")
+ assert response.status_code == 200
+
+ with ws_client.websocket_connect(
+ "/apps/nested/nested_app/ws"
+ ) as websocket:
+ data = websocket.receive_text()
+ assert data == "WS from nested_app"
+
+ def test_nonexistent_nested_path(self):
+ response = self.client.get("/apps/nested/nonexistent/")
+ assert response.status_code == 404
+ assert response.text == "Not Found"