Velo v0.2.1 📋 Cheat sheet ★ GitHub

No section matches your search.

⚡ Velo 0.2.1 · now with Velo Studio

Python web apps by drag & drop, or in code.

Velo builds polished web apps (dashboards, forms, data tools, chat UIs) with zero dependencies. Design visually in Velo Studio, or write a few lines of Python. Both produce the same app, and Studio apps export to clean Python whenever you want.

pip install velo-ui
velo studio            # drag & drop builder → http://localhost:7860
Velo Studio: component palette, canvas and inspector
🧩Drag & drop builder

38 components, nested layouts, a live preview next to the canvas, undo/redo and autosave.

🧮Spreadsheet-style logic

{name} in text, =price * qty for values, button actions with no code.

🐍Real Python underneath

Export any Studio app to readable Velo code, or plug your own functions into buttons.

📦Zero dependencies

Pure standard library. Installs in seconds and runs anywhere Python 3.9+ runs.

⚡Fast & smooth

Only the page function re-runs; the browser morphs the DOM, so focus and scroll are kept.

🚀Deploy anywhere

velo run --prod or velo docker. Works on Render, Railway, Fly.io, a VPS…

Installation

You need Python 3.9 or newer. Check with python --version (on some systems: python3 --version). Get Python from python.org. On Windows, tick “Add python.exe to PATH” in the installer.

Recommended: inside a virtual environment

# 1. create a project folder and a virtual environment
mkdir myapp
cd myapp
python -m venv .venv

# 2. activate it
.venv\Scripts\activate          # Windows
source .venv/bin/activate       # macOS / Linux

# 3. install Velo
pip install velo-ui

# 4. check
velo version

velo version prints the version and the author line. If it does, you're ready.

Upgrade

pip install -U velo-ui
Package name vs import name. You install velo-ui, but in Python you write import velo, and the command is velo.

Optional extras

Velo needs nothing else. If pandas is installed, ui.table and the charts accept DataFrames directly; Pillow images work with ui.image. Neither is required.

Quick start: Studio (no code)

Build a working app in five minutes without writing code.

  1. Open Studio. In a terminal, inside your project folder:
    velo studio
    Your browser opens http://localhost:7860. Studio creates app.velo.json in the folder. That file is your app.
  2. Pick a template from the welcome window (try Hello world), or start blank.
  3. Drag a component from the left panel onto the canvas, e.g. a Text input. Its Variable name is name.
  4. Drag a Title above it, click it, and in the inspector on the right type Hello {name}!.
  5. Click ◫ Split in the top bar. The real app runs on the right. Type in the input and the title changes live.
  6. Add a Button. In its inspector, under When clicked, choose Show message with text Nice to meet you, {name} 🎉.
  7. Run it like a normal app when you're done (Studio autosaves):
    velo run app.velo.json
💡 Want the Python version? Click </> Code in Studio, or run velo export app.velo.json to get an app.py.

Quick start: Python

Create app.py:

import velo

app = velo.App("Hello Velo", icon="👋")

@app.page("/")
def home(ui):
    ui.title("Hello Velo 👋", "Type your name below")
    name = ui.input("Your name", placeholder="Ada Lovelace")
    level = ui.slider("Excitement", 1, 10, 7)
    ui.text(f"Hi {name or 'there'}! " + "🎉" * level)
    if ui.button("Celebrate", icon="✨"):
        ui.toast(f"Thanks {name}!", "success")

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

Run it:

python app.py          # or: velo run app.py --open

Open http://localhost:8000. Save the file and the browser updates instantly (hot reload) without losing what you typed.

The mental model: your page function runs top to bottom. Every widget returns its current value. When a visitor changes something, Velo re-runs the function and updates only what changed on the screen.

Scaffold a starter project with velo new myapp.

The Studio screen

Velo Studio split view with live preview
AreaWhat it does
Top barApp title · undo/redo · views Design, Split, Preview, Code · desktop/mobile frame · problems badge · save status · ✨ Templates · Export menu · dark mode.
Left: ComponentsThe palette, grouped (Text, Inputs, Actions, Data, Feedback, Layout). Search with /. Drag onto the canvas or click to add.
Left: PagesAdd, rename, reorder, duplicate and delete pages; set each page's URL path and icon.
Left: App & DataTitle, icon, accent colour, theme, wide layout, state variables, the Python hooks file, and a formula cheat sheet.
Centre: canvasYour page as it will look: a Sidebar zone on the left and the page body. Blue lines show where a drop will land.
Right: inspectorProperties of the selected component, its actions (buttons), Show only if, and any problems.

Command options: velo studio [file.velo.json] [-t template] [--port 7860] [--host 127.0.0.1] [--no-open] [--force]. The live preview runs on port + 1 (7861 by default).

Building a page

Adding components

  • Drag a tile from the palette and drop it anywhere: between items, inside a card, a column, a tab, or the sidebar.
  • Click a tile to add it right after the selected component (or inside it, if the selection is a container). This also works on touch screens.

Selecting and editing

  • Click a component to select it. A blue chip appears with ↑ ↓ (move), ⧉ (duplicate) and ✕ (delete).
  • Double-click to jump straight into its first property.
  • The inspector shows all properties. Changes appear instantly on the canvas and in the preview.
  • Drag a component that's already on the canvas to move it, even into another container.

Layout components (containers)

ContainerUse it forTip
ColumnsSide-by-side contentWidths 1,1 = two equal columns, 2,1 = wide + narrow, 1,1,1 = three.
CardA panel with a titleGreat for forms and KPI groups.
RowItems in a line (buttons, badges)Wraps on small screens.
TabsSwitchable sectionsOne tab label per line. Click tab labels on the canvas to edit each tab.
ExpanderCollapsible “more details”Set Open by default if needed.
GroupInvisible wrapperCombine with Show if to hide/show many things at once.

Every page also has a Sidebar: drop filters and settings there.

💡 Shrinking columns or tabs never deletes content. Extra items move into the last column or tab.

Variables & state

Velo Studio apps work like a spreadsheet: things have names, and anything can refer to them.

Input variables

Every input (text, number, slider, dropdown, checkbox, upload, chat…) has a Variable name, e.g. name, age, city, file. Its value is whatever the visitor entered. Rules: start with a letter; letters, digits and _ only; each name used once.

State variables

Values the app remembers for each visitor: a counter, a list of form entries, a “logged in” flag. Add them in App & Data → State variables with a starting value:

Starting valueTypeExample use
0numberclick counter, score
""texta status message
[]listform entries, a to-do list (use with Add to list)
falseyes/noshow/hide something with Flip yes/no
{"a": 1}dictionarysettings
💡 Typing a new name in a button action's Variable field creates the state variable for you.

Renaming

Rename a variable in the inspector, and every {reference}, formula and action that uses it is updated automatically.

Formulas

Formulas are the only “code” you ever write in Studio. They use Python syntax and run in a safe sandbox.

You writeWhereResult
Hello {name}!any text propertyA template: {…} is replaced by the value.
Total: {price * qty:,.2f}textCompute + format → Total: 1,234.50
=count + 1any propertyStarts with =: the whole value is computed.
agree and '@' in emailShow if / Only ifTrue or false.
{{ and }}textLiteral { and }.

What you can use

  • Arithmetic + - * / // % **, comparisons == != < <= > >=, and or not, in
  • Conditions: 'Pass' if score >= 50 else 'Fail'
  • Lists, dicts, indexing and slicing: rows[0]['name'], text[:20]
  • List comprehensions: [r for r in rows if r['score'] > 90]
  • Text methods: name.upper(), .lower() .title() .strip() .split() .replace() .startswith()…
  • Dict methods: .get() .keys() .values() .items(); dates: .year .month .day .strftime()

Functions

FunctionExampleWhat it does
len sum min max round abs=round(sum(xs) / len(xs), 1)The usual maths
sorted range list dict set any all zip enumerate reversed=sorted(names)Collections
str int float bool=int(age) + 1Convert types
csv(text_or_file)=csv(file)Rows (list of dicts) from CSV text or an uploaded file; numbers converted
col(rows, name)=sum(col(rows, 'sales'))All values of one column
where(rows, column, value)=where(rows, 'city', city)Filter rows. value may be a list; empty = all rows
group(rows, by, value, agg)=group(rows, 'month', 'sales')Group & aggregate. agg: 'sum' (default), 'mean', 'count', 'min', 'max'
columns(rows)=columns(csv(file))Column names (perfect for dropdown options)
mean(xs)=mean(col(rows, 'score'))Average
fmt(value, spec)=fmt(total, ',.2f')Format a number as text
to_csv(rows)=to_csv(entries)Rows back to CSV text
today() now()Today is {today()}Current date / date-time
sqrt pi=round(pi * r ** 2, 2)Maths constants/functions
🔒 Safe by design: formulas can't import modules, open files, reach the network, or access anything starting with _. They're written by the app author; visitors only ever enter data, never code.

Button actions

Select a Button → ⚡ When clicked → + Add action. Actions run top to bottom. Each one can have an Only if condition.

ActionFieldsExample
Set variablevariable, valuecount ← =count + 1
Flip yes/novariableshow_help
Add to listvariable, valueentries ← ={'name': name, 'email': email}
Clear variablevariableentries becomes [], numbers 0, text ""
Reset inputsnames (blank = all)name email
Show messagetext, styleSaved, {name}! · info / success / warning / error
Go to pagepage/thanks
Run Python hookfunction namesend_email (see Python hooks)

Values: =… is computed; 5 becomes a number; true/false become yes/no; anything else is text (with {templates}).

Example: a validated sign-up button

#ActionOnly if
1Show message “Please enter a valid email” (warning)'@' not in email
2Add to list entries ← ={'name': name, 'email': email}'@' in email
3Show message “Welcome, {name}!” (success)'@' in email
4Reset inputs name email'@' in email

Show if (visibility)

Any component has 👁 Visibility → Show only if. Write a condition; the component appears only when it's true. Leave empty to always show.

ConditionMeaning
agreethe “agree” checkbox is ticked
len(entries) > 0the list has at least one item
plan == 'Pro'a dropdown/segmented choice
filea file has been uploaded
age >= 18 and country == 'Pakistan'combine with and / or
💡 Put several components in a Group and give the group the condition to hide/show them together.

Pages & navigation

  • Pages tab → + Add page. Set its Title, Path (e.g. /about) and Icon.
  • With two or more pages, the app gets a navigation menu automatically (sidebar on desktop, ☰ menu on mobile).
  • Buttons can jump between pages with the Go to page action.
  • Input values are kept per visitor across pages, so a value typed on page 1 can be shown on page 2 with {name}.

Data, CSV & charts

Table and Chart have a Data property that accepts either:

  • CSV text pasted directly (first line = column names), or
  • a formula starting with =, such as =entries (a state list), =csv(file) (an upload), =group(csv(file), 'region', 'sales').

Upload a CSV and chart it

  1. Drop a File upload (variable file, accept .csv) into the sidebar.
  2. Drop a Dropdown named x_col with options =columns(csv(file)), and another named y_col with the same options.
  3. Drop a Chart: Data =csv(file), X column {x_col}, Y columns {y_col}.
  4. Drop a Table: Data =csv(file). Give the chart and table Show if file.

The Data explorer template is exactly this, with a sample dataset.

Charts

Types: line, area, bar, pie (donut). X column is the label column; Y columns can be several, comma-separated (sales, costs). Leave them empty and Velo picks sensible columns. Stacked stacks bars/areas.

Download

The Download component's content can be text with templates, or a formula. A list of rows (e.g. =entries) is turned into CSV automatically.

Chat component

Drop a Chat component. It shows a greeting, the conversation, and an input box. Its reply comes from either:

  • Reply template: text where {message} is what the visitor typed, e.g. You said **{message}** ({len(message.split())} words). Markdown works.
  • Python hook: the name of a function in your hooks file that returns the reply. Connect any AI model this way.

The conversation is stored in the chat's variable (default chat) as a list of {'role': ..., 'content': ...}; =len(chat) counts messages. Reset inputs with the chat's name clears it.

Python hooks

Hooks let a Studio app call your own Python, with any library you like (send email, query a database, call an AI model…).

  1. In App & Data → Python hooks, set Hooks file to hooks.py.
  2. Create hooks.py next to your app.velo.json.
  3. Use a function from a button (Run Python hook) or a chat component (hook property).
# hooks.py
def send_email(ctx):                 # button action
    to = ctx["email"]                # read any variable (input or state)
    # ... smtplib / an email API here ...
    ctx.set("sent", True)            # change a state variable or an input
    ctx.toast(f"Email sent to {to} ✉️", "success")

def answer(ctx, message):            # chat hook: return the reply (markdown allowed)
    if "price" in message.lower():
        return "It's **free**!"
    return f"You said: {message}"
Context memberWhat it gives you
ctx["name"] / ctx.get("name", default)Read an input or state variable
ctx.valuesDict of all input values
ctx.stateThis visitor's state (dict-like)
ctx.set(name, value)Set a state variable or an input
ctx.toast(text, kind)Show a message (info, success, warning, error)
ctx.navigate(path)Go to another page
ctx.uiThe full Velo ui object for anything else

Studio reloads the preview automatically when hooks.py changes. You can also register functions in Python with @app.action("name"); see Loading Studio apps.

Templates

Open ✨ Templates in Studio, or start from one on the command line: velo studio app.velo.json -t dashboard.

TemplateName for -tShows you
⬜ BlankblankAn empty page
👋 Hello worldhelloInputs, live text, a counter button, reset
📊 DashboarddashboardSidebar filters, KPI metrics, tabs with charts, table + CSV download, two pages
📝 Form + tableformValidation with “Only if”, adding to a list, reset, export CSV, show-if card
🔎 Data explorerexplorerUpload a CSV, choose columns and chart type
💬 ChatbotchatbotChat UI with a reply template, ready for an AI hook
🧮 CalculatorcalculatorLoan maths with live formulas and a generated chart

Preview, code & export

  • ◫ Split: canvas + live app side by side. ▶ Preview: the live app alone. Edits hot-swap into the preview without losing what you typed there.
  • 🖥️ / 📱: desktop or phone-sized frame.
  • </> Code: the exact Python your app equals. Copy or download it.
  • Export menu: download app.py, download the .velo.json, import a .velo.json, or open the preview in a new tab.
velo export app.velo.json            # writes app.py next to it
velo export app.velo.json -o web.py  # choose the file name
python app.py                        # the exported app runs on its own

Exported code is ordinary Velo Python: widgets become variables, actions become small functions, templates become f-strings. It's the natural path from no-code to full code.

Saving

Studio autosaves every change to the .velo.json file (status in the top bar). Ctrl+S saves immediately. The file is plain JSON, so commit it to git like any source file.

Problems

Studio checks your app as you work: unknown variables, formula typos, duplicate names. A red/yellow badge marks the component; the top-bar ⛔ problems button lists them all and jumps to each.

Keyboard shortcuts

KeysAction
Del / BackspaceDelete selected component
Ctrl/⌘ + DDuplicate
Ctrl/⌘ + ZUndo
Ctrl/⌘ + Shift + Z or Ctrl + YRedo
Alt + ↑ / ↓Move up / down
Ctrl/⌘ + SSave now
/Search components
1 2 3 4Design · Split · Preview · Code
EscDeselect / close dialog
Double-clickEdit the component's first property

Component reference (Studio)

Every component, its type in .velo.json, and its properties. Inputs marked 🔤 are variables.

TypeNameWhat it isProperties
Text
titleTitleBig page title + subtitletext, subtitle
headerHeaderSection headingtext
subheaderSubheaderSmaller headingtext
textTextParagraphtext, muted
markdownMarkdownRich text: bold, lists, links, tablestext
captionCaptionSmall muted texttext
badgeBadgeColoured labeltext, kind (accent/success/warning/error/neutral)
linkLinkExternal linktext, url
codeCodeCode block with copy buttoncode, lang
imageImageImage from a URLsrc, caption, width
dividerDividerHorizontal line—
spaceSpacerVertical spaceheight
Feedback
alertAlertInfo / success / warning / error boxkind, title, text
metricMetricKPI number with delta arrowlabel, value, delta, inverse, help
progressProgressProgress bar (0–100)value, label
Inputs 🔤
inputText inputSingle-line textname, label, placeholder, value, itype (text/password/email/url/tel), help
textareaText areaMulti-line textname, label, placeholder, value, rows, help
numberNumberNumber boxname, label, value, min, max, step, help
sliderSliderDrag to pick a numbername, label, min, max, value, step, suffix, help
selectDropdownPick onename, label, options, value, help
radioSegmentedPick one of a few (buttons)name, label, options, value
multiselectChipsPick manyname, label, options, value
checkboxCheckboxYes / noname, label, value
toggleSwitchOn / offname, label, value
dateDateDate pickername, label
colorColourColour pickername, label, value
uploadFile uploadDrag & drop filename, label, accept
Actions
buttonButtonRuns actionslabel, kind (primary/secondary/ghost/danger), icon, full, actions
downloadDownloadDownload text/CSVlabel, content, filename
Data
tableTableSearchable, sortable, paginateddata, page_size, search
chartChartLine, area, bar, piekind, data, x, y, title, height, stacked
chatChat 🔤Conversation UIname, placeholder, greeting, reply, hook
Layout (hold other components)
columnsColumnsSide by sidewidths, gap (sm/md/lg)
cardCardPaneltitle, subtitle
rowRowHorizontal line—
tabsTabsTabbed sectionslabels
expanderExpanderCollapsiblelabel, open
containerGroupInvisible wrapper—

Every component also accepts show_if.

Python: App & pages

import velo

app = velo.App(
    "My App",            # title (browser tab + sidebar)
    icon="🚀",           # emoji favicon/logo
    theme="auto",        # "auto" | "light" | "dark"
    accent="#10b981",    # one colour themes everything
    wide=False,          # full-width layout
)

@app.page("/", title="Dashboard", icon="📊")
def dashboard(ui):
    ui.title("Dashboard")

@app.page("/settings", title="Settings", icon="⚙️")
def settings(ui):
    ui.title("Settings")

app.run()                # dev: hot reload · app.run(prod=True) for deployment

app.run(host=None, port=None, *, reload=None, prod=None, open=False). Defaults: port 8000 (or $PORT), host 127.0.0.1 in dev, 0.0.0.0 in prod. Two or more pages get automatic navigation.

Python: text & feedback

ui.title("Title", "optional subtitle")
ui.header("Section");  ui.subheader("Subsection")
ui.text("Paragraph", muted=False);  ui.caption("small note")
ui.markdown("**bold**, _italic_, `code`, [link](https://...)")   # safe markdown (alias ui.md)
ui.code("print('hi')", lang="python")
ui.json({"a": 1})
ui.badge("New", "success");  ui.link("Docs", "https://...")
ui.image("photo.png", caption="...", width=400)    # URL, path, bytes or PIL image
ui.divider();  ui.space(24)
ui.info("..."); ui.success("..."); ui.warning("..."); ui.error("...", title="Oops")
ui.alert("text", kind="info", title=None)
ui.metric("Revenue", "$12.4k", delta="+8%", help="...", inverse=False)
ui.progress(0.65, "Uploading")                     # 0.0 – 1.0
ui.toast("Saved!", "success")                      # corner notification
ui.html("<b>trusted HTML</b>")

Python: inputs

Every input returns its current value. Give it key="..." to read/write it from anywhere with ui.get / ui.set.

name  = ui.input("Name", placeholder="Ada", type="text", help=None)   # type: text|password|email|url|tel
bio   = ui.textarea("Bio", rows=4)
age   = ui.number("Age", 30, min=0, max=120, step=1)
level = ui.slider("Level", 0, 100, 50, step=5, suffix="%")
city  = ui.select("City", ["Karachi", "Lahore", "Islamabad"])   # returns the option itself (any type)
plan  = ui.radio("Plan", ["Free", "Pro", "Team"])               # segmented control (alias ui.segmented)
tags  = ui.multiselect("Tags", ["Python", "Data", "AI"])        # list
ok    = ui.checkbox("I agree");   dark = ui.toggle("Dark mode")
day   = ui.date("Start date")                                   # datetime.date or None
color = ui.color("Brand colour", "#6366f1")
f     = ui.upload("CSV file", accept=".csv", multiple=False)    # UploadedFile | list | None
if f:
    ui.text(f"{f.name} · {f.size} bytes")
    rows = f.text()                                             # decoded text · f.data is bytes

Options can be any objects. Use format=lambda o: o.name to control how they're shown. All inputs accept on_change=fn, args=(...).

Python: buttons & downloads

if ui.button("Save", icon="💾"):           # True on the run caused by the click
    save()

ui.button("Delete", kind="danger", on_click=delete, args=(item_id,))
# kind: primary | secondary | ghost | danger · full=True · disabled=True

ui.download("Export CSV", csv_text, "report.csv")           # str or bytes
ui.download("Image", png_bytes, "chart.png", mime="image/png")

Python: layout

a, b, c = ui.columns(3)                 # or ui.columns([2, 1]), gap="sm"|"md"|"lg"
a.metric("Users", 1520)                 # containers proxy every component…
with b:                                 # …or use `with`
    ui.metric("Revenue", "$12k")

with ui.card("Settings", "optional subtitle"):
    ui.toggle("Enabled")

t1, t2 = ui.tabs(["Chart", "Data"])
with t1: ui.line_chart(rows)
with t2: ui.table(rows)

with ui.expander("Advanced", open=False):
    ui.number("Retries", 3)

with ui.sidebar:                        # the left sidebar
    region = ui.select("Region", ["North", "South"])

with ui.row():                          # horizontal group (buttons, badges)
    ui.button("Yes"); ui.button("No", kind="secondary")

with ui.container(): ...                # plain grouping

Python: tables & charts

Data can be a pandas DataFrame, a list of dicts, a dict of lists, or a list of lists.

rows = [{"month": "Jan", "sales": 120, "costs": 80},
        {"month": "Feb", "sales": 150, "costs": 90}]

ui.table(rows, page_size=10, search=True)          # sortable, searchable (alias ui.dataframe)
ui.line_chart(rows, x="month", y=["sales", "costs"])
ui.area_chart(rows, x="month", y="sales", title="Sales")
ui.bar_chart(rows, x="month", y=["sales", "costs"], stacked=True)
ui.pie_chart({"k": ["A", "B"], "v": [60, 40]})
ui.chart(rows, x="month", y="sales", kind="bar", height=300)    # generic

Data helpers used by Studio are available in Python too:

from velo.helpers import csv, col, where, group, columns, mean, to_csv, fmt

data = csv(open("sales.csv").read())        # or csv(uploaded_file)
north = where(data, "region", "North")
ui.bar_chart(group(north, "month", "sales"), x="month", y="sales")

Python: state, keys & callbacks

@app.page("/")
def counter(ui):
    ui.init(count=0, todos=[])          # defaults, set once per visitor

    def add(step):
        ui.state.count += step          # callbacks run BEFORE the re-render

    with ui.row():
        ui.button("−", on_click=add, args=(-1,), kind="secondary")
        ui.button("+", on_click=add, args=(1,))
    ui.metric("Count", ui.state.count)
CallPurpose
ui.init(**defaults)Set state defaults once per session
ui.state.x / ui.state["x"]Per-visitor memory (dict-like). Use ["items"] form for names like items, keys
ui.get(key, default) / ui.set(key, value)Read/write any widget that has key=
ui.reset(*keys)Reset widgets to defaults (no keys = all)
ui.navigate("/page")Go to another page (also inside callbacks)
ui.rerun()Run the page again immediately
ui.session_idThis visitor's session id

Python: chat apps

@app.page("/")
def chat(ui):
    ui.init(msgs=[])
    for role, text in ui.state.msgs:
        ui.chat_message(role, text)               # role: "user" | "assistant"
    if q := ui.chat_input("Ask me anything…"):
        reply = my_llm(q)                         # any AI model / logic
        ui.state.msgs += [("user", q), ("assistant", reply)]
        ui.rerun()

Python: caching & live updates

@velo.cache(ttl=300, maxsize=256)    # shared across visitors and re-runs
def load_data(path):
    return expensive_read(path)

ui.autorefresh(5)                    # live dashboard: re-run every 5 s while open
app.push()                           # from a background thread: refresh all browsers
app.push(ui.session_id)              # …or just one visitor

Python: loading Studio apps

Run a .velo.json from Python and extend it with code.

import velo

app = velo.load("app.velo.json")        # a normal velo.App

@app.action("send_email")               # usable by "Run Python hook" buttons & chat hooks
def send_email(ctx):
    ctx.toast(f"Sent to {ctx['email']}", "success")

@app.page("/admin", title="Admin", icon="🔐")   # hand-written pages next to Studio pages
def admin(ui):
    ui.title("Admin")

app.run()
FunctionReturns
velo.load(path_or_dict)A runnable app built from a spec
velo.spec.validate(spec)List of problems {id, level, msg}
velo.codegen.to_python(spec)Equivalent Python source code
velo.ContextThe object hooks receive (ctx)

Recipes

1 · Student result calculator (Studio)

  1. Three Number inputs: maths, science, english (max 100).
  2. A Metric “Total” with value =maths + science + english.
  3. A Metric “Percentage” with value {(maths + science + english) / 3:.1f}%.
  4. A Badge with text {'Pass' if (maths + science + english) / 3 >= 50 else 'Fail'}.
  5. An Alert (success) “Excellent work!” with Show if (maths + science + english) / 3 >= 80.

2 · Collect entries and export CSV (Studio)

State entries = [] · inputs name, email · button with Add to list entries ← ={'name': name, 'email': email} then Reset inputs · a Table with data =entries · a Download with content =entries, filename entries.csv. Or just start from the Form + table template.

3 · CSV dashboard (Python)

import velo
from velo.helpers import csv, where, group, col

app = velo.App("Sales", icon="📊", wide=True)

@app.page("/")
def home(ui):
    with ui.sidebar:
        f = ui.upload("Sales CSV", accept=".csv")
    if not f:
        ui.info("Upload a CSV with month, region and sales columns.")
        return
    rows = csv(f)
    with ui.sidebar:
        region = ui.multiselect("Region", sorted({r["region"] for r in rows}))
    rows = where(rows, "region", region)
    a, b = ui.columns(2)
    a.metric("Total sales", f"{sum(col(rows, 'sales')):,}")
    b.metric("Rows", len(rows))
    ui.bar_chart(group(rows, "month", "sales"), x="month", y="sales")
    ui.table(rows)

app.run()

4 · AI chatbot (Studio + hook)

Use the Chatbot template, set Hooks file to hooks.py and the chat's hook to answer:

# hooks.py — works with any AI provider's Python library
def answer(ctx, message):
    history = ctx["chat"]                 # [{'role': 'user', 'content': ...}, ...]
    return call_your_model(history)       # return the reply text

5 · Multi-page app with navigation buttons (Python)

@app.page("/", title="Form", icon="📝")
def form(ui):
    ui.input("Name", key="name")
    ui.button("Continue →", on_click=lambda: ui.navigate("/summary"))

@app.page("/summary", title="Summary", icon="✅")
def summary(ui):
    ui.title(f"Thanks, {ui.get('name') or 'friend'}!")

CLI reference

CommandWhat it does
velo studio [file] [-t TEMPLATE] [--force] [--port N] [--host H] [--no-open]Open the drag & drop builder (default file app.velo.json, created if missing)
velo run app.py · velo run app.velo.jsonRun an app with hot reload
  --port N --host H --open --prod --no-reloadRun options. --prod: 0.0.0.0, no reload, no tracebacks, gzip
velo export [file.velo.json] [-o app.py] [--force]Turn a Studio app into Python
velo new NAMEScaffold a starter project
velo docker [app.py|app.velo.json] [--port N]Write a Dockerfile (and vendor Velo)
velo versionPrint version and author
python -m velo ...Same commands, if velo isn't on PATH

Environment variables: PORT, VELO_HOST, VELO_ACCESS_LOG=1 (log requests).

Deploy

Any server or VPS

pip install velo-ui
velo run app.py --prod --port 8000          # or: velo run app.velo.json --prod

Docker

velo docker app.py                          # writes Dockerfile + .dockerignore
docker build -t myapp .
docker run -p 8000:8000 myapp

Render, Railway, Fly.io, Koyeb, Cloud Run, Heroku

  1. Put your app in a GitHub repo with a requirements.txt containing velo-ui (plus anything your hooks use).
  2. Start command: velo run app.py --prod (or app.velo.json). Velo reads $PORT automatically.
  3. Health check path: /health.
⚠️ Notes: sessions live in memory, so run one process per app (or use sticky sessions). Uploads travel as base64 JSON, practical up to about 25 MB. Behind nginx, disable buffering for /api/stream.

Publishing these docs

This page is a single docs/index.html. On GitHub: Settings → Pages → Deploy from a branch → main / /docs, and it goes live at https://rafay183.github.io/velo/. It also works on Netlify, Vercel, or any static host.

The .velo.json format

{
  "velo": 1,
  "generator": "Velo Studio — by Muhammad Rafay Shaikh (Pakistan)",
  "app":   {"title": "Registration", "icon": "📝", "accent": "#8b5cf6", "theme": "auto", "wide": false},
  "state": {"entries": []},
  "hooks": "hooks.py",
  "pages": [{
    "path": "/", "title": "Register", "icon": "📝",
    "sidebar": [],
    "body": [
      {"id": "n1", "type": "input", "props": {"name": "email", "label": "Email"}},
      {"id": "n2", "type": "button", "props": {"label": "Join", "actions": [
        {"do": "append", "var": "entries", "value": "={'email': email}", "if": "'@' in email"}]}},
      {"id": "n3", "type": "card", "props": {"title": "People"}, "show_if": "len(entries) > 0",
       "slots": [[{"id": "n4", "type": "table", "props": {"data": "=entries"}}]]}
    ]
  }]
}
  • Nodes have id, type, props, optional show_if, and for containers slots (a list of lists: one per column/tab).
  • Actions use do: set toggle append clear reset toast navigate call, plus fields var value text kind to fn vars if.
  • Missing properties take their defaults, so hand-written specs can stay short.

How Velo works

  1. The browser opens one live stream (Server-Sent Events) and sends small JSON events (set, click, submit).
  2. The server applies the event to that visitor's session, runs callbacks, then re-runs only the page function, producing a compact component tree.
  3. The browser morphs the page to match. Unchanged elements aren't touched, so focus, cursor, scroll, open tabs and table sorting survive.
  4. When you save a file, Velo re-executes it, swaps the new page functions into the running app and refreshes browsers. Sessions stay where they were.
  5. Studio apps are interpreted from the JSON at runtime by the same engine, so a Studio app and its exported Python behave the same.

Customise the look with App(accent=..., theme=..., wide=...) or override CSS variables (--accent, --r, --font…) via ui.html("<style>...</style>").

Cheat sheets

Print this section (Ctrl+P) for a handy reference.

🖥️ Terminal

pip install velo-ui        # install
pip install -U velo-ui     # upgrade
velo studio                # builder
velo studio x.velo.json -t form
velo run app.velo.json     # run Studio app
velo run app.py --open     # run Python app
velo export app.velo.json  # → app.py
velo new myapp             # scaffold
velo run app.py --prod     # production
velo docker app.py         # Dockerfile
velo version

🧮 Studio formulas

Hello {name}
show a variable in text
{price * qty:,.2f}
compute + format
=count + 1
whole value computed
='Yes' if agree else 'No'
condition
=csv(file)
rows from upload
=where(rows, 'city', city)
filter
=group(rows, 'month', 'sales')
group & sum
=sum(col(rows, 'sales'))
column total
=columns(rows)
column names
=[r for r in rows if r['x'] > 5]
comprehension
len(entries) > 0
Show if / Only if

⚡ Button actions

Set variable
count ← =count + 1
Flip yes/no
show_help
Add to list
entries ← ={'name': name}
Clear variable
entries → []
Reset inputs
name email (blank = all)
Show message
Saved {name}! · success
Go to page
/thanks
Run Python hook
def fn(ctx): … in hooks.py
Only if
any condition per action

🐍 Python basics

import velo
app = velo.App("App", icon="⚡")

@app.page("/", title="Home")
def home(ui):
    ui.title("Hi")
    x = ui.input("Name")
    if ui.button("Go"):
        ui.toast(f"Hi {x}")

app.run()

🧩 Python inputs

ui.input  ui.textarea  ui.number
ui.slider(l, min, max, value)
ui.select(l, opts)  ui.radio(l, opts)
ui.multiselect(l, opts)
ui.checkbox  ui.toggle  ui.date
ui.color  ui.upload(l, accept=".csv")
ui.button(l, on_click=fn, args=())
ui.download(l, data, "file.csv")

📐 Python layout & data

a, b = ui.columns(2)   # [2, 1]
with ui.card("T"): ...
t1, t2 = ui.tabs(["A", "B"])
with ui.expander("More"): ...
with ui.sidebar: ...
with ui.row(): ...
ui.table(rows)  ui.metric(l, v, d)
ui.line_chart(rows, x=, y=)
ui.bar_chart  ui.area_chart
ui.pie_chart  ui.chart(kind=)

🧠 Python state

ui.init(count=0, items=[])
ui.state.count += 1
ui.state["items"]          # dict-name keys
ui.get("key"); ui.set("key", v)
ui.reset("key")            # or ui.reset()
ui.navigate("/p"); ui.rerun()
@velo.cache(ttl=60)
ui.autorefresh(5); app.push()

💬 Text & feedback

ui.title(t, sub)  ui.header  ui.subheader
ui.text  ui.caption  ui.markdown
ui.code(src, lang)  ui.json(obj)
ui.badge(t, kind)  ui.link(t, url)
ui.image(src)  ui.divider()  ui.space()
ui.info  ui.success  ui.warning  ui.error
ui.progress(0.5)  ui.toast(t, kind)
ui.chat_message(role, t)
ui.chat_input("Ask…")

⌨️ Studio keys

Del
delete
Ctrl D
duplicate
Ctrl Z / Ctrl Shift Z
undo / redo
Alt ↑ ↓
move
Ctrl S
save
/
search components
1 2 3 4
Design · Split · Preview · Code
Esc
deselect

Troubleshooting & FAQ

“velo” is not recognized / command not found

Activate your virtual environment (.venv\Scripts\activate on Windows), or use python -m velo studio. On Windows, re-install Python with “Add to PATH” ticked.

“invalid choice: 'studio'”

You have an old version. Run pip install -U velo-ui and check velo version. If it still shows the old version, run pip uninstall velo-ui and install again; an old pip install -e . may be shadowing it.

Port already in use

Use another port: velo studio --port 7000 or velo run app.py --port 8080.

The Studio preview panel is blank

The preview runs on Studio's port + 1 (7861). Allow it in your firewall. In cloud editors that forward only one port, use Design view and test with velo run.

A formula shows ⚠

Hover the red badge or open ⛔ problems. Common causes: a misspelled variable, a missing quote ('text'), or = forgotten in front of a computed value.

My state variable resets

State is per visitor and lives in server memory. Restarting the server clears it. Save important data to a file or database from a Python hook.

Git or OneDrive trouble on Windows

Keep project folders (especially git repos) outside OneDrive, e.g. C:\code\myapp. Syncing can corrupt .git files.

Can I use Velo commercially?

Yes. Velo is MIT licensed.

Is Velo a Streamlit or Gradio replacement?

It fills the same role (Python data and AI apps) with zero dependencies, a built-in visual builder, multi-page navigation, client-side tabs, and DOM morphing that keeps focus and scroll.

Contributing

git clone https://github.com/rafay183/velo.git
cd velo
python -m venv .venv && .venv\Scripts\activate      # macOS/Linux: source .venv/bin/activate
pip install -e .
python tests/test_velo.py && python tests/test_studio.py
FileRole
velo/core.pyApp, sessions and every ui.* component
velo/server.pyHTTP server, live stream, hot reload
velo/spec.pyStudio component catalog, formula sandbox, .velo.json interpreter, validator
velo/codegen.pyStudio app → Python exporter
velo/studio.py · velo/static/studio.*Studio server and UI (vanilla JS, no build step)
velo/static/app.js · app.cssBrowser renderer and theme

Workflow: open an issue → branch → change + test → pull request. Releases: bump the version in pyproject.toml and velo/__init__.py, update CHANGELOG.md, merge, then publish a GitHub Release tagged v0.x.y. GitHub Actions uploads it to PyPI.

About the author

MR
Muhammad Rafay Shaikh

Creator and maintainer of Velo & Velo Studio · Pakistan 🇵🇰

github.com/rafay183 · github.com/rafay183/velo · pypi.org/project/velo-ui

Every app built with Velo carries a small credit: “Built with Velo” in the sidebar, plus the author's name in the page's metadata. Velo is free and open source under the MIT license. Contributions, stars and feedback are welcome.