|

How to Design Python-First Interactive Dashboards with Prefab Reactive UI Components and Static HTML Export

In this tutorial, we construct a Prefab software that demonstrates how to create interactive dashboards completely in Python. We use Prefab’s component-based Python interface to design a elegant operations dashboard with reactive state, charts, tables, filters, varieties, tabs, alerts, metrics, and client-side actions. We generate lifelike pipeline monitoring knowledge, join it to stay UI controls, and export the ultimate app as a static HTML dashboard that we are able to preview instantly inside Google Colab. Through this workflow, we learn the way Prefab lets us transfer from Python knowledge logic to a contemporary React-powered consumer interface with out having to write frontend code manually.

Installing Prefab in Colab

import os
import sys
import base64
import subprocess
from pathlib import Path
from IPython.show import HTML, show, FileLink
PREFAB_VERSION = "0.20.2"
APP_PATH = Path("/content material/prefab_advanced_tutorial_app.py")
HTML_PATH = Path("/content material/prefab_advanced_dashboard.html")
subprocess.check_call([
   sys.executable,
   "-m",
   "pip",
   "install",
   "-q",
   f"prefab-ui=={PREFAB_VERSION}",
])
APP_CODE = ""

We arrange the Colab surroundings by importing the required Python utilities and defining the Prefab model, app path, and HTML export path. We set up the pinned prefab-ui package deal in order that the tutorial runs persistently with out version-related points. We additionally initialize an empty APP_CODE string, which we use to construct the whole Prefab software step-by-step.

Generating Synthetic Operations Data

import random
from collections import Counter, defaultdict
from datetime import date, timedelta
from prefab_ui.actions import AppendState, OpenHyperlink, PopState, SetState, ShowToast, ToggleState
from prefab_ui.app import PrefabApp
from prefab_ui.elements import (
   Alert, AlertDescription, AlertTitle, Badge, Button, Card, CardContent material,
   CardDescription, CardFooter, CardHeader, CardTitle, Code, Column,
   DataTable, DataTableColumn, Form, Grid, H2, Input, Markdown, Mermaid,
   Metric, Muted, Progress, Ring, Row, Slider, Small, Switch, Tab, Tabs,
   Text
)
from prefab_ui.elements.charts import (
   BarChart, ChartSeries, LineChart, PieChart, RadarChart, ScatterChart,
   Sparkline
)
from prefab_ui.elements.control_flow import Else, ForEach, If
from prefab_ui.rx import EVENT, STATE
random.seed(42)
TODAY = date.at present()
DATES = [TODAY - timedelta(days=29 - i) for i in range(30)]
REGIONS = ["All", "APAC", "EMEA", "NA", "LATAM"]
PIPELINES = [
   "Customer 360 ETL",
   "Invoice OCR",
   "LLM Triage",
   "Risk Scoring",
   "Forecast Sync",
   "Warehouse Load",
]
OWNERS = ["Data Platform", "AI Apps", "Revenue Ops", "Risk Engineering"]
STATES = ["Completed", "Completed", "Completed", "Completed", "Late", "Failed"]
PRIORITIES = ["P0", "P1", "P2", "P3"]
runs = []
daily_region_rows = []
for d in DATES:
   for area in REGIONS[1:]:
       region_bias = {
           "APAC": 0.96,
           "EMEA": 0.94,
           "NA": 0.97,
           "LATAM": 0.91,
       }[region]
       quantity = random.randint(32, 78)
       failures = 0
       late = 0
       total_cost = 0.0
       total_latency = 0.0
       total_revenue = 0.0
       for i in vary(quantity):
           pipeline = random.selection(PIPELINES)
           proprietor = random.selection(OWNERS)
           state = random.selections(
               STATES,
               weights=[
                   region_bias * 10,
                   6,
                   4,
                   3,
                   1.2,
                   max(0.2, (1 - region_bias) * 16),
               ],
               okay=1,
           )[0]
           length = max(
               12,
               int(
                   random.gauss(95, 35)
                   + (20 if state == "Late" else 0)
                   + (45 if state == "Failed" else 0)
               ),
           )
           price = spherical(max(0.09, random.lognormvariate(-1.15, 0.55) + length / 1800), 2)
           income = spherical(random.uniform(1.2, 8.5) * (1.3 if state == "Completed" else 0.6), 2)
           precedence = random.selections(PRIORITIES, weights=[1, 3, 7, 10], okay=1)[0]
           if state == "Failed":
               failures += 1
           if state == "Late":
               late += 1
           total_cost += price
           total_latency += length
           total_revenue += income
           if d >= TODAY - timedelta(days=10) and (state in {"Failed", "Late"} or random.random() < 0.05):
               runs.append({
                   "run_id": f"{d.strftime('%mpercentd')}-{area[:2]}-{len(runs)+1:04d}",
                   "date": d.strftime("%Y-%m-%d"),
                   "pipeline": pipeline,
                   "proprietor": proprietor,
                   "area": area,
                   "state": state,
                   "precedence": precedence,
                   "duration_s": length,
                   "cost_usd": price,
                   "revenue_k": income,
                   "sla_gap": spherical(max(0, length - 120) / 60, 1),
               })
       daily_region_rows.append({
           "date": d.strftime("%b %d"),
           "area": area,
           "runs": quantity,
           "failures": failures,
           "late": late,
           "success_rate": spherical(100 * (quantity - failures - late * 0.35) / quantity, 1),
           "avg_latency": spherical(total_latency / quantity, 1),
           "cost_usd": spherical(total_cost, 2),
           "revenue_k": spherical(total_revenue, 1),
       })
runs = sorted(
   runs,
   key=lambda r: (r["priority"], r["state"] != "Failed", -r["duration_s"])
)[:80]
def aggregate_daily(rows):
   by_date = defaultdict(lambda: {
       "date": "",
       "runs": 0,
       "failures": 0,
       "late": 0,
       "cost_usd": 0.0,
       "revenue_k": 0.0,
       "latency_weighted": 0.0,
   })
   for r in rows:
       bucket = by_date[r["date"]]
       bucket["date"] = r["date"]
       bucket["runs"] += r["runs"]
       bucket["failures"] += r["failures"]
       bucket["late"] += r["late"]
       bucket["cost_usd"] += r["cost_usd"]
       bucket["revenue_k"] += r["revenue_k"]
       bucket["latency_weighted"] += r["avg_latency"] * r["runs"]
   out = []
   for d in [x.strftime("%b %d") for x in DATES]:
       b = by_date[d]
       if b["runs"]:
           b["success_rate"] = spherical(100 * (b["runs"] - b["failures"] - b["late"] * 0.35) / b["runs"], 1)
           b["avg_latency"] = spherical(b["latency_weighted"] / b["runs"], 1)
           b["cost_usd"] = spherical(b["cost_usd"], 2)
           b["revenue_k"] = spherical(b["revenue_k"], 1)
           del b["latency_weighted"]
           out.append(dict(b))
   return out
def aggregate_regions(rows):
   by_region = defaultdict(lambda: {
       "area": "",
       "runs": 0,
       "failures": 0,
       "late": 0,
       "cost_usd": 0.0,
       "revenue_k": 0.0,
       "latency_weighted": 0.0,
   })
   for r in rows:
       b = by_region[r["region"]]
       b["region"] = r["region"]
       b["runs"] += r["runs"]
       b["failures"] += r["failures"]
       b["late"] += r["late"]
       b["cost_usd"] += r["cost_usd"]
       b["revenue_k"] += r["revenue_k"]
       b["latency_weighted"] += r["avg_latency"] * r["runs"]
   out = []
   for area in REGIONS[1:]:
       b = by_region[region]
       b["success_rate"] = spherical(100 * (b["runs"] - b["failures"] - b["late"] * 0.35) / b["runs"], 1)
       b["avg_latency"] = spherical(b["latency_weighted"] / b["runs"], 1)
       b["cost_usd"] = spherical(b["cost_usd"], 2)
       b["revenue_k"] = spherical(b["revenue_k"], 1)
       b["roi"] = spherical(b["revenue_k"] / max(1, b["cost_usd"]), 1)
       del b["latency_weighted"]
       out.append(dict(b))
   return out
def make_status_rows(table_rows):
   counts = Counter(r["state"] for r in table_rows)
   return [{"state": k, "count": v} for k, v in counts.items()]
def make_pipeline_rows(table_rows):
   counts = Counter(r["pipeline"] for r in table_rows)
   return [{"pipeline": k, "count": v} for k, v in counts.most_common()]
def make_kpis(area, daily_rows, table_rows):
   runs_count = sum(r["runs"] for r in daily_rows)
   failures = sum(r["failures"] for r in daily_rows)
   late = sum(r["late"] for r in daily_rows)
   price = sum(r["cost_usd"] for r in daily_rows)
   income = sum(r["revenue_k"] for r in daily_rows)
   return {
       "area": area,
       "runs": runs_count,
       "success_rate": spherical(100 * (runs_count - failures - late * 0.35) / max(1, runs_count), 1),
       "avg_latency": spherical(sum(r["avg_latency"] * r["runs"] for r in daily_rows) / max(1, runs_count), 1),
       "cost_usd": spherical(price, 2),
       "revenue_k": spherical(income, 1),
       "roi": spherical(income / max(1, price), 1),
       "open_issues": len(table_rows),
       "p0p1": sum(1 for r in table_rows if r["priority"] in {"P0", "P1"}),
       "failure_rate": spherical(100 * failures / max(1, runs_count), 2),
       "spark": [r["success_rate"] for r in daily_rows[-14:]],
   }
DAILY_BY_REGION = {"All": aggregate_daily(daily_region_rows)}
REGION_ROWS = aggregate_regions(daily_region_rows)
for area in REGIONS[1:]:
   DAILY_BY_REGION[region] = [r for r in daily_region_rows if r["region"] == area]
RUNS_BY_REGION = {
   area: [r for r in runs if region == "All" or r["region"] == area]
   for area in REGIONS
}
STATUS_BY_REGION = {
   area: make_status_rows(RUNS_BY_REGION[region])
   for area in REGIONS
}
PIPELINE_BY_REGION = {
   area: make_pipeline_rows(RUNS_BY_REGION[region])
   for area in REGIONS
}
KPI_BY_REGION = {
   area: make_kpis(area, DAILY_BY_REGION[region], RUNS_BY_REGION[region])
   for area in REGIONS
}
WATCHLIST = sorted(
   runs,
   key=lambda r: (r["priority"], r["state"] != "Failed", -r["sla_gap"])
)[:8]
SCATTER_ROWS = [
   {
       "region": r["region"],
       "success_rate": r["success_rate"],
       "cost_usd": r["cost_usd"],
       "avg_latency": r["avg_latency"],
   }
   for r in REGION_ROWS
]
RADAR_ROWS = [
   {"metric": "Success", **{r["region"]: r["success_rate"] for r in REGION_ROWS}},
   {"metric": "ROI", **{r["region"]: min(100, r["roi"] * 8) for r in REGION_ROWS}},
   {"metric": "Latency", **{r["region"]: max(0, 100 - r["avg_latency"] / 2) for r in REGION_ROWS}},
   {"metric": "Cost", **{r["region"]: max(0, 100 - r["cost_usd"] / 20) for r in REGION_ROWS}},
]
REGION_ACTIONS = {
   area: [
       SetState("selected_region", region),
       SetState("line_rows", DAILY_BY_REGION[region]),
       SetState("table_rows", RUNS_BY_REGION[region]),
       SetState("status_rows", STATUS_BY_REGION[region]),
       SetState("pipeline_rows", PIPELINE_BY_REGION[region]),
       SetState("region_kpis", KPI_BY_REGION[region]),
       SetState("selected_run", None),
       ShowToast(f"Region set to {area}", variant="data", length=1800),
   ]
   for area in REGIONS
}
'''

We add the primary imports for Prefab elements, actions, charts, management move, and reactive state dealing with. We generate lifelike artificial operations knowledge throughout areas, pipelines, homeowners, states, priorities, prices, latency, and income. We additionally create aggregation capabilities and put together datasets that energy the dashboard’s charts, metrics, filters, tables, and watchlist.

Building the Overview Tab

initial_state = {
   "selected_region": "All",
   "line_rows": DAILY_BY_REGION["All"],
   "table_rows": RUNS_BY_REGION["All"],
   "status_rows": STATUS_BY_REGION["All"],
   "pipeline_rows": PIPELINE_BY_REGION["All"],
   "region_kpis": KPI_BY_REGION["All"],
   "selected_run": None,
   "slo_target": 94,
   "operator_name": "Colab Builder",
   "notes": [{"note": "Click a run row to inspect it, then add triage notes here."}],
   "watchlist": WATCHLIST,
   "compact": False,
   "dark_mode": False,
}
with PrefabApp(
   title="Prefab Advanced Colab Tutorial",
   state=initial_state,
   css_class="max-w-7xl mx-auto p-6",
) as app:
   with Column(hole=6):
       with Row(justify="between", align="heart", hole=4):
           with Column(hole=1):
               H2("Prefab Advanced Operations Dashboard")
               Muted(
                   "An entire Colab-ready tutorial: Python DSL, reactive state, "
                   "charts, tables, varieties, conditionals, actions, Mermaid, and static export."
               )
           with Row(hole=2, align="heart"):
               Badge(f"Region: {STATE.selected_region}", variant="data")
               Badge(f"Operator: {STATE.operator_name}", variant="secondary")
               Button(
                   "Docs",
                   variant="define",
                   onClick=OpenHyperlink("https://prefab.prefect.io/docs/welcome"),
               )
       with Alert(variant="data", icon="sparkles"):
           AlertTitle("What this app demonstrates")
           AlertDescription(
               "Everything beneath consists in Python. The exported HTML runs client-side "
               "with no backend, whereas actions replace Prefab state immediately."
           )
       with Card():
           with CardHeader():
               CardTitle("Interactive controls")
               CardDescription(
                   "Use state actions to swap datasets, modify SLO targets, and personalize "
                   "the UI with out JavaScript."
               )
           with CardContent material():
               with Grid(columns={"sm": 1, "md": 2, "lg": 4}, hole=4):
                   with Column(hole=2):
                       Small("Region fast filters")
                       with Row(hole=2):
                           for area in REGIONS:
                               Button(
                                   area,
                                   measurement="sm",
                                   variant="secondary" if area != "All" else "default",
                                   onClick=REGION_ACTIONS[region],
                               )
                   with Column(hole=2):
                       Small("SLO goal")
                       Slider(
                           worth=STATE.slo_target,
                           min=80,
                           max=99,
                           step=0.5,
                           onChange=SetState("slo_target", EVENT),
                           gradient=True,
                       )
                       Muted(f"Target is {STATE.slo_target}% profitable runs")
                   with Column(hole=2):
                       Small("Operator title")
                       Input(
                           worth=STATE.operator_name,
                           placeholder="Your title",
                           on_change=SetState("operator_name", EVENT),
                       )
                   with Column(hole=2):
                       Small("Client-side toggles")
                       Switch(
                           worth=STATE.compact,
                           label="Compact assessment mode",
                           onChange=ToggleState("compact"),
                       )
                       Switch(
                           worth=STATE.dark_mode,
                           label="Dark-mode flag",
                           onChange=ToggleState("dark_mode"),
                       )
       with Tabs(worth="overview"):
           with Tab("Overview", worth="overview"):
               with Column(hole=5):
                   with Grid(columns={"sm": 1, "md": 2, "lg": 4}, hole=4):
                       Metric(
                           label="Runs",
                           worth=STATE.region_kpis.runs,
                           description=f"Selected slice: {STATE.selected_region}",
                       )
                       Metric(
                           label="Success charge",
                           worth=f"{STATE.region_kpis.success_rate}%",
                           delta=f"Target {STATE.slo_target}%",
                           development="up",
                           trendSentiment="constructive",
                       )
                       Metric(
                           label="Avg latency",
                           worth=f"{STATE.region_kpis.avg_latency}s",
                           description="Weighted 30-day common",
                       )
                       Metric(
                           label="ROI index",
                           worth=STATE.region_kpis.roi,
                           description="Revenue 1000's per USD price",
                       )
                   with Grid(columns={"sm": 1, "lg": 3}, hole=4):
                       with Card(css_class="lg:col-span-2"):
                           with CardHeader():
                               CardTitle("Reliability development")
                               CardDescription(
                                   "Line chart certain to a reactive state key. "
                                   "Region buttons substitute the entire knowledge record."
                               )
                           with CardContent material():
                               LineChart(
                                   knowledge=STATE.line_rows,
                                   xAxis="date",
                                   sequence=[
                                       ChartSeries(dataKey="success_rate", label="Success %"),
                                       ChartSeries(dataKey="avg_latency", label="Avg latency"),
                                   ],
                                   top=330,
                                   curve="easy",
                                   showDots=False,
                                   showLegend=True,
                               )
                       with Card():
                           with CardHeader():
                               CardTitle("SLO well being")
                               CardDescription(
                                   "Progress and ring elements learn stay KPI and goal state."
                               )
                           with CardContent material():
                               with Column(hole=4, align="heart"):
                                   Ring(
                                       worth=STATE.region_kpis.success_rate,
                                       goal=STATE.slo_target,
                                       label=f"{STATE.region_kpis.success_rate}%",
                                       measurement="lg",
                                       gradient=True,
                                   )
                                   Progress(
                                       worth=STATE.region_kpis.success_rate,
                                       goal=STATE.slo_target,
                                       max=100,
                                       gradient=True,
                                   )
                                   Sparkline(
                                       knowledge=STATE.region_kpis.spark,
                                       top=56,
                                       curve="easy",
                                       fill=True,
                                   )
                                   with If(STATE.region_kpis.success_rate >= STATE.slo_target):
                                       Badge("Meeting goal", variant="success")
                                   with Else():
                                       Badge("Below goal", variant="warning")
                   with Grid(columns={"sm": 1, "lg": 2}, hole=4):
                       with Card():
                           with CardHeader():
                               CardTitle("Open subject standing combine")
                           with CardContent material():
                               PieChart(
                                   knowledge=STATE.status_rows,
                                   dataKey="rely",
                                   nameKey="state",
                                   innerRadius=55,
                                   showLegend=True,
                                   top=310,
                               )
                       with Card():
                           with CardHeader():
                               CardTitle("Affected pipelines")
                           with CardContent material():
                               BarChart(
                                   knowledge=STATE.pipeline_rows,
                                   xAxis="pipeline",
                                   sequence=[ChartSeries(dataKey="count", label="Open issues")],
                                   top=310,
                                   showLegend=False,
                               )
'''

We outline the preliminary software state and begin constructing the Prefab dashboard structure. We create the dashboard header, area filters, SLO slider, operator enter, toggles, and the primary overview tab. We join reactive state to metrics, line charts, progress indicators, rings, sparklines, pie charts, and bar charts so the interface updates dynamically.

Run Explorer and Diagnostics

           with Tab("Run Explorer", worth="runs"):
               with Column(hole=4):
                   with Card():
                       with CardHeader():
                           CardTitle("Searchable sortable run desk")
                           CardDescription(
                               "Click any row. Prefab shops the row object in state and "
                               "conditionally renders the element panel."
                           )
                       with CardContent material():
                           DataTable(
                               columns=[
                                   DataTableColumn(key="run_id", header="Run ID", sortable=True),
                                   DataTableColumn(key="date", header="Date", sortable=True),
                                   DataTableColumn(key="pipeline", header="Pipeline", sortable=True),
                                   DataTableColumn(key="owner", header="Owner", sortable=True),
                                   DataTableColumn(key="region", header="Region", sortable=True),
                                   DataTableColumn(key="state", header="State", sortable=True),
                                   DataTableColumn(key="priority", header="Priority", sortable=True),
                                   DataTableColumn(
                                       key="duration_s",
                                       header="Duration",
                                       sortable=True,
                                       align="right",
                                   ),
                                   DataTableColumn(
                                       key="cost_usd",
                                       header="Cost",
                                       sortable=True,
                                       align="right",
                                   ),
                               ],
                               rows=STATE.table_rows,
                               search=True,
                               paginated=True,
                               pageSize=12,
                               onRowClick=SetState("selected_run", EVENT),
                           )
                   with If(STATE.selected_run):
                       with Card():
                           with CardHeader():
                               CardTitle(f"Selected run: {STATE.selected_run.run_id}")
                               CardDescription(
                                   f"{STATE.selected_run.pipeline} in {STATE.selected_run.area}"
                               )
                           with CardContent material():
                               with Grid(columns={"sm": 1, "md": 4}, hole=3):
                                   Metric(label="State", worth=STATE.selected_run.state)
                                   Metric(label="Priority", worth=STATE.selected_run.precedence)
                                   Metric(
                                       label="Duration",
                                       worth=f"{STATE.selected_run.duration_s}s",
                                   )
                                   Metric(
                                       label="SLA hole",
                                       worth=f"{STATE.selected_run.sla_gap} min",
                                   )
                           with CardFooter():
                               Button(
                                   "Clear choice",
                                   variant="define",
                                   onClick=SetState("selected_run", None),
                               )
           with Tab("Diagnostics", worth="diagnostics"):
               with Grid(columns={"sm": 1, "lg": 2}, hole=4):
                   with Card():
                       with CardHeader():
                           CardTitle("Regional reliability map")
                           CardDescription(
                               "Scatter chart compares price, latency, and success by area."
                           )
                       with CardContent material():
                           ScatterChart(
                               knowledge=SCATTER_ROWS,
                               xAxis="cost_usd",
                               yAxis="success_rate",
                               zAxis="avg_latency",
                               sequence=[ChartSeries(dataKey="region", label="Region")],
                               top=320,
                           )
                   with Card():
                       with CardHeader():
                           CardTitle("Balanced rating radar")
                           CardDescription(
                               "Scores are normalized for visible comparability throughout areas."
                           )
                       with CardContent material():
                           RadarChart(
                               knowledge=RADAR_ROWS,
                               axisKey="metric",
                               sequence=[
                                   ChartSeries(dataKey="APAC"),
                                   ChartSeries(dataKey="EMEA"),
                                   ChartSeries(dataKey="NA"),
                                   ChartSeries(dataKey="LATAM"),
                               ],
                               top=320,
                           )
                   with Card(css_class="lg:col-span-2"):
                       with CardHeader():
                           CardTitle("P0/P1 watchlist")
                           CardDescription(
                               "ForEach repeats a mini-card for every high-priority merchandise."
                           )
                       with CardContent material():
                           with Grid(columns={"sm": 1, "md": 2, "lg": 4}, hole=3):
                               with ForEach("watchlist") as merchandise:
                                   with Card():
                                       with CardHeader():
                                           with Row(justify="between", align="heart"):
                                               CardTitle(merchandise.run_id)
                                               Badge(merchandise.precedence, variant="damaging")
                                           CardDescription(merchandise.pipeline)
                                       with CardContent material():
                                           Text(
                                               f"{merchandise.area} · {merchandise.state} · "
                                               f"hole {merchandise.sla_gap} min"
                                           )
'''

We add the run explorer and diagnostics sections of the appliance. We construct a searchable and sortable knowledge desk the place we are able to click on a row and examine detailed run info utilizing conditional rendering. We additionally add diagnostic visualizations resembling scatter charts, radar charts, and a high-priority watchlist rendered by means of repeated Prefab playing cards.

Exporting Static HTML Dashboard

          with Tab("Triage Notes", worth="notes"):
               with Grid(columns={"sm": 1, "lg": 2}, hole=4):
                   with Card():
                       with CardHeader():
                           CardTitle("Add client-side notes")
                           CardDescription(
                               "The type appends submitted values to a state record. "
                               "No backend is required."
                           )
                       with CardContent material():
                           with Form(
                               on_submit=[
                                   AppendState("notes", EVENT),
                                   ShowToast("Note added", variant="success"),
                               ]
                           ):
                               Input(
                                   title="observe",
                                   placeholder="Example: Escalate APAC LLM Triage failures",
                                   required=True,
                               )
                               Button("Add observe", buttonType="submit")
                       with CardFooter():
                           Button(
                               "Remove newest observe",
                               variant="define",
                               onClick=PopState("notes", -1),
                           )
                   with Card():
                       with CardHeader():
                           CardTitle("Notes in state")
                           CardDescription("ForEach renders every submitted observe.")
                       with CardContent material():
                           with Column(hole=2):
                               with ForEach("notes") as observe:
                                   with Alert(variant="success", icon="examine"):
                                       AlertDescription(observe.observe)
           with Tab("Architecture", worth="structure"):
               with Column(hole=4):
                   Markdown("""
### How this tutorial maps to actual Prefab work
1. Build knowledge in Python.
2. Compose UI elements with `with` blocks.
3. Bind knowledge and labels to reactive state utilizing `STATE` / `Rx`.
4. Trigger `SetState`, `AppendState`, `ToggleState`, and `ShowToast` from UI occasions.
5. Export to HTML for static sharing, or serve domestically with `prefab serve`.
""")
                   Mermaid("""
flowchart LR
   A[Python data and business logic] --> B[Prefab component tree]
   B --> C[JSON wire protocol]
   C --> D[Bundled React renderer]
   D --> E[Interactive dashboard]
   E --> F[Client-side state actions]
   F --> B
""")
                   Code(
                       """prefab export /content material/prefab_advanced_tutorial_app.py -o /content material/prefab_advanced_dashboard.html
prefab serve /content material/prefab_advanced_tutorial_app.py --reload""",
                       language="bash",
                   )
'''
APP_PATH.write_text(APP_CODE)
print("Verifying Prefab set up...")
subprocess.check_call([sys.executable, "-m", "prefab_ui.cli", "version"])
print("nExporting Prefab app to static HTML...")
subprocess.check_call([
   sys.executable,
   "-m",
   "prefab_ui.cli",
   "export",
   str(APP_PATH),
   "-o",
   str(HTML_PATH),
])
print(f"nPython app written to: {APP_PATH}")
print(f"Static dashboard written to: {HTML_PATH}")
print("nDownload hyperlinks:")
show(FileLink(str(APP_PATH)))
show(FileLink(str(HTML_PATH)))
html_bytes = HTML_PATH.read_bytes()
encoded = base64.b64encode(html_bytes).decode("utf-8")
show(HTML(f"""
<div fashion="font-family: system-ui, -apple-system, Segoe UI, sans-serif; margin: 12px 0;">
 <h3 fashion="margin-bottom: 4px;">Prefab Advanced Dashboard Preview</h3>
 <p fashion="margin-top: 0; shade: #555;">
   Use the tabs, area buttons, SLO slider, desk row clicks, and triage-note type contained in the embedded app.
 </p>
</div>
<iframe
 src="knowledge:textual content/html;base64,{encoded}"
 width="100%"
 top="950"
 fashion="border: 1px stable #ddd; border-radius: 12px;"
></iframe>
"""))

We full the dashboard by including triage notes, structure documentation, a Mermaid flowchart, and command examples. We write the collected Prefab code right into a Python file, confirm the set up, export the app as static HTML, and generate obtain hyperlinks. We then embed the exported dashboard inside Colab utilizing an iframe so we are able to work together with the completed software instantly within the pocket book.

Conclusion

In conclusion, we efficiently created an entire Prefab-powered dashboard that mixes Python knowledge era, reactive state administration, interactive visible elements, and static HTML export right into a single sensible workflow. We labored with filters, metrics, charts, knowledge tables, conditionals, varieties, notes, and structure diagrams to perceive how Prefab can help real-world dashboards and inside instruments. By operating the mission in Google Colab, we stored the setup easy whereas nonetheless constructing a complicated software with a production-style UI.


Check out the Full Codes with Notebook. Also, be at liberty to observe us on Twitter and don’t overlook to be part of our 150k+ML SubReddit and Subscribe to our Newsletter. Wait! are you on telegram? now you can join us on telegram as well.

Need to companion with us for selling your GitHub Repo OR Hugging Face Page OR Product Release OR Webinar and many others.? Connect with us

The submit How to Design Python-First Interactive Dashboards with Prefab Reactive UI Components and Static HTML Export appeared first on MarkTechPost.

Similar Posts