Skip to main content

⚡ PyDataUI v2

PyDataUI Hero Banner

PyPI version PyPI Downloads Python Version Tests License Docs

The Embedded Streamlit-Like Python Web Framework Built Natively Into FastAPI.
Data Scientists • AI Engineers • FastAPI Teams • MLOps Engineers

🌐 Documentation Website • 🚀 Main Track (Streamlit DX) • 🔌 FastAPI Integration • ⚡ Track 2 (Declarative) • 🌐 Community JSX • 📦 Optional Surfaces (TUI, Desktop, Mobile)


💡 Why PyDataUI Beats Streamlit (and Transpilers)

Developers love Streamlit's 10-second procedural syntax (st.title, st.metric, st.sidebar), until it hits real FastAPI backends and production workloads:

  1. Streamlit: Runs on an isolated Tornado server (port 8501) that cannot embed cleanly into FastAPI, re-executes your entire Python script from line 1 on every click, bottlenecks concurrency, and exposes zero OpenAPI REST routes.
  2. Reflex / Transpilers: Require Node.js/npm build toolchains, 450+ MB node_modules, and a separate JS runtime alongside your FastAPI backend.

PyDataUI keeps Streamlit's ergonomic pdu.* procedural API as its MAIN Track — embedded directly inside a real fastapi.FastAPI instance:

Architecture Comparison

  • Familiar Streamlit-Like Procedural UI (Main Track): Write pdu.write(df), with pdu.sidebar():, pdu.metric(...), and pdu.chat_input(...) just like Streamlit — with pdu.password_input, pdu.download_button, and pdu.link_button.
  • Embedded Directly Inside FastAPI (Single Process): Access pdu.get_fastapi(), attach APIRouter / Depends() / CORSMiddleware / BackgroundTasks, or mount inside an existing microservice via pdu.mount(api, pdu.get_app(), path="/ui") with zero CORS or serialization hops.
  • Built-In Hide & Expand Sidebar (⌘B): Every with pdu.sidebar(): app includes a smooth collapsible drawer button and localStorage state persistence out of the box.
  • Zero Full-Script Re-runs: Powered by surgical HTMX DOM morphing — ML models, DB pools, and FastAPI services stay resident in memory.
  • Native OpenAPI (/docs), Notebooks & share=True: Auto Swagger docs, Jupyter/Google Colab zero-config execution (pdu.run(share=True)), and instant free Cloudflare Quick Tunnels.
  • Secondary / Optional Bonus Surfaces: Need headless SSH inspection or native shells later? Optionally render the exact same app in Terminal UI (pdu.run_tui()) or package it for Desktop / Mobile (PWA, Tauri, Capacitor) without changing your core stack.

🆕 What's New in v1.9.9 — Performance, Multi-Worker Safety & Seven Pillars

v1.9.9 Performance & Multi-Worker Fixes (on top of the Seven Pillars & Hybrid Client/Server runtime):

  • Deterministic Callbacks & vals= (hx-vals): register_callback() uses deterministic SHA-1 fingerprints instead of growing _callbacks, eliminating per-request memory leaks and enabling multi-worker deployments; pass vals={"id": ...} to share 1 callback across N cards.
  • Conditional JS + hx-boost="true" + Immutable Static Cache: chart.umd.min.js, htmx-ws.js, and alpine.min.js load only when used on the page; /_pdu/static/...?v=1.9.9 serves Cache-Control: public, max-age=31536000, immutable; hx-boost="true" enables SPA-like soft navigation.
  • Production CSS Compiler (pydataui build --css-only): Scans .py files and purges static/app.css (zero Node.js required); automatically disables cdn.tailwindcss.com in production (debug=False).
  • Client Repeater (pdu.client_each) & pdu.infinite_scroll: Render Alpine <template x-for> lists from pdu.client_dataset() or hx-trigger="revealed" pagination sentinels.

Seven production capabilities landed together, still with zero Node.js, zero Rust, zero Celery/Redis:

Pillar API What it gives you
1. Stateless Sessions App(storage="signed") HMAC-signed session cookies with no DB/Redis — scale workers behind a load balancer; 4 KB guard built in.
2. Declarative Bindings data-pdu-toggle, data-pdu-modal, data-pdu-tab, pdu.form(persist_draft=True) Toggles, modals, tabs, and offline form drafts with zero custom JavaScript.
3. Background Tasks @pdu.background, pdu.task_progress, pdu.task_status Thread/process task pools with live SSE progress bars — no Celery or broker.
4. URL Query State pdu.query_state(Filters) Typed, validated filters bound to URL params, synced to session state, with HX-Push-Url Back/Forward support.
5. Virtual Tables pdu.virtual_table(df, page_size=50) Server-sliced search/sort/pagination for 1M+ row pandas, polars, or DuckDB datasets — only one page in the DOM.
6. Unified RBAC @pdu.protect(roles=[...]), @pdu.require_role(...) One guard for pages, APIs, and actions; HTMX gets HX-Redirect on 401 plus strict CSRF on mutations.
7. SEO Static Pages @pdu.static_page(...) Pre-rendered pages with OpenGraph tags, ETag caching, and an automatic /sitemap.xml plus /robots.txt.

v2.0.0 hardening on top of the seven pillars

  • Task reliability: JSON-safe task payloads (DataFrames, dates, sets), TTL + capacity retention, and cooperative pdu.cancel_task(...).
  • Data isolation: virtual-table slices are bound to the browser session that registered them; cross-session requests get 403.
  • Multi-worker sessions: configure storage="signed" with session_secret_file= / session_cookie_max_bytes= directly on App(...).
  • Resilient streaming: SSE progress streams send retry: + keepalive comments and close cleanly on cancelled.
  • URL fidelity: pdu.query_state preserves unrelated query params and round-trips repeated/list filters.
  • Cacheable SEO pages: revalidate=, cache_max_age=, proxy-aware canonical URLs, sitemap lastmod, and /robots.txt.

🎨 Visual Theme Showcase: One-Line Enterprise Aesthetics

Forget the rigid or dated look of traditional prototyping tools. PyDataUI gives you production-grade Shadcn & Tailwind aesthetics on day one. Switch between themes in 1 line of Python:

Theme Gallery Showcase

Theme Preset Ideal For Activate with 1 Line
Violet (theme="violet") AI Agent Copilots, LLM Workbenches, Chatbots pdu.set_page_config(theme="violet")
Emerald (theme="emerald") FinTech, Executive SaaS, Billing & MRR KPIs pdu.set_page_config(theme="emerald")
Zinc Dark (theme="zinc") DevOps, Kubernetes Telemetry, Dark Mode Analytics pdu.set_page_config(theme="zinc", dark_mode=True)
Amber (theme="amber") Logistics, E-Commerce Operations, Warehouse Fleet pdu.set_page_config(theme="amber")

📦 Installation

pip install pydataui

🚀 Track 1 (Main Track): Streamlit-Style DX — Upgraded for Production

PyDataUI's primary workflow gives you the exact top-to-bottom Python simplicity you already know from Streamlit—embedded natively on FastAPI with a built-in Hide/Expand sidebar (⌘B), 0 script re-runs, OpenAPI /docs routes, and instant notebook / Cloudflare sharing:

import pydataui as pdu
import pandas as pd

# 1. Page Configuration & Theme
pdu.set_page_config(title="AI & Sales Intelligence", layout="wide", theme="zinc", dark_mode=True)

# 2. Modern Sidebar Controls
with pdu.sidebar():
    pdu.title("Controls")
    pdu.theme_toggle()
    model = pdu.selectbox("Select Model", ["Llama-3.3", "DeepSeek-R1", "GPT-4o"])
    temp = pdu.slider("Temperature", 0.0, 1.0, 0.7)
    dataset = pdu.file_uploader("Upload Evaluation CSV", accept=[".csv"])
    pdu.write(dataset.get_data())

# 3. Main Dashboard Header & Status
pdu.title("GPU Cluster Telemetry & Agent Dispatch")
pdu.success("All 16 H100 SXM5 nodes online. Telemetry streaming active.")

# 4. Multi-Column KPI Grid
col1, col2, col3 = pdu.columns([1, 1, 1])
with col1:
    pdu.metric("Active Sessions", "2,840", delta="+12.4%")
with col2:
    pdu.metric("P99 Inference Latency", "14.2ms", delta="-3.1ms")
with col3:
    pdu.metric("Token Throughput", "8.2k tokens/s", delta="+18.5%")

# 5. Interactive Tabs & Charts
tab_data, tab_chat = pdu.tabs(["Data Explorer", "Operations Copilot"])

with tab_data:
    df = pd.DataFrame({
        "Worker Node": [f"node-{i:02d}" for i in range(1, 5)],
        "GPU Utilization": ["88%", "92%", "78%", "95%"],
        "VRAM Allocated": ["72 GB", "76 GB", "64 GB", "78 GB"]
    })
    pdu.write(df)  # Polymorphic auto-renderer: renders interactive paginated table
    pdu.line_chart([65, 72, 80, 85, 92, 88, 91, 95])

with tab_chat:
    with pdu.chat_message("user"):
        pdu.write("Are there any thermal anomalies on worker nodes?")
    with pdu.chat_message("assistant"):
        pdu.write("All nodes operating within normal thermal limits. Peak VRAM was 78 GB on Node-04.")
    pdu.chat_input("Ask the operations assistant a question...")

if __name__ == "__main__":
    pdu.run(port=8000, share=True)  # Ready in 3.5s with instant public HTTPS link!

Run it with PyDataUI or directly via standard Uvicorn:

python app.py                           # Launch Web UI (http://127.0.0.1:8000) + /docs
uvicorn app:pdu.get_fastapi --reload    # Or mount directly inside your existing FastAPI backend
  • 🌐 Local Web UI: http://127.0.0.1:8000 (with built-in Hide/Expand Sidebar ⌘B)
  • 🔌 FastAPI + OpenAPI Docs: http://127.0.0.1:8000/docs (use pdu.get_fastapi() or pdu.mount(api, pdu.get_app(), path="/ui"))
  • 🔗 Free Cloudflare Public Tunnel (share=True): https://<your-app>.trycloudflare.com (works in Jupyter/Colab too, zero account needed!)
  • 📟 Optional Secondary TUI: pydataui tui app.py renders the same app inside headless terminals/SSH if needed

🧩 Advanced Layout, Positioning & Commercial Dashboard Guide (v1.4.4)

PyDataUI introduces commercial-grade layout freedom and enterprise primitives directly into Streamlit-style procedural Python:

1. Flexbox Layout Engine (pdu.flex, pdu.row, pdu.column)

Take complete control over alignment, justification, gaps, and wrapping with both with context managers and direct component arguments:

import pydataui as pdu

# Horizontal navigation bar with Flexbox between-alignment
with pdu.flex(direction="row", justify="between", align="center", gap=4):
    pdu.subheader("Production Cluster")
    with pdu.row(align="center", gap=2):
        pdu.badge("Operational", color="emerald", variant="subtle")
        pdu.badge("v1.4.4", color="indigo")
        pdu.button("+ Deploy Pod", type="primary")

# Vertical stack with stretch alignment
with pdu.flex(direction="column", align="stretch", gap=3):
    pdu.caption("Cluster Load")
    pdu.progress(85)

2. Responsive CSS Grid Engine (pdu.grid)

Build auto-wrapping, responsive dashboard grids without writing a single CSS media query:

# Auto-responsive card grid: columns automatically wrap when cards reach 260px minimum width!
with pdu.grid(min_column_width="260px", gap=4):
    pdu.stat_card("Active Nodes", "32 / 32", change="100% OK", sparkline=[10, 10, 10], color="emerald")
    pdu.stat_card("P99 Latency", "8.2 ms", change="-2.1ms", sparkline=[14, 12, 10, 8], color="indigo")
    pdu.stat_card("VRAM Allocated", "1,180 GB", change="+12%", sparkline=[60, 75, 85, 92], color="amber")
    pdu.stat_card("Token Throughput", "18.4k t/s", change="+24.8%", sparkline=[12, 15, 17, 18], color="rose")

# Fixed 3-column grid with custom row and column gaps:
with pdu.grid(columns=3, row_gap=3, column_gap=6):
    pdu.metric("Cluster CPU", "42%")
    pdu.metric("Memory", "68%")
    pdu.metric("Network I/O", "1.2 GB/s")

3. Coordinate Positioning Engine (Absolute & Relative)

Add floating status badges, absolute card overlays, and pinned toolbars:

# Elevated Card with Floating Absolute Badge pinned to top-right
with pdu.card(position="relative"):
    pdu.badge("HOTSPOT DETECTED", color="rose", position="absolute", top="14px", right="14px")
    pdu.title("Worker Node 04")
    pdu.line_chart([65, 72, 80, 85, 94, 98, 82], color="rose")

# Pinned Bottom Toolbar (sticky action bar docked to viewport)
with pdu.pinned(position="bottom"):
    with pdu.flex(justify="between", align="center", class_name="max-w-4xl mx-auto"):
        pdu.text("3 worker nodes require kernel updates.")
        pdu.button("Apply Batch Update", type="primary")

4. Advanced Tabs & Headless Multi-Step Wizards (pdu.tabs)

# 1. Full-width equal distribution tabs
tab_a, tab_b = pdu.tabs(["System Telemetry", "Security Audit"], expand=True)

# 2. Modern Segmented Pill Tabs
tab_week, tab_month = pdu.tabs(["7 Days", "30 Days"], variant="pill")

# 3. Headless Step-by-Step Wizard (tab headers completely hidden)
# Build custom multi-step onboarding, checkouts, and AI interview forms in 1 line!
steps = pdu.tabs(["Step 1: Account", "Step 2: Payment", "Step 3: Launch"], hide_tab_buttons=True)
with steps[0]:
    pdu.text_input("Company Name")
    pdu.button("Next: Payment →", on_click=lambda: pdu.session_state.update({"step": 1}))

5. Commercial Dashboard & Analytics Primitives

# 1. Status Badges (subtle, solid, outline with preset colors or custom hex)
pdu.badge("Online", color="emerald", variant="subtle")
pdu.badge("Critical", color="rose", variant="solid")
pdu.badge("Draft", color="zinc", variant="outline")

# 2. Pure SVG Inline Sparklines (zero external dependencies, renders in 0.001ms)
pdu.sparkline([12, 14, 18, 15, 22, 28, 35], color="indigo", height=32, fill=True)

# 3. Executive StatCard with Icon and Sparkline
pdu.stat_card(title="MRR Velocity", value="$154,200", change="+18.2%", sparkline=[90, 110, 130, 154], icon="📈", color="emerald")

# 4. Temporal Inputs bound to session_state
pdu.date_input("Audit Window", value="2026-11-18", key="audit_date")
pdu.time_input("Maintenance Schedule", value="02:00", key="maint_time")

# 5. Search Bar with Instant HTMX Callback
pdu.search_input(placeholder="Search telemetry logs...", key="log_query", on_search=filter_logs)

# 6. Commercial SaaS Pricing Cards
with pdu.grid(columns=3, gap=6):
    pdu.pricing_card("Starter", "$29", features=["Up to 5 nodes", "Community Slack"])
    pdu.pricing_card("Pro", "$149", features=["50 nodes", "24/7 SLA", "90-day logs"], highlighted=True, badge_label="BEST VALUE")
    pdu.pricing_card("Enterprise", "Custom", features=["Unlimited nodes", "Dedicated VPC"])

# 7. Spacing Primitives
pdu.spacer(height=24)        # 24px vertical spacer
pdu.divider(label="OR")      # Horizontal divider with centered label

6. Scrollable Containers & Streamlit-Style Height Constraints (v1.5.2)

Full native support for fixed-height scrollable views with sleek, modern themed thin scrollbars (overflow-y: auto, overflow-x: auto):

# 1. Streamlit-Style Scrollable Container with Fixed Height and Border
with pdu.container(height=300, border=True):
    pdu.subheader("Real-Time Event Stream")
    for event in event_feed:
        pdu.write(event)  # Smoothly scrolls vertically with themed thin scrollbars!

# 2. Dedicated Scrollable Container (Horizontal, Vertical, or Both)
with pdu.scrollable(height=240, direction="y"):
    pdu.dataframe(large_dataframe)

# 3. Elevated Card with Scrollable Body & Pinned Header Bar
with pdu.card(title="System Audit Logs", subtitle="Live telemetry traces", height=350, scroll=True):
    for log in logs:
        pdu.caption(f"[{log.time}] {log.message}")

7. Core Interactive Patterns & Developer FAQ (v1.5.5)

A. Instant Theme Toggle (Dark & Light Mode)

Toggle themes with zero latency anywhere in your sidebar or header:

pdu.theme_toggle()  # One-click client switcher between Light & Dark mode
  • How it works: Swaps the .dark class and data-theme attribute on <html>. All CSS variables (--pdu-color-bg, --pdu-color-card, --foreground, etc.) update immediately across all sidebars, cards, inputs, and tables.
  • Persistence: Automatically remembers the user's choice in browser localStorage.
B. File Uploading & Dataset Inspection

PyDataUI supports two powerful upload patterns:

1. Zero-Boilerplate Procedural Flow (Recommended)

with pdu.sidebar():
    dataset = pdu.file_uploader("Upload Evaluation CSV", accept=[".csv"])
    pdu.write(dataset.get_data())
    pdu.write(dataset.get_data())  # Or simply pdu.write(dataset)
  • Before file selection: Cleanly resolves with zero errors or empty boxes.
  • Upon file selection: Automatically uploads, shows a green badge (✓ file.csv), parses CSV/TSV/JSON/Parquet into Pandas, and displays the interactive table.

2. Custom Callback Pattern

def handle_upload(file):
    df = file.to_pandas()  # Or pd.read_csv(file)
    pdu.session_state["df"] = df
    pdu.toast(f"Loaded {len(df)} rows from {file.filename}!", icon="📊")

# Pass the function reference (do NOT call handle_upload() upfront with parentheses or await!)
pdu.file_uploader("Upload CSV", accept=[".csv"], on_change=handle_upload)
C. Interactive DataTables with Live Search & Sorting

Both pdu.write(df) / pdu.dataframe(df) and pdu.table(records) include instant client-side live search and column sorting:

  • Live Search: Type into the search box to filter table rows with zero latency and zero server reruns.
  • Column Sorting: Click any column header to sort ascending (▲) or descending (▼) numerically or alphabetically.
D. Chat & Conversational AI Interfaces
tab_data, tab_chat = pdu.tabs(["Data Explorer", "Operations Copilot"])

with tab_chat:
    with pdu.chat_message("user"):
        pdu.write("Thermal status?")
    with pdu.chat_message("assistant"):
        pdu.write("All worker nodes online.")
    pdu.chat_input("Ask a question...")  # Automatically appends conversation & preserves active tab

🧩 Layout Containers & Context Managers Guide

PyDataUI provides first-class support for Python context managers (with blocks) as well as direct method chaining across all structural layout primitives:

import pydataui as pdu

# 1. Elevated Cards with optional Title/Subtitle
with pdu.card(title="Account Settings", subtitle="Manage security and preferences"):
    pdu.text_input("Display Name", key="user_name")
    pdu.checkbox("Enable Two-Factor Authentication")
    pdu.button("Save Preferences")

# 2. Scoped Containers (with optional card border styling)
with pdu.container(border=True):
    pdu.subheader("Audit Log")
    pdu.write("All system events are synchronized with SIEM.")

# 3. Horizontal & Vertical Stacks
with pdu.row():
    pdu.button("Cancel", type="secondary")
    pdu.button("Submit", type="primary")

with pdu.column():
    pdu.caption("Step 1: Configuration")
    pdu.caption("Step 2: Deployment")

# 4. Multi-Column Grid with Direct & Context Syntax
col1, col2 = pdu.columns([2, 1])
with col1:
    pdu.metric("Throughput", "14.2k t/s", delta="+18%")
# Direct method call without `with` is also 100% supported!
col2.metric("P99 Latency", "12.8 ms", delta="-2.4ms")

# 5. Collapsible Expanders & Dialog Overlays
with pdu.expander("💡 Deep Reasoning Trace (1,420 tokens)"):
    pdu.code("SELECT * FROM cluster_telemetry WHERE latency > 100;")

with pdu.dialog("Confirm Deletion"):
    pdu.write("This action will permanently revoke the API key.")
    pdu.button("Revoke Key", type="destructive")

# 6. Live Progress Status Containers
with pdu.status("Executing cluster deployment...", expanded=True) as s:
    pdu.write("Validating manifest...")
    pdu.write("Deploying 32 pods...")
    s.update(label="Deployment Complete!", state="complete", expanded=False)

🔐 Multi-Page Apps, Signup & Production Authentication

Create complete enterprise SaaS user flows (Registration, Sign In, Role-Protected Dashboard) in pure procedural Python:

import pydataui as pdu

pdu.set_page_config(title="SaaS Portal", theme="indigo", dark_mode=True)

# 1. Public Registration Page
@pdu.page("/signup", public=True)
def signup_screen():
    with pdu.card(title="Create Enterprise Account", subtitle="Get started in 30 seconds"):
        with pdu.form("signup_form"):
            pdu.text_input("Username", key="reg_user")
            pdu.text_input("Work Email", key="reg_email")
            pdu.text_input("Password", type="password", key="reg_pass")
            
            def handle_signup():
                u = pdu.session_state.get("reg_user")
                p = pdu.session_state.get("reg_pass")
                e = pdu.session_state.get("reg_email")
                if not u or not p:
                    pdu.error("Please fill all required fields")
                    return
                pdu.create_user(u, p, email=e, roles=["admin"])
                pdu.login(u, p)
                pdu.switch_page("/dashboard")

            pdu.form_submit_button("Create Account & Launch", on_click=handle_signup)

# 2. Public Login Page
@pdu.page("/login", public=True)
def login_screen():
    with pdu.card(title="Sign In", subtitle="Welcome back"):
        with pdu.form("login_form"):
            pdu.text_input("Username", key="login_user")
            pdu.text_input("Password", type="password", key="login_pass")

            def handle_login():
                u = pdu.session_state.get("login_user")
                p = pdu.session_state.get("login_pass")
                if pdu.login(u, p):
                    pdu.switch_page("/dashboard")
                else:
                    pdu.error("Invalid username or password")

            pdu.form_submit_button("Sign In", on_click=handle_login)

# 3. Role-Protected Dashboard
@pdu.page("/dashboard", roles=["admin"])
def dashboard_screen():
    with pdu.sidebar():
        pdu.title("Ops Console")
        pdu.write(f"Logged in as: **{pdu.session_state.get('user')}**")
        pdu.button("Log Out", on_click=lambda: (pdu.logout(), pdu.switch_page("/login")))

    pdu.title("Production Operations Dashboard")
    col1, col2, col3 = pdu.columns(3)
    col1.metric("Active Clusters", "32 / 32", delta="100% OK")
    col2.metric("VRAM Pool", "1,180 GB", delta="92% Utilized")
    col3.metric("Latency P99", "12.8 ms", delta="-2.4ms")

if __name__ == "__main__":
    pdu.run(port=8000)

⚡ Track 2: Reflex-Style Declarative Apps (Optional Scale Tier)

Prefer explicit declarative component trees (Container, Card, AppShell) instead of Track 1 procedural Python? PyDataUI also includes a Reflex-grade declarative component & state engine in pure Python with zero Node.js or npm dependencies:

from pydataui import App, Container, Card, Heading, Text, Button, Table, Row, state
from pydantic import BaseModel, Field

app = App(title="CloudAI Enterprise SaaS")

# 1. Declarative Server State & Reactive Actions
s = state(credits=1500, deployments=[{"id": "dep-01", "model": "Llama-3.3-70B", "status": "Running"}])

@s.action
def deploy_model(model_name: str = "Mistral-Large"):
    s.deployments.append({"id": f"dep-0{len(s.deployments) + 1}", "model": model_name, "status": "Running"})
    s.credits -= 100

# 2. Declarative Component Tree & Page Route
@app.page("/")
def dashboard_page():
    return Container(
        Row(
            Heading("Enterprise AI Dashboard", level=1),
            Button("+ Deploy Mistral", on_click=lambda: deploy_model("Mistral-Large"), variant="primary"),
            class_name="flex justify-between items-center mb-6"
        ),
        Card(
            Heading("Remaining Credits", level=4),
            Text(s.credits, class_name="text-2xl font-bold text-emerald-600"),
            Table(data=s.deployments),
            class_name="p-6 shadow-sm"
        ),
        class_name="max-w-5xl mx-auto p-8"
    )

# 3. Built-In Native FastAPI API Route
class PromptRequest(BaseModel):
    prompt: str = Field(..., min_length=1)

@app.api("/api/v1/generate", method="POST", tags=["AI Inference"])
async def generate_api(body: PromptRequest):
    return {"success": True, "output": f"Completion for: {body.prompt[:40]}..."}

if __name__ == "__main__":
    app.run(port=8000)

⚖️ Streamlit-Style (Track 1) vs. Reflex-Style (Track 2): Which is Production-Grade?

A frequent question when adopting PyDataUI is whether Track 1 (Streamlit-style procedural pdu.*) is only for prototypes while Track 2 (Reflex-style declarative App(), Container()) is for production.

In PyDataUI, BOTH Track 1 and Track 2 are 100% Production-Grade.

Here is the architectural reason why:

  • Track 1 is NOT Streamlit under the hood: It borrows Streamlit's ergonomic procedural syntax (pdu.text_input, pdu.button, pdu.metric), but compiles to the exact same ASGI FastAPI backend and surgical HTMX DOM-diffing engine as Track 2. It never re-runs your script from line 1. It shares process memory, runs in Uvicorn multi-worker clusters, and exposes full Swagger docs at /docs.
  • Track 2 provides Reflex-grade declarative component architecture: It uses explicit component trees (Container, Row, Card) and declarative state bindings (s = state(), @s.action), which is ideal for multi-engineer teams building reusable, modular UI components.

When to Choose Which Track:

Dimension Track 1: Procedural (pdu.*) Track 2: Declarative (App(), Container())
Syntax Style Linear procedural Python (Streamlit-like) Component tree & State objects (Reflex-like)
Production Ready? Yes (100% FastAPI + HTMX) Yes (100% FastAPI + HTMX)
Full-Script Re-runs? ❌ Never (Surgical DOM fragment morphing) ❌ Never (Targeted @s.action dispatch)
FastAPI Access & Docs pdu.get_fastapi(), auto /docs app.fastapi, auto /docs
Best Team Fit Solo developers, ML/AI engineers, fast MVPs Multi-developer teams, large modular codebases
Component Layout Scoped context managers (with pdu.card():) Hierarchical nesting (Container(Row(Card(...))))
Server Concurrency 1,000+ concurrent ASGI sessions 1,000+ concurrent ASGI sessions

🔌 Full FastAPI & Starlette Production Integration

Because PyDataUI runs on native FastAPI and Starlette, 100% of FastAPI and Starlette features work out of the box. Read the full FastAPI + PyDataUI Complete Integration Guide (covers pdu.get_fastapi(), APIRouter, Depends(), lifespan, CORS, CSRF, sub-mount guarantees, and TestClient recipes) or jump straight into examples/fastapi_track1_unified.py.

1. Direct Access to Underlying FastAPI Application

Access the underlying FastAPI instance at any time to register routers, background tasks, custom exception handlers, or dependency injection:

import pydataui as pdu
from fastapi import APIRouter, BackgroundTasks

# Access the FastAPI instance in Procedural DX or Full-Stack mode
fastapi_app = pdu.get_fastapi()  # or app.fastapi

# Attach FastAPI APIRouter
router = APIRouter(prefix="/v1")

@router.post("/notify")
def send_notification(bg: BackgroundTasks):
    bg.add_task(send_async_slack_alert, "Deployment succeeded")
    return {"status": "enqueued"}

fastapi_app.include_router(router)

2. Starlette & FastAPI Middlewares (CORS, GZip, Security)

Attach any Starlette or FastAPI middleware directly:

from starlette.middleware.cors import CORSMiddleware
import pydataui as pdu

app = pdu.get_app()
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

3. Production Swagger UI Hardening & Customization

Take full control over API documentation when moving to production:

import pydataui as pdu

# Option A: Completely remove /docs and /openapi.json in production (404)
hardened_app = pdu.App(title="Production Service", docs_url=None, openapi_url=None)

# Option B: Filter and customize Swagger UI parameters (Track 1)
pdu.set_page_config(
    swagger_ui_parameters={
        "filter": True,                              # Enable instant search filter in Swagger
        "defaultModelsExpandDepth": -1,              # Hide data models by default
        "syntaxHighlight.theme": "monokai",          # Custom code highlighting theme
        "persistAuthorization": True                 # Remember auth tokens across refreshes
    }
)

# Option C: Lock down /docs behind Role-Based Authentication
# Only users logged in with the "admin" role can access the Swagger UI!
pdu.set_page_config(docs_roles=["admin"])

4. 1-Line FastAPI Mounting

Already have an existing FastAPI backend or microservice? Mount PyDataUI cleanly with mount() (sets root_path automatically for sub-mounted static assets and events):

from fastapi import FastAPI
from pydataui import App, Container, Heading, mount

# 1. Existing Enterprise FastAPI Application
api = FastAPI(title="Core Microservice")

@api.get("/api/health")
def health():
    return {"status": "healthy"}

# 2. Build PyDataUI Dashboard (or mount Track 1 via `mount(api, pdu.get_app(), path="/dashboard")`)
dashboard = App(title="Ops Portal")

@dashboard.page("/")
def ops_home():
    return Container(Heading("Operations Portal"))

# 3. Mount cleanly — 1 process, 1 port, 0ms in-memory access!
mount(api, dashboard, path="/dashboard")

Run with standard Uvicorn:

uvicorn main:api --reload --port 8000
  • 📡 FastAPI API: http://127.0.0.1:8000/api/health
  • 📖 FastAPI Docs: http://127.0.0.1:8000/docs
  • 💻 PyDataUI Dashboard: http://127.0.0.1:8000/dashboard/

🎨 20 Modern Themes + Infinite Custom Palettes

PyDataUI ships with 20 official out-of-the-box color presets matching all standard Shadcn/Tailwind design systems:

20 Color Presets

Category Presets Available Hex Identifiers
Modern Neutrals zinc, slate, stone, neutral, gray #18181b • #0f172a • #1c1917 • #171717 • #111827
Greens & Cyans emerald, green, teal, cyan #059669 • #16a34a • #0d9488 • #0891b2
Blues & Purples blue, indigo, violet, purple #2563eb • #4f46e5 • #7c3aed • #9333ea
Pinks & Warm fuchsia, pink, rose, red, orange, amber, yellow #c026d3 • #db2777 • #e11d48 • #dc2626 • #ea580c • #d97706 • #ca8a04

🔮 1. AI Copilot & Agent Playground (theme="violet")

Built for LLM workbenches, multi-turn chat agents, and real-time inference telemetry. Features collapsible reasoning thought traces, token speed counters, and syntax-highlighted code output:

Violet AI Copilot Theme

import pydataui as pdu

# 1. Page Configuration & Theme
pdu.set_page_config(title="DeepAgent Copilot", theme="violet", dark_mode=True)

# 2. Left Control Sidebar
with pdu.sidebar():
    pdu.header("DeepAgent Copilot")
    pdu.caption("Powered by PyDataUI v1.5.2")
    pdu.divider()

    model = pdu.selectbox("INFERENCE MODEL", ["DeepSeek-R1-Distill-70B", "Llama-3.3-70B"])
    temp = pdu.slider("TEMPERATURE (0.70)", 0.0, 1.0, 0.70)

    pdu.caption("CONTEXT (32k / 64k)")
    pdu.progress(50)

    pdu.text_area(
        "SYSTEM PROMPT",
        value="You are an autonomous SRE copilot monitoring 16 H100 distributed worker nodes...",
        height=80
    )
    pdu.button("+ New Agent Session", type="primary")

# 3. Main Chat Top Bar with Live Telemetry Badges
with pdu.flex(justify="between", align="center", class_name="mb-4 pb-3 border-b border-border/40"):
    with pdu.column(gap=0):
        pdu.subheader("Cluster Diagnostic Agent")
        pdu.caption("Session: #agent-session-8492 • Zero-latency in-memory bridge")
    with pdu.row(gap=2):
        pdu.badge("⚡ 84.6 t/s", color="violet", variant="subtle")
        pdu.badge("✓ Latency: 12ms", color="emerald", variant="subtle")

# 4. Multi-Turn Diagnostic Chat Stream
with pdu.chat_message("user"):
    pdu.write("Analyze the P99 latency spike on cluster node-04 and remediate.")

with pdu.chat_message("assistant"):
    with pdu.expander("💡 Thought Process: 1,420 tokens analyzed (0.4s)", expanded=True):
        pdu.write(
            "I inspected real-time Prometheus traces on **node-04**. A cache compaction deadlock "
            "triggered temporary VRAM starvation. Executing zero-downtime rebalance:"
        )

    pdu.code("""import pydataui as pdu

await cluster.isolate_node("node-04", drain_timeout=15)
# In-memory execution: 0ms network hop, cluster stabilized!""", language="python")

    pdu.success(
        "**Remediation Executed Successfully**  \n"
        "P99 Latency dropped from 284ms to 12.1ms • All 32 pods re-routed to node-05 and node-06"
    )

# 5. Bottom Interactive Prompt Input
pdu.chat_input("Ask Copilot to run cluster commands, query metrics, or debug models...")

if __name__ == "__main__":
    pdu.run(port=8000, share=True)  # Instantly generates public HTTPS link!

💎 2. FinTech, Billing & Revenue Analytics (theme="emerald")

Engineered for SaaS metrics, ARR/MRR acceleration, transaction ledgers, and executive board reporting:

Emerald FinTech Theme

import pydataui as pdu
import pandas as pd

# 1. Page Configuration & Theme
pdu.set_page_config(title="ApexPay Financial", theme="emerald", layout="wide", dark_mode=True)

# 2. Commercial Top Navigation Bar
pdu.navbar(
    title="ApexPay",
    logo="💳",
    links=[
        {"label": "Overview", "href": "/"},
        {"label": "Invoices", "href": "/invoices"},
        {"label": "Customers", "href": "/customers"},
        {"label": "Webhooks", "href": "/webhooks"},
        {"label": "REST API", "href": "/docs"}
    ],
    search=False
)

# 3. 4 Executive KPI Cards
col1, col2, col3, col4 = pdu.columns([1, 1, 1, 1])
with col1: pdu.metric("Annual Run Rate (ARR)", "$1,840,500", delta="+24.8%")
with col2: pdu.metric("Monthly Recurring (MRR)", "$154,200", delta="+18.2%")
with col3: pdu.metric("Paying Accounts", "2,840", delta="+142 mo")
with col4: pdu.metric("Net Retention Rate", "118.4%", delta="TOP 5%")

# 4. Main Chart & Billing Channels Split Row
chart_col, split_col = pdu.columns([2, 1])

with chart_col:
    with pdu.card(title="MRR Acceleration & Cohort Revenue", subtitle="Real-time telemetry morphing via HTMX • In-memory compute"):
        pdu.area_chart([92, 104, 118, 132, 145, 154])  # Peaks at $154,200 (Nov)

with split_col:
    with pdu.card(title="Billing Channels", subtitle="Enterprise vs Self-Serve"):
        pdu.caption("Enterprise Wire / Invoicing (68%) — **$104.8k**")
        pdu.progress(68)
        pdu.caption("Credit Card Auto-Billing (24%) — **$37.0k**")
        pdu.progress(24)
        pdu.caption("Automated ACH Direct (8%) — **$12.4k**")
        pdu.progress(8)

# 5. Recent Commercial Invoices Ledger
pdu.subheader("Recent Commercial Invoices")
df_invoices = pd.DataFrame({
    "CUSTOMER": ["Stripe Global AI Labs", "HuggingFace Enterprise", "Anthropic Partner Node"],
    "INVOICE ID": ["inv_2026_9841", "inv_2026_9842", "inv_2026_9843"],
    "PLAN TIER": ["Enterprise Dedicated (128x H100)", "Scale AI Tier (64x A100)", "Claude 3.5 Sonnet Integration"],
    "BILLING CYCLE": ["Annual (Prepaid)", "Monthly Usage", "Net-15 Invoice"],
    "AMOUNT": ["$48,000.00", "$22,450.00", "$18,900.00"],
    "STATUS": ["PAID ✓", "PAID ✓", "PENDING"]
})
pdu.table(df_invoices)

if __name__ == "__main__":
    pdu.run(port=8000)

⚡ 3. DevOps, Cluster Telemetry & Dark Mode Analytics (theme="zinc", dark_mode=True)

High-density, low-eye-strain telemetry for Kubernetes clusters, GPU farms, and real-time distributed systems:

Zinc Dark Mode Telemetry

import pydataui as pdu
import pandas as pd

# 1. Page Configuration & Theme
pdu.set_page_config(title="Cluster Telemetry", theme="zinc", layout="wide", dark_mode=True)

# 2. Left Telemetry & Node Navigation Sidebar
with pdu.sidebar():
    pdu.header("Cluster Telemetry")
    pdu.caption("Kubernetes H100 Mesh")
    pdu.divider()

    cluster = pdu.selectbox("ACTIVE CLUSTER", ["us-east-h100-prod", "eu-central-a100-prod"])
    pdu.radio("Navigation", [
        "📊 Overview & Health",
        "🖥️ GPU Nodes (16)",
        "📦 Active Pods (128)",
        "⚡ Token Throughput",
        "🚨 Alert Channels (0)",
        "🛠️ OpenAPI REST /docs"
    ])

    with pdu.card(title="Cluster Resources"):
        pdu.caption("CPU Allocation (48%)")
        pdu.progress(48)
        pdu.caption("VRAM Usage (88%)")
        pdu.progress(88)
        pdu.caption("PCIe Bandwidth (94%)")
        pdu.progress(94)
        pdu.caption("🟢 All 16 nodes operating at 100%")

# 3. Main Dashboard Header & Quick Action Buttons
with pdu.flex(justify="between", align="center", class_name="mb-4 pb-3 border-b border-border/40"):
    with pdu.column(gap=0):
        pdu.subheader("Real-Time Cluster Telemetry")
        pdu.caption("Streaming in-process telemetry • 0ms API overhead")
    with pdu.row(gap=2):
        pdu.button("📥 Export Parquet")
        pdu.button("⚡ Drain & Rebalance", type="destructive")

# 4. 4 High-Density KPI Metrics
col1, col2, col3, col4 = pdu.columns(4)
with col1: pdu.metric("P99 Inference Latency", "12.8 ms", delta="-2.4ms")
with col2: pdu.metric("VRAM Allocated", "1,180 GB", delta="92.1%")
with col3: pdu.metric("Active Model Pods", "32 / 32", delta="100% OK")
with col4: pdu.metric("Token Throughput", "14.2k t/s", delta="+18%")

# 5. Dual-Series Telemetry Line Chart
with pdu.card(title="Token Throughput (t/s) vs Inference Latency (ms)"):
    pdu.line_chart([140, 110, 125, 75, 60, 45])

# 6. Worker Nodes Real-Time Status Table
pdu.subheader("Active Worker Nodes")
df_nodes = pd.DataFrame({
    "WORKER NODE": ["us-east-h100-01", "us-east-h100-02", "us-east-h100-03"],
    "HARDWARE": ["8x H100 SXM5 80GB", "8x H100 SXM5 80GB", "8x H100 SXM5 80GB"],
    "TEMP": ["64°C", "66°C", "71°C"],
    "GPU LOAD": ["94% VRAM", "92% VRAM", "98% VRAM"],
    "STATUS": ["ONLINE", "ONLINE", "ONLINE"]
})
pdu.table(df_nodes)

if __name__ == "__main__":
    pdu.run(port=8000)

🔐 4. Enterprise Authentication & Glassmorphic Login (theme="indigo")

Clean, secure enterprise login with single sign-on (SSO), CSRF tokens, input validation, and atmospheric indigo dark theming:

import pydataui as pdu

# 1. Page Configuration & Theme
pdu.set_page_config(title="Login — NexusCloud AI", theme="indigo", dark_mode=True)

# 2. Centered Glassmorphic Authentication Card
with pdu.box(class_name="min-h-screen flex items-center justify-center p-4"):
    with pdu.card(class_name="max-w-md w-full p-8 shadow-2xl backdrop-blur-xl border border-border/80"):
        # Brand Badge & Title Header
        with pdu.flex(direction="col", align="center", class_name="mb-6 text-center space-y-2"):
            pdu.badge("🛡️ SSO & Enterprise Security", color="indigo", variant="subtle")
            pdu.header("Sign in to NexusCloud")
            pdu.caption("Enter your corporate credentials or single sign-on provider")

        # Email & Password Form Inputs
        email = pdu.text_input("Corporate Email", placeholder="alex.vance@company.com", key="auth_email")
        password = pdu.text_input("Password", type="password", placeholder="••••••••••••", key="auth_pass")

        # Remember Me Checkbox & Reset Password Link
        with pdu.flex(justify="between", align="center", class_name="my-3 text-xs"):
            pdu.checkbox("Remember this workstation (30 days)", key="remember_me")
            pdu.link("Forgot password?", href="/reset-password")

        # Primary Submit Action
        pdu.button("Sign In to Workspace ⚡", type="primary", use_container_width=True)

        pdu.divider("or continue with enterprise SSO")

        # OAuth / SSO Provider Quick Buttons
        with pdu.row(gap=2):
            pdu.button("Google Workspace", use_container_width=True)
            pdu.button("Okta / SAML 2.0", use_container_width=True)

        # Enterprise Compliance Caption
        with pdu.flex(justify="center", class_name="mt-6 text-xs text-muted-foreground"):
            pdu.caption("🔒 256-bit TLS encrypted • ISO 27001 & SOC 2 Type II certified")

if __name__ == "__main__":
    pdu.run(port=8000)

End-to-end commercial portal featuring a sticky top navigation bar, collapsible hierarchy sidebar, breadcrumbs, high-density KPI metrics, and a docked commercial footer:

import pydataui as pdu
import pandas as pd

# 1. Page Configuration & Theme
pdu.set_page_config(title="DataMesh Cloud Platform", theme="slate", layout="wide", dark_mode=True)

# 2. Sticky Commercial Top Navigation Bar
pdu.navbar(
    brand="DataMesh Enterprise",
    logo="🌐",
    links=[
        {"label": "Overview", "href": "/", "active": True},
        {"label": "Pipelines", "href": "/pipelines"},
        {"label": "Model Registry", "href": "/models"},
        {"label": "Endpoints", "href": "/endpoints"},
        {"label": "Security Logs", "href": "/audit"}
    ],
    search="Search clusters, models, or datasets...",
    user={"name": "Sarah Connor", "role": "Platform Lead"},
    sticky=True
)

# 3. Left Control & Hierarchy Sidebar
with pdu.sidebar():
    pdu.header("DataMesh OS")
    pdu.caption("v1.5.3 Production Mesh")
    pdu.divider()

    env = pdu.selectbox("Active Environment", ["Production (us-east-1)", "Staging (eu-central-1)"])
    pdu.radio("Quick Views", ["📊 Cluster Telemetry", "🚀 Model Deployments", "🛡️ RBAC Permissions", "⚙️ System Settings"])

    with pdu.card(title="Storage Quota"):
        pdu.caption("Distributed S3 Pool (74%)")
        pdu.progress(74)
        pdu.caption("14.8 TB / 20.0 TB Allocated")

# 4. Main Workspace with Breadcrumbs & Action Header
pdu.breadcrumb(["Home", "Compute Mesh", "GPU Worker Nodes"])

with pdu.flex(justify="between", align="center", class_name="mb-4 pb-2 border-b border-border/40"):
    with pdu.column(gap=0):
        pdu.header("Distributed Inference Telemetry")
        pdu.caption("Active workload nodes across multi-region Kubernetes clusters")
    with pdu.row(gap=2):
        pdu.button("📥 Export Parquet")
        pdu.button("⚡ Deploy Endpoint", type="primary")

# 4 KPI Stat Cards with Rounded Delta Badges
c1, c2, c3, c4 = pdu.columns(4)
with c1: pdu.metric("Cluster Throughput", "28.4k req/s", delta="+14.2%")
with c2: pdu.metric("P99 Tail Latency", "11.4 ms", delta="-3.1ms")
with c3: pdu.metric("VRAM Saturation", "88.6%", delta="Optimal")
with c4: pdu.metric("Health Score", "99.98%", delta="100% SLA")

# Real-Time Telemetry Line Chart
with pdu.card(title="P99 Response Time (ms) by Availability Zone", subtitle="Live 5-second polling via in-memory telemetry"):
    pdu.line_chart([18.2, 16.4, 14.8, 12.1, 11.4])

# Active Endpoints Ledger Table
pdu.subheader("Active Model Serving Endpoints")
df_endpoints = pd.DataFrame({
    "MODEL ID": ["llama-3.3-70b-instruct", "deepseek-r1-distill-qwen", "mistral-large-2407"],
    "REPLICAS": ["8 / 8 Pods", "16 / 16 Pods", "4 / 4 Pods"],
    "HARDWARE": ["8x H100 SXM5", "16x A100 80GB", "4x L40S 48GB"],
    "AVG LATENCY": ["14.2 ms", "10.8 ms", "18.6 ms"],
    "STATUS": ["HEALTHY ✓", "HEALTHY ✓", "HEALTHY ✓"]
})
pdu.table(df_endpoints)

# 5. Commercial Footer with Branding, Copyright & Legal Links
pdu.footer(
    brand="DataMesh Cloud",
    logo="🌐",
    copyright="© 2026 DataMesh Systems, Inc. All rights reserved.",
    links=[
        {"label": "Privacy Policy", "href": "/privacy"},
        {"label": "Terms of Service", "href": "/terms"},
        {"label": "SOC 2 Type II", "href": "/security"},
        {"label": "System Status", "href": "/status"}
    ]
)

if __name__ == "__main__":
    pdu.run(port=8000)

Zero Theme Limitations: Custom Palettes & Brand Colors

You are never limited to presets. Define any custom brand palette via hex code or custom dictionary:

# 1. Built-in Preset
pdu.set_page_config(theme="violet")

# 2. Custom Brand Hex
pdu.set_page_config(theme="#4f46e5")

# 3. Unlimited Custom Dictionary Palette
pdu.set_page_config(theme={
    "primary": "#6366f1",
    "primary_hover": "#4f46e5",
    "bg": "#0f172a",
    "accent": "#a855f7"
})

⚖️ Architectural Trade-Offs & Advantage Comparison

When choosing a framework for commercial data applications, AI platforms, or internal tools, understanding where PyDataUI wins and its architectural boundaries is essential.

🏆 Where PyDataUI Outperforms Reflex & Streamlit

  1. 0.02ms In-Memory Model Access: Your UI and your AI models (PyTorch, LangChain, Ollama, Pandas, Polars) share the exact same Python process memory. No JSON serialization overhead, zero internal REST/gRPC latency hops.
  2. 1 Language & 1 Runtime (Zero Node.js): 100% pure Python. Unlike Reflex, PyDataUI requires zero package.json, zero Node.js/npm toolchains, zero Webpack/Babel compilation steps, and 0 MB node_modules (saving ~450 MB).
  3. Surgical HTMX DOM Morphing: Unlike Streamlit (which re-executes lines 1–100 on every user click), PyDataUI dispatches only the targeted state action and surgical DOM swap, eliminating session sync bugs and lag.
  4. Native FastAPI & Auto OpenAPI 3.1: Built directly on FastAPI and Starlette. Every state action can automatically expose an OpenAPI 3.1 REST route with interactive Swagger UI at /docs.
  5. Unified Full-Stack Deployment: 1 process, 1 port. Deploy via standard Docker, Uvicorn, or launch an instant secure public HTTPS tunnel in 3.5 seconds with share=True.

⚠️ Architectural Boundaries: When to Choose What

Being completely transparent about framework design choices:

  1. Streamlit: Best for quick, disposable exploratory scripts and single-user Jupyter notebooks where full-script reruns on every widget click are acceptable.
  2. Reflex: Best if your architecture specifically demands a client-side React SPA transpiler with heavy client-side JavaScript bundles and you already maintain a Node.js/npm CI/CD toolchain.
  3. PyDataUI: Best for data teams, AI engineers, and Python developers who want Streamlit's 10-second procedural prototyping speed AND Reflex's declarative component architecture, but demand a clean 100% pure Python stack powered natively by FastAPI and HTMX with zero Node.js overhead.

📊 4-Way Comprehensive Architecture Comparison

Feature / Dimension Streamlit (Python) Reflex (Python + Node.js) FastAPI (Backend Only) PyDataUI v1.9.9 (Embedded Hybrid Client+Server on FastAPI)
Syntax Ergonomics st.* procedural Component trees ❌ None (API only) pdu.* Track 1 Main (+ Track 2 optional)
Embed Inside FastAPI ❌ Separate Tornado server ❌ Separate Next/Py servers ✅ Core API only ✅ Native (pdu.get_fastapi() & pdu.mount())
Execution on Click ❌ Reruns script lines 1-500 WebSocket roundtrip N/A (REST endpoint) Surgical HTMX swap (0 full rerun)
Collapsible Sidebar Static toggle Manual CSS/props ❌ None ✅ Built-in Hide/Expand + ⌘B Persisted
Build & Dependencies Clean Python 450 MB+ node_modules Clean Python Clean Python (Zero npm / 0 MB)
Built-in REST API & Docs ❌ None Separate backend OpenAPI 3.1 Swagger Auto OpenAPI 3.1 Swagger UI (/docs)
WebSockets Streaming Internal session Mandatory every click Manual WebSockets Native @pdu.channel / live_channel
Responsive Flex & Grid ❌ Primitive columns only Chakra / Tailwind ❌ None Native pdu.flex & pdu.grid
Optional Bonus Surfaces ❌ Browser only ❌ Browser only ❌ None Built-in TUI (pdu.run_tui()) + Desktop/Mobile
Public Sharing Demos Cloud login required Manual hosting Manual cloud hosting share=True (Cloudflare + Notebooks)
Memory per User Session ❌ High (Duplicate DataFrames) 300–500 MB+ (Node + Py) Stateless Ultra-Low (25–45 MB base)

💡 Is Streamlit Only for Prototyping or Full-Stack MVPs?

Streamlit is architecturally optimized for rapid exploratory prototyping and internal data apps, not commercial full-stack SaaS MVPs.

  • The Re-Run Barrier: Every user click re-runs your script from line 1. For complex customer-facing workflows, payment flows, or stateful onboarding, this leads to state race conditions, flashing spinners, and accidental duplicate database queries.
  • No Real Backend/Webhooks: Streamlit lacks a REST API routing engine. You cannot easily listen for Stripe webhooks (/api/webhooks/stripe) or expose API endpoints for mobile or external clients.
  • Memory & Concurrency Ceiling: Persistent WebSockets per tab and duplicated in-memory DataFrames often cause memory exhaustion (OOM) at 20–50 concurrent users.
  • Why PyDataUI Bridges the Gap: PyDataUI retains Streamlit's 1-line procedural simplicity (pdu.text_input, pdu.button, pdu.metric) while running on FastAPI and HTMX—giving you surgical DOM updates (0 script reruns), real REST endpoints, background tasks, and commercial Shadcn visual polish.

⚡ Reflex-Style Declarative Architecture with Zero Node.js Tax

PyDataUI delivers the clean declarative component and state model developers love in Reflex, implemented in 100% pure Python without node_modules or Webpack:

  • Declarative Page Routing: @app.page("/dashboard") route decorators with automatic layout nesting.
  • Native API Route Handlers: @app.api("/api/v1/generate", method="POST") with automatic OpenAPI 3.1 Swagger docs.
  • Declarative Component Trees: Server-rendered Python component trees (Container, Row, Card) compiled directly to semantic HTML.
  • Bi-Directional WebSocket Streaming: @pdu.channel("ticker") and with pdu.live_channel("ticker"): for sub-millisecond telemetry.
  • Modern Design Tokens: Native Tailwind utility classes (class_name="...") and 20+ official Shadcn theme presets.

See docs/PYDATAUI_VS_REFLEX.md for the full architectural breakdown.


⚡ Native FastAPI & Starlette High-Performance ASGI Engine

PyDataUI is powered directly by the FastAPI and Starlette ASGI ecosystem, delivering enterprise-grade asynchronous performance, high-throughput concurrency, and complete integration with existing Python services:

  1. Native ASGI Engine (FastAPI Default): Runs on Starlette and FastAPI with Uvicorn worker clusters. Zero C or Rust compilation toolchains required.
  2. Hybrid SSR + Client Islands (v1.9.9, Livewire/Hotwire-style): Pair server @pdu.page / @pdu.fragment / @app.api endpoints with client=True Alpine widget islands (x-model on $store.pdu), pdu.client_dataset() plus dataset= / filters= bindings on pdu.metric(), pdu.dataframe(), and pdu.plotly_chart() (0ms in-browser KPI/table filtering and Plotly.react() redraws), pdu.client_each(), pydataui build --css-only, pdu.mount_static() FastAPI StaticFiles, and offline=True (zero external CDN dependencies). No bundler or build step required.
  3. Automatic OpenAPI 3.1 & Swagger UI: Every state action and API route is documented at /docs out of the box.
  4. Bi-Directional WebSockets: Built-in native WebSocket routing at /_pdu/ws/{channel_name} with full support for HTMX WebSocket extensions (htmx-ws.js).
  5. Seamless Middleware Stack: 100% compatible with Starlette CORS, GZip, Session, and security middlewares.

Scope note: PyDataUI is HTML-over-the-wire, not a Next.js clone. Routing is decorator-based (@page), there is no file-system router, bundler, or React Server Components — components are Python and render to server HTML.

Multi-Worker Production Deployment (Uvicorn & Granian)

PyDataUI is fully ASGI 3.0 compliant. Deploy in production with either the battle-tested Uvicorn worker fleet or the ultra-high-throughput Rust-powered Granian runner:

Option A: Standard Production Runner (Uvicorn)

# High-concurrency multi-worker Uvicorn deployment:
uvicorn app:app.asgi_app --workers 4 --host 0.0.0.0 --port 8000

Option B: Rust-Powered High-Throughput Runner (Granian)

# Maximum ASGI throughput powered by Rust, Tokio & Hyper (38,000+ req/s):
pip install granian
granian --interface asgi app:app.asgi_app --workers 4 --host 0.0.0.0 --port 8000

Direct FastAPI Mounting

Mount PyDataUI into your existing microservices in a single line:

from fastapi import FastAPI
from pydataui import App, Container, Heading, mount

api = FastAPI(title="Enterprise Gateway")
dashboard = App(title="Internal Admin")

@dashboard.page("/")
def home():
    return Container(Heading("Enterprise Ops Portal"))

# Mount cleanly: 1 process, 1 port, zero latency hops!
mount(api, dashboard, path="/dashboard")

🌐 Community Components & Developer Contributions: Build & Publish with pdu.from_jsx()

React and Angular achieved global adoption because developers could easily build, share, and publish thousands of open-source UI blocks to npm.

Today, the most popular design ecosystems in the world (Shadcn UI, Tailwind UI, v0.dev, Magic UI) author components in JSX & Tailwind format.

With pdu.from_jsx(), PyDataUI opens the door for any developer to author, publish, and share reusable Python UI components in their own repositories or on PyPI—with zero Node.js, zero npm, and zero build toolchains.

1. How pdu.from_jsx Works

pdu.from_jsx() takes any raw JSX / HTML snippet from Shadcn or v0.dev and compiles it directly into a callable Python component factory:

import pydataui as pdu

# Define a reusable component factory in 1 line:
MetricCard = pdu.from_jsx("""
<div className="relative overflow-hidden rounded-xl border border-border bg-card p-6 shadow-sm hover:shadow-md transition">
    <div className="flex items-center justify-between">
        <span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">{title}</span>
        <span className="rounded-full bg-emerald-500/10 px-2.5 py-0.5 text-xs font-medium text-emerald-500 border border-emerald-500/20">{badge}</span>
    </div>
    <div className="mt-3 flex items-baseline gap-2">
        <span className="text-3xl font-extrabold tracking-tight text-card-foreground">{value}</span>
        <span className="text-xs font-semibold text-emerald-500">{delta}</span>
    </div>
    <p className="mt-2 text-xs text-muted-foreground">{caption}</p>
</div>
""")

# Use it in your layout just like native components:
with pdu.grid(columns=3, gap=4):
    pdu.write(MetricCard(title="Active GPU Clusters", value="16 / 16", delta="+2 nodes", badge="Healthy", caption="SXM5 H100 Fleet"))
    pdu.write(MetricCard(title="P99 Inference Latency", value="12.4ms", delta="-1.8ms", badge="Optimal", caption="Measured over 50k reqs"))
    pdu.write(MetricCard(title="Token Throughput", value="8.4k t/s", delta="+14.2%", badge="Streaming", caption="Real-time telemetry"))

2. Interactive Callbacks: Binding JSX to Python Actions

React-style onClick, onChange, and onSubmit attributes bind seamlessly to Python functions and @state.action methods:

s = pdu.state(counter=0)

@s.action
def increment():
    s.counter += 1

InteractiveCounter = pdu.from_jsx("""
<div className="flex items-center gap-4 p-4 border rounded-lg bg-card">
    <span className="text-lg font-bold">Count: {count}</span>
    <button onClick={on_click} className="px-4 py-2 bg-primary text-primary-foreground rounded-md text-sm font-medium">
        Increment +1
    </button>
</div>
""")

pdu.write(InteractiveCounter(count=s.counter, on_click=increment))

3. Build & Publish Components in Your Own Repository

You can create your own open-source component library, publish it to PyPI, and share it on GitHub:

  1. Create your package repository (e.g. pydataui-shadcn-blocks).
  2. Define your components in Python using pdu.from_jsx() or native Component classes.
  3. Publish to PyPI via twine:
    pip install pydataui-shadcn-blocks
    
  4. Use in any PyDataUI app:
    from pydataui_shadcn_blocks import SpotlightCard, PricingTable
    pdu.write(SpotlightCard(title="Autonomous AI Agent", category="Ops"))
    

4. Join the Community Showcase & Registry

Did you build a cool component library, dashboard template, or AI agent UI with PyDataUI?

  • Publish on your GitHub: Tag it with #pydataui and #pydataui-components.
  • Submit a PR: Open a PR to add your repository to the official Community Components & JSX Guide and get featured on the documentation site!

📦 Secondary / Optional Surfaces (TUI, Desktop & Mobile)

PyDataUI focuses first on being the cleanest embedded Streamlit-like UI layer inside FastAPI. Whenever you also need extra delivery targets without switching frameworks, the same component tree supports optional secondary surfaces:

  • 📟 Terminal UI (TUI): Run interactive Rich/ASCII dashboards (pdu.run_tui() / pydataui tui app.py --once) directly over SSH or in headless GPU clusters without opening web ports.
  • 💻 Desktop Apps (Tauri / pywebview): Package into a standalone ~15 MB desktop .app or .exe (pdu.run(desktop=True)) with zero Electron bloat.
  • 📱 Mobile Apps & PWA (Capacitor / iOS / Android): Wrap as PWA or native mobile apps when needed (Documentation).

🤝 Community & Support

Licensed under the MIT License.

Metadata

Release files for pydataui 1.9.9

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pydataui 1.9.9
File Size Uploaded Provenance Actions
pydataui-1.9.9.tar.gz 545.5 kB Without provenance Details for pydataui-1.9.9.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pydataui 1.9.9
File Interpreter ABI Platform Actions
pydataui-1.9.9-py3-none-any.whl Python 3 none any Details for pydataui-1.9.9-py3-none-any.whl

Total release size: 986.5 kB

Release files / pydataui-1.9.9.tar.gz

Download URL pydataui-1.9.9.tar.gz
Size 545.5 kB
Tags Source
SHA-256 checksum
How to use checksums
8a790a68bbae3c34eec132b29e7153f44f8a9edf0090d72d20463be227c62e53
BLAKE2b-256 checksum
How to use checksums
00280efd1e2e3a18968888e7de61e8c082bcb9a7b4bcc4ef1ffc188b2393f665
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.9

Release files / pydataui-1.9.9-py3-none-any.whl

Download URL pydataui-1.9.9-py3-none-any.whl
Size 440.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a6c51f588f4bdd0ed30720db1b250c8e977b2f4f850e5694dfc36e7400fee31f
BLAKE2b-256 checksum
How to use checksums
b6204f5ceaccc7184820a2f604a69f4ad09b85b5f59e2dd45047758b27a07495
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.9

Security for pydataui 1.9.9

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.9.9 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page