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
example: add flask example (#2686)
Myles Scolnick73d6f05eb06f
diff --git a/examples/frameworks/flask/.gitignore b/examples/frameworks/flask/.gitignorenew file mode 100644index 0000000000..7ed44ae377--- /dev/null+++ b/examples/frameworks/flask/.gitignore@@ -0,0 +1 @@+flask_sessiondiff --git a/examples/frameworks/flask/README.md b/examples/frameworks/flask/README.mdnew file mode 100644index 0000000000..cee8ccf7ed--- /dev/null+++ b/examples/frameworks/flask/README.md@@ -0,0 +1,18 @@+# Flask + marimo++This is a simple example of how to use Flask with marimo. This example programmatically creates multiple marimo apps from a directory, and then serves them as a single Flask app.++This example includes:++- Authentication+- Serving multiple marimo apps from a directory+- A home page listing all the apps+- Loading environment variables from a `.env` file+- Basic logging++## Running the app++1. [Install `uv`](https://github.com/astral-sh/uv/?tab=readme-ov-file#installation)+2. Run the app with `uv run --no-project main.py`++This will start the Flask development server.diff --git a/examples/frameworks/flask/main.py b/examples/frameworks/flask/main.pynew file mode 100644index 0000000000..f511d53aee--- /dev/null+++ b/examples/frameworks/flask/main.py@@ -0,0 +1,115 @@+# /// script+# requires-python = ">=3.12"+# dependencies = [+# "flask",+# "marimo",+# "asgiref",+# "python-dotenv",+# "flask-session",+# "werkzeug",+# ]+# ///+from flask import Flask, render_template, request, redirect, url_for, session+from flask_session import Session+from werkzeug.security import check_password_hash, generate_password_hash+import marimo+import os+import logging+from dotenv import load_dotenv+from functools import wraps+from starlette.middleware.wsgi import WSGIMiddleware+from starlette.applications import Starlette+from starlette.routing import Mount, Route+from starlette.responses import RedirectResponse++# Load environment variables+load_dotenv()++# Set up logging+logging.basicConfig(level=logging.INFO)+logger = logging.getLogger(__name__)++ui_dir = os.path.join(os.path.dirname(__file__), "..", "..", "ui")+templates_dir = os.path.join(os.path.dirname(__file__), "templates")++app = Flask(__name__, template_folder=templates_dir)+app.config['SECRET_KEY'] = os.getenv("SECRET_KEY", "your-secret-key")+app.config['SESSION_TYPE'] = 'filesystem'+Session(app)++# Simulated user database (replace with a real database in production)+users = {"admin": generate_password_hash("password123")}++app_names: list[str] = []+marimo_app = marimo.create_asgi_app()++for filename in os.listdir(ui_dir):+ if filename.endswith(".py"):+ app_name = os.path.splitext(filename)[0]+ app_path = os.path.join(ui_dir, filename)+ marimo_app = marimo_app.with_app(path=f"/{app_name}", root=app_path)+ app_names.append(app_name)++# Wrap the Flask app with WSGIMiddleware+wsgi_app = WSGIMiddleware(app)++# Create the final ASGI app+asgi_app = Starlette(routes=[+ Route("/", endpoint=lambda request: RedirectResponse(url="/flask/")),+ Mount("/flask", app=wsgi_app),+ Mount("/", app=marimo_app.build()),+])++def login_required(f):+ @wraps(f)+ def decorated_function(*args, **kwargs):+ if 'username' not in session:+ return redirect(url_for('login'))+ return f(*args, **kwargs)+ return decorated_function+[email protected]('/login', methods=['GET', 'POST'])+def login():+ if request.method == 'POST':+ username = request.form['username']+ password = request.form['password']+ if username in users and check_password_hash(users[username], password):+ session['username'] = username+ logger.info(f"User {username} logged in successfully")+ return redirect(url_for('home'))+ logger.warning(f"Failed login attempt for user {username}")+ return render_template('login.html', error="Invalid credentials")+ return render_template('login.html')+[email protected]('/logout')+def logout():+ username: str = session.get('username')+ session.clear()+ logger.info(f"User {username} logged out")+ return redirect(url_for('login'))+[email protected]('/')+@login_required+def home():+ return render_template('home.html', username=session['username'], app_names=app_names)+[email protected]('/ping')+def ping():+ return {"message": "pong"}+[email protected](401)+def unauthorized(error: Exception):+ logger.error(f"Unauthorized access: {error}")+ return render_template('error.html', detail="Unauthorized access"), 401+[email protected](404)+def not_found(error: Exception):+ logger.error(f"Page not found: {error}")+ return render_template('error.html', detail="Page not found"), 404++if __name__ == '__main__':+ import uvicorn+ # print valid routes recursively+ for route in asgi_app.routes:+ print(route)+ uvicorn.run(asgi_app, host="0.0.0.0", port=8000)diff --git a/examples/frameworks/flask/templates/error.html b/examples/frameworks/flask/templates/error.htmlnew file mode 100644index 0000000000..9c9831c87a--- /dev/null+++ b/examples/frameworks/flask/templates/error.html@@ -0,0 +1,16 @@+<!DOCTYPE html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Error</title>+ <script src="https://cdn.tailwindcss.com"></script>+ </head>+ <body class="bg-gray-100 flex items-center justify-center h-screen">+ <div class="bg-white p-8 rounded-lg shadow-md w-96">+ <h1 class="text-2xl font-bold mb-6 text-center text-red-600">Error</h1>+ <p class="text-center mb-4">{{ detail }}</p>+ <a href="{{ url_for('home') }}" class="block text-center text-blue-500 hover:text-blue-700">Return to Home</a>+ </div>+ </body>+</html>diff --git a/examples/frameworks/flask/templates/home.html b/examples/frameworks/flask/templates/home.htmlnew file mode 100644index 0000000000..8b4d517aa7--- /dev/null+++ b/examples/frameworks/flask/templates/home.html@@ -0,0 +1,30 @@+<!DOCTYPE html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Home</title>+ <script src="https://cdn.tailwindcss.com"></script>+ </head>+ <body class="bg-gray-100">+ <div class="container mx-auto px-4 py-8">+ <div class="flex justify-between items-center mb-6">+ <h1 class="text-3xl font-bold">Welcome, {{ username }}!</h1>+ <a href="{{ url_for('logout') }}" class="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded">+ Logout+ </a>+ </div>+ <h2 class="text-2xl font-semibold mb-4">Available Applications:</h2>+ <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">+ {% for app_name in app_names %}+ <a href="/{{ app_name }}" class="block" target="{{ app_name }}">+ <div class="bg-white rounded-lg shadow-md hover:shadow-lg transition-shadow duration-300 p-4">+ <h3 class="text-lg font-semibold text-blue-600 hover:text-blue-800">{{ app_name }}</h3>+ <p class="text-gray-600 mt-2">Click to open application</p>+ </div>+ </a>+ {% endfor %}+ </div>+ </div>+ </body>+</html>diff --git a/examples/frameworks/flask/templates/login.html b/examples/frameworks/flask/templates/login.htmlnew file mode 100644index 0000000000..b163decaca--- /dev/null+++ b/examples/frameworks/flask/templates/login.html@@ -0,0 +1,28 @@+<!DOCTYPE html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Login</title>+ <script src="https://cdn.tailwindcss.com"></script>+ </head>+ <body class="bg-gray-100 flex items-center justify-center h-screen">+ <div class="bg-white p-8 rounded-lg shadow-md w-96">+ <h1 class="text-2xl font-bold mb-6 text-center">Login</h1>+ {% if error %}+ <p class="text-red-500 mb-4">{{ error }}</p>+ {% endif %}+ <form action="{{ url_for('login') }}" method="post" class="space-y-4">+ <div>+ <label for="username" class="block mb-1">Username</label>+ <input type="text" id="username" name="username" required class="w-full px-3 py-2 border rounded-md" />+ </div>+ <div>+ <label for="password" class="block mb-1">Password</label>+ <input type="password" id="password" name="password" required class="w-full px-3 py-2 border rounded-md" />+ </div>+ <button type="submit" class="w-full bg-blue-500 text-white py-2 rounded-md hover:bg-blue-600">Login</button>+ </form>+ </div>+ </body>+</html>