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 --include-cloudflare for easy deployment of wasm to cloudflare workers (#4643)
Myles Scolnick031be14b355c
diff --git a/docs/guides/exporting.md b/docs/guides/exporting.mdindex bec9639ab3..dabacb0fa5 100644--- a/docs/guides/exporting.md+++ b/docs/guides/exporting.md@@ -179,6 +179,7 @@ Options:- `--output`: Directory to save the HTML and required assets- `--show-code/--no-show-code`: Whether to initially show or hide the code in the notebook- `--watch/--no-watch`: Watch the notebook for changes and automatically export+- `--include-cloudflare`: Write configuration files necessary for deploying to Cloudflare!!! note "Note"@@ -189,6 +190,26 @@ Options:Pages](publishing/github_pages.md), [Cloudflare Pages](publishing/cloudflare_pages.md) or use the [onlineplayground](publishing/playground.md).+??? note "Deploying to Cloudflare"++ You can include `--include-cloudflare` for deploying to Cloudflare. For example:++ ```+ marimo export html-wasm notebook.py -o my_app/dist --include-cloudflare+ ```++ To run locally, run:++ ```+ npx wrangler dev+ ```++ To deploy to Cloudflare, run:++ ```+ npx wrangler deploy+ ```+### Testing the exportYou can test the export by running the following command in the directory containing your notebook:@@ -209,7 +230,6 @@ After exporting your notebook to WASM HTML, you can publish it to[GitHub Pages](https://pages.github.com/) for free. See our [guide onGitHub Pages](publishing/github_pages.md) to learn more.-### Exporting multiple notebooksIn order to export multiple notebooks under the same folder, you can use the following snippet:@@ -358,5 +378,4 @@ In order to use marimo islands, you need to import the necessary JS/CSS headers</body>```-::: marimo.MarimoIslandGeneratordiff --git a/marimo/_cli/export/cloudflare.py b/marimo/_cli/export/cloudflare.pynew file mode 100644index 0000000000..71e59f8575--- /dev/null+++ b/marimo/_cli/export/cloudflare.py@@ -0,0 +1,79 @@+from pathlib import Path++from marimo._cli.print import bold, echo, green+from marimo._server.print import _utf8+++def create_cloudflare_files(title: str, out_dir: Path) -> None:+ echo("\n" + _utf8("☁️☁️☁️☁️☁️☁️") + "\n")++ parent_dir = out_dir.parent+ index_js = parent_dir / "index.js"+ wrangler_jsonc = parent_dir / "wrangler.jsonc"+ created_files = False++ if index_js.exists():+ echo(+ f"Cloudflare {index_js.name} already exists at {green(str(index_js.absolute()))}. Skipping..."+ )+ else:+ created_files = True+ # Create index.js+ index_js.write_text(+ """+export default {+ async fetch(request, env) {+ const url = new URL(request.url);++ if (url.pathname.startsWith("/health")) {+ return new Response(JSON.stringify({ made: "with marimo" }), {+ headers: { "Content-Type": "application/json" },+ });+ }++ return env.ASSETS.fetch(request);+ },+};""".strip()+ )++ if wrangler_jsonc.exists():+ echo(+ f"Cloudflare {wrangler_jsonc.name} already exists at {green(str(wrangler_jsonc.absolute()))}. Skipping..."+ )+ else:+ created_files = True+ # Create wrangler.jsonc+ wrangler_jsonc.write_text(+ f"""+{{+ "name": "{title}",+ "main": "{index_js.name}",+ "compatibility_date": "2025-01-01",+ "assets": {{+ "directory": "./{out_dir.relative_to(parent_dir)}",+ "binding": "ASSETS"+ }}+}}""".strip()+ )++ cwd = ""+ if parent_dir != Path.cwd() and str(parent_dir) != ".":+ cwd = f" --cwd {parent_dir}"++ if created_files:+ echo(+ f"Cloudflare configuration files created at {green(str(parent_dir.absolute()))}."+ )++ echo(+ f"""+To run locally, run:++ {bold("npx wrangler dev" + cwd)}++To deploy to Cloudflare Pages, run:++ {bold("npx wrangler deploy" + cwd)}+"""+ )+ echo(_utf8("☁️☁️☁️☁️☁️☁️"))diff --git a/marimo/_cli/export/commands.py b/marimo/_cli/export/commands.pyindex b71a7081ec..25afb999f2 100644--- a/marimo/_cli/export/commands.py+++ b/marimo/_cli/export/commands.py@@ -7,10 +7,12 @@ from typing import Callable, Literal, Optionalimport click+from marimo._cli.export.cloudflare import create_cloudflare_filesfrom marimo._cli.parse_args import parse_argsfrom marimo._cli.print import echo, greenfrom marimo._cli.utils import prompt_to_overwritefrom marimo._dependencies.dependencies import DependencyManager+from marimo._server.api.utils import parse_titlefrom marimo._server.export import (ExportResult,export_as_ipynb,@@ -492,6 +494,15 @@ and cannot be opened directly from the file system (e.g. file://)."only relevant for run mode."),)+ "--include-cloudflare/--no-include-cloudflare",+ default=False,+ show_default=True,+ help=(+ "Whether to include Cloudflare Worker configuration files"+ " (index.js and wrangler.jsonc) for easy deployment."+ ),+)@click.option("--sandbox/--no-sandbox",is_flag=True,@@ -511,6 +522,7 @@ def html_wasm(mode: Literal["edit", "run"],watch: bool,show_code: bool,+ include_cloudflare: bool,sandbox: Optional[bool],) -> None:"""Export a notebook as a WASM-powered standalone HTML file."""@@ -567,6 +579,9 @@ def html_wasm("Then open the URL that is printed to your terminal.")+ if include_cloudflare:+ create_cloudflare_files(parse_title(name), out_dir)+outfile = out_dir / filenamereturn watch_and_export(MarimoPath(name), outfile, watch, export_callback)diff --git a/tests/_cli/test_cli_export.py b/tests/_cli/test_cli_export.pyindex 6e12f45fcf..6186701ff5 100644--- a/tests/_cli/test_cli_export.py+++ b/tests/_cli/test_cli_export.py@@ -129,6 +129,36 @@ class TestExportHTML:# Clean upshutil.rmtree(public_dir)+ @staticmethod+ def test_cli_export_html_wasm_cloudflare(temp_marimo_file: str) -> None:+ out_dir = Path(temp_marimo_file).parent / "cloudflare" / "out"+ p = subprocess.run(+ [+ "marimo",+ "export",+ "html-wasm",+ temp_marimo_file,+ "--output",+ out_dir,+ "--include-cloudflare",+ ],+ capture_output=True,+ )+ assert p.returncode == 0, p.stderr.decode()++ # Verify Cloudflare files were created+ assert (out_dir.parent / "index.js").exists()+ assert (out_dir.parent / "wrangler.jsonc").exists()++ # Verify index.js content+ index_js = (out_dir.parent / "index.js").read_text()+ assert "env.ASSETS.fetch(request)" in index_js++ # Verify wrangler.jsonc content+ wrangler = (out_dir.parent / "wrangler.jsonc").read_text()+ assert "name" in wrangler+ assert "main" in wrangler+@staticmethoddef test_cli_export_html_wasm_output_is_file(temp_marimo_file: str,