Changelog
All notable changes to this project are documented here. The format follows Keep a Changelog and the project uses semantic versioning.
#[0.6.3]
An audit release. A security and reliability pass over the whole framework (guards and RLS fail closed, forms only accept their own fields, dropped database connections recover, Redis hiccups no longer switch features off), and the pieces apps missed most: HTTP routes and middleware, page caching, translations, error boundaries, better testing and debugging, CSV export, drag-and-drop uploads, a form stepper, responsive images, and rename in the editor. Read Changed before upgrading: pyweb serve now needs PYWEB_AUTH_SECRET, and Postgres tenant tables get a new policy.
#Security
- Guards fail closed without a secret. A server function guarded by
@auth.requiredor permissions used to run unchecked when the app had noPYWEB_AUTH_SECRET; it is now refused. Rate limits run before any other check. - Forms only accept the fields they rendered. Each
<Form>carries a signed list of its field names; extra fields in a submit (is_admin=1) are ignored, and a submit without the list is refused ("reload the page"). - Row policies cover bulk writes and the stored row.
update()anddelete()on a policied Model check every affected row, andsave()checks the row as stored as well as the new values. - Postgres row-level security fails closed. A connection that never set the organization sees no rows (it used to see every organization), and the organization is set before every statement, so views and functions are covered too.
- Spread attributes (
{**attrs}) can't addon*handlers in any case,srcdoc, or unchecked URLs (formaction,data,poster, ...). - Emailed links never use a foreign
Hostheader, in development too. - Accounts: 2FA codes work once; setting a first password and signing out other devices need a recent sign-in (10 minutes); OAuth
email_verifiedmust really be true; form redirects go throughsafe_next. - Webhooks: GitHub deliveries are de-duplicated on the body (GitHub doesn't sign its delivery id).
- Push: someone who learns a browser's push endpoint can't take it over or unsubscribe it.
- Outbound fetch: NAT64 (
64:ff9b::/96) and IPv4-compatible IPv6 addresses are judged by the IPv4 address inside them. - S3:
upload_url(name, content_type=...)signs the content type, so an upload can't be stored astext/html. - Request headers are looked up case-insensitively everywhere (CSRF token,
Last-Event-ID,traceparent). - WebSockets: a ping flood closes the socket.
- Translations: the
Plural-Formsrule of a.pofile may only be a plural rule (no powers, shifts or huge numbers), so a hostile catalog can't hang the server. - Page cache: copies are kept per host and per language, and cached pages say
Vary: Cookie(plusAccept-Languagewith translations) so a CDN keeps them apart too. <Image>: Pillow opens only the format a file's name says, and each file has one cached copy per width however its path is spelled.- Source maps in
pyweb devhold the whole.pywebfile, server code included: only the developer's own browser gets them (not share-link guests or the LAN).pyweb buildmaps never contain source. - CSV: DataTable downloads also neutralize cells starting with a tab or carriage return.
- The VS Code extension uses
vscode-languageclient11; its build tools no longer pull in vulnerable@azure/msal-nodeandqsversions. - Dev tools:
pyweb dev --sharetreats a tunnel that rewritesHostto localhost as a guest; detailed error pages go only to the developer;pyweb mcp --httpalways needs a token (kept in.pyweb/mcp-token); the compile cache is read only from a folder and files only you can write.
#Fixed (reliability)
- Dropped database connections recover. A connection the server closed (restart, failover, idle timeout) is replaced instead of failing every request that later draws it from the pool; a read on one is retried once on a fresh connection; a transaction pings a connection that sat idle.
- Redis live updates and rate limits no longer turn themselves off for good after one error: they work without Redis for 5 seconds and try again. Two servers publishing to one channel at once can't make Redis refuse a message anymore (number, store and announce are one atomic script), and the shared rate limit can't be overshot by concurrent calls. Redis clients get 2-second timeouts.
- Live queries no longer miss a change when a page render picked up the new rows before the watcher re-ran.
RedisCache:clear()deletes only the cache's own keys (it used to empty the whole Redis database);@cache(backend=RedisCache(...))andswr()work with it; tag sets expire with their keys.- Jobs: PyWeb's own jobs (webhooks, push) run in a worker that never queued one; a job name a worker doesn't know is retried later (a deploy in progress) instead of dying at once; a timed-out job keeps its slot until its thread really returns.
- Overload and shutdown: requests waiting for a thread beyond
PYWEB_MAX_QUEUE(256) get503withRetry-After; work still queued when its time limit passes isn't started;/healthzis answered even with every thread busy, and/readyzsays 503 while draining; jobs and requests wind down together withinPYWEB_SHUTDOWN_TIMEOUT(25 s). - Streamed server functions run every step on one thread; a WebSocket handshake that fails gives its slot back; the Redis job store's cleanup reaches every job; failures in the live-data watcher are logged.
#Added
- HTTP routes and middleware.
@app.route("/api/items/{id:int}", methods=[...])(and@app.get/@app.post) answer anything that isn't a page: JSON, text, CSV downloads (pyweb.routes.csv), redirects, with typed path parameters,login=/roles=/rate=guards, API tokens (tokens=True), CORS (cors=[...]) and a same-site check for writes.@app.middlewareruns around every request. Routes appear inpyweb openapiand the MCPpyweb_routestool. See Routes & middleware. - Page caching. Every page gets an
ETag(and304 Not Modified); pages that are the same for everyone may be kept by the browser (no-cacheinstead ofno-store).@app.page(cache=300, vary=[...])keeps the rendered HTML for visitors who aren't signed in, dropped when a table the page read changes, shared through Redis when configured. See Performance. - Translations.
_("...")andngettext("{n} item", "{n} items", n)in Python and in markup, gettext.pocatalogs inlocales/(no extra package), the language from alangcookie orAccept-Language(App(locales=[...]),set_locale()),<html lang>anddir="rtl", the page's strings sent to the browser (an optionali18n.js),number/currency/dateformatting, andpyweb i18n extract | init | check. See Translations. <ErrorBoundary fallback="...">. A part of the page that fails, on the server or in the browser, shows its fallback instead of breaking the page. Its browser code is a small module loaded only by pages that use it.- Testing:
response.find("li.done")/find_all(...),client.render("Component", **props),client.a11y("/")(accessibility rules on the rendered page) andassert_snapshot(value, name). - Debugging:
pyweb dev --debug(attach VS Code or PyCharm through debugpy); source maps from each page module to its.pyweblines inpyweb dev, andpyweb build --sourcemaps. /robots.txtand/sitemap.xml(withApp(base_url=...)), from the app's public pages plus@app.sitemapgenerators;App(robots=...).- Plugins work:
App(plugins=[...])registers a plugin's routes, pages, server functions and Models. - CSV export:
DataTable export="csv"downloads the rows that match the search; the admin has "Export CSV" per Model (fresh sign-in, logged). - Uploads: drop files on a
<FileInput>, see what's chosen (image previews, remove one), an upload progress bar, and several files in one field (photos: list[UploadedFile]). Stepper/Step(UI kit): a form in steps that checks each step's fields before the next.Image(UI kit):srcsetof resized copies made by the server (/__pyweb/img/<width>/..., with Pillow:pyweb-stack[images]), lazy loading, no layout shift.- Editor: find references, rename (across the folder's
.pywebfiles for components and server functions) and "did you mean" quick fixes. TestClient.put/patch/delete;pyweb.request.bodyandrequest.json().PYWEB_DB_POOL(default 10) andApp(pool_size=...): database connections per process.
#Fixed
from pyweb.browser import document(andBlob,URL, ...) works in a file that also runs on the server; browser code can constructDate,URL,URLSearchParams,Blob,FormData,Event,CustomEventandPromise(newis added for you).- A server function with a
list[...]parameter and no default gets[]when the form sends none, instead of failing.
#Changed (internals)
- An option in
@app.page(...)/@app.layout(...)that isn't written out as a value (login=NEEDS_LOGIN) is a compile error; it used to be ignored, which could leave a page public. - One definition of "came from another site" (
pyweb.security.cross_site) for server functions, forms, the auth kit and push; one cookie parser (pyweb.net.http.parse_cookies). - The dev server moved to
pyweb.devserver, the production checks topyweb.checks, project scaffolding topyweb.scaffoldand the page CSP topyweb.csp(the old import paths still work). The server runtime no longer imports the AI helper:pyweb devhooks into page errors instead. from pyweb import *no longer brings in tooling modules (sync,lsp,deploy,build, ...);pyweb.lspand the others still import.- Every
PYWEB_*setting is documented (a test keeps it that way).
#Changed
pyweb serveandpyweb.asgi.create_app()refuse to start withoutPYWEB_AUTH_SECRET(setPYWEB_ENV=developmentto run without one). The development key is random per machine (kept in~/.cache/pyweb/dev-secret) instead of derived from the project path.- Tenant tables on Postgres get a new row-level security policy (
pyweb_tenant_v2). Apps that create tables get it on start; with migrations, runpyweb db diffandpyweb db upgrade.pyweb upgradeexplains both changes. - Forms rendered by 0.6.2 and submitted after the upgrade are refused once with "reload the page".
#[0.6.2]
The dev loop. Saves update the open page in place with every page and component keeping its state, any element opens its own line in your editor, error pages fix themselves with AI (your assistant's model through MCP, or your own key), a timeline steps back through every change, and pyweb dev --share gives someone a link to try what you're building. All of it lives in pyweb dev: production output is unchanged and there is nothing to change in your apps. See The dev loop.
#Added
- Hot reload without a page load. A save swaps the page in place through client navigation: no reload, no flash. Page variables, component variables (each instance keeps its own), form fields, scroll, focus and the selection stay. A stylesheet-only save swaps just that stylesheet. When the page changed too much to swap, it reloads with the same state, also after a compile error is fixed.
- Click to source. Hold Alt to see where any element comes from; Alt-click opens that line in your editor (
PYWEB_EDITOR, else VS Code, Cursor, Windsurf, Zed or Sublime Text, else avscode://link) and shows the inspector: the components around it with their live variables, which you can edit. - Fix with AI and Edit with AI. Compile error pages and dev 500 pages have Fix with AI; Alt+Shift-click any element to ask for a change. The answer is a compiled diff of one app file: Apply writes it (refused if the file changed since) and Undo puts it back (
.pyweb/history/). It is answered by the assistant connected throughpyweb mcpwhen its app supports MCP sampling, elseANTHROPIC_API_KEYorOPENAI_API_KEY/OPENAI_BASE_URL, else the page offers the prompt to copy. Credentials in what's sent are replaced by placeholders and put back in the answer. - Time-travel timeline. The toolbar's Timeline tab records every change to the page's variables with its cause (a click, typing, a server call); a slider steps back through them with the page paused, and Resume returns to now.
pyweb dev --share: a temporary public link (cloudflared, else localhost.run) with a QR code. The link's token sets a cookie that every request through the tunnel needs; guests get the app and hot reload, not your tools.- A better first five minutes.
pyweb newwith no name asks for the name, a starter and a colour preset (--themewithout asking);pyweb devopens the browser, prints the network URL with a QR code for a phone with--host 0.0.0.0, and shows a one-time Welcome panel with what to try and how to connect your assistant. - A faster first start. Parse results and compiled code are cached on disk (
~/.cache/pyweb;PYWEB_CACHE=0turns it off): loading the saas example in a fresh process went from about 340 to 210 ms.pyweb.bench --systemreportscold_dev_ms. - MCP: the
pyweb_assist_requeststool and thefix_errorsprompt;pyweb mcpanswers the page's AI requests through sampling.
#Changed
pyweb dev's toolbar and its/__pyweb/dev/endpoints answer only the person running it: a request from this machine to a loopback address. Visitors from the network (--host 0.0.0.0) or a share link get hot reload only.- The runtime is 25 bytes bigger (gzip) for the dev hooks; nothing runs in production.
#[0.6.1]
Better error messages, pyweb doctor, a pyweb dev that keeps your place when it reloads, much faster reloads and tests, and fixes found by installing 0.6.0 from PyPI and putting every template through every command. Nothing to change in your apps.
#Added
- Better error messages. Compile errors show the line with a caret under the problem, suggest the name you meant (a prop, component, variable, server function argument, kit variant or motion preset: "did you mean 'name'?"), and link the docs page that explains them. The CLI, the
pyweb devoverlay and the MCP tools (frame,docsfields) show the same. When page code raises inpyweb dev, the error page starts with the frames in your own files and their source lines. pyweb devkeeps your place when it reloads. After a save, the page comes back with its variables (a counter's count, a bound input's text), unbound form fields, scroll position and focus as they were. A variable whose type changed, or that was renamed, starts over; add?freshto the URL to start everything over. Production builds only grow by the names of page variables.pyweb doctorchecks the project and the machine in one go: Python, whether the app compiles, optional packages the app needs, the database and pending migrations, Redis, secrets written in the source, changespyweb upgradewants, a stale dev server link, tests, the port and the editor extension, each with a fix (--productionadds the production settings,--jsonfor CI). Assistants get it as thepyweb_doctortool.- Faster reloads and tests. The UI kit is compiled once per process and each file's Python code is reused until it changes: on the saas example a
pyweb devreload after a save went from about 255 to 60 ms, aTestClientfrom about 255 to 55 ms, and compiling from about 240 to 60 ms. The dev server notices a save within 0.1 s (was 0.4 s) and the page asks for the new version every 0.25 s (was 0.6 s).python -m pyweb.bench --systemreportsreload_msandtest_client_ms, and CI's benchmark gate watches them. pyweb checkwarns about kit props and motion values that won't work (<Button variant="outlin">), as the editor already did.
#Fixed
pyweb checkprinted the file and line twice for compile errors.- Components drawn as a kit button (
DialogClose) were flagged by the editor forvariant="default", which they support. pyweb testwith no path ranpytest tests/, which new apps don't have (their test istest_app.pynext toapp.pyweb), so it failed in every new project. It now runs the current folder, and accepts the app's.pywebfile as well as a test file or folder.- The
pyweb_testMCP tool given the app's.pywebfile (as every other tool takes) found no tests; it now tests that file's folder. pyweb upgradesays to apply pending migrations before creating theauth_sessionsone (on a fresh checkoutpyweb db diffrefused to run), and notes that 0.6'spyweb checkreports accessibility problems, which--stricttreats as failures.
#[0.6.0]
Teams, installable and desktop apps, a UI kit and motion, and security by design: organizations with roles, invitations and tenant-scoped Models (enforced by the database on Postgres), API tokens and OpenAPI, webhooks, PWA and Web Push, native desktop windows and installers, a styled and accessible component kit with springs and layout animations, Trusted Types, encrypted fields and a threat model, about 2.5× faster serving, Python 3.15 and free-threaded builds, and a much more capable MCP server. Most 0.5 apps run unchanged; see Upgrading to 0.6 and run pyweb upgrade --check.
#Added
- Python 3.14, 3.15 and free-threaded 3.15t are supported and tested in CI. On a free-threaded build one
pyweb serveprocess uses every core (about 3× the requests per second of the same build with the GIL). - Python 3.15 features. Browser code can use unpacking in comprehensions (
[*row for row in rows],{**d for d in ds}).lazy importis server-only Python, and older Pythons get a clear error that names the version it needs. pyweb profile app.pywebserves the app and records where the time goes while you use it: a Tachyon flame graph on Python 3.15, a text report before.pyweb-stack[speed]adds orjson for live queries, WebSocket messages, page state and server function results (a 10,000-row live query encodes 10× faster).python -m pyweb.bench --systemmeasures requests per second over sockets, a signed-in page, start-up and live queries;--compare DIRfails on a 15% regression against another checkout. CI runs it on every push.PYWEB_SSR_VERIFY=1renders every page with both renderers and fails if they differ.- New docs page: Performance, including why PyWeb has no Rust core.
- Trusted Types. Pages tell the browser to refuse plain strings in HTML and script sinks; PyWeb's runtime uses private policies (Markdown, client navigation, the service worker). Pages that use npm packages are exempt.
- Encrypted fields.
Field(encrypted=True)stores AES-256-GCM ciphertext underPYWEB_DATA_KEY(kept apart from the session secret);searchable=Trueadds a blind index for exact lookups. Rotate withPYWEB_DATA_KEY_PREVIOUSandpyweb db reencrypt. - Secret scanning.
pyweb checkfinds keys written into the app and the files next to it: known formats fail the check, random-looking values in secret-named variables are warnings. pyweb.http.fetchfor URLs other people choose: refuses internal addresses (including through redirects and DNS rebinding), with time and size limits.PYWEB_FETCH_ALLOWlets it reach internal services you name.@server(rate="5/minute", per="user"|"ip"|"all")limits one server function (429 withRetry-After; shared through Redis when configured).- Webhooks.
@app.webhook("/hooks/stripe", secret=..., scheme="stripe")checks GitHub, Stripe and Standard Webhooks signatures, drops repeats and replays, and runs the handler as a retried job.webhooks.send()/publish()sign deliveries (Standard Webhooks), retry them over about a day through the SSRF-safe fetch, and log each attempt;WebhookEndpointrows hold each organization's endpoints. - Installable apps.
App(pwa=True)(orpwa=PWA(name=, icon=, theme_color=, offline_page=, cache_pages=...)) serves a web app manifest, icons made from one PNG (or drawn for you) and a service worker: static files work offline, pages without a connection show an offline page, and withcache_pages=Truepages visitors opened while signed out stay readable offline. The worker is registered through a third Trusted Types policy,pyweb-sw, which accepts only/sw.js. - A UI kit (
from pyweb.ui import Button, Card, Badge, Alert, ...): themed, accessible, server-rendered components.App(theme=Theme(accent=, radius=, font=, density=, dark=))or a preset computes 12-step OKLCH colour scales (accent, gray, status colours; light and dark) with contrast checked to 4.5:1. The kit's CSS sits in a cascade layer so app CSS always wins, and every part carriesdata-part/data-stateattributes.pyweb ui add|diff|listcopies a component's source into the app. Overlays and pickers follow the WAI-ARIA Authoring Practices: Dialog, AlertDialog, Sheet, Popover, Tooltip, HoverCard, DropdownMenu, ContextMenu, Menubar (with checkbox/radio items and submenus), SelectMenu, Combobox, a Command palette (⌘K) and sonner-style toasts (pyweb.ui.toast()from server code). Also Tabs, Accordion and Collapsible (native<details>), Checkbox, Switch, RadioGroup, Toggle, ToggleGroup, Slider, InputOTP, a Sidebar layout, NavigationMenu, Breadcrumb, Pagination, Resizable panels, ScrollArea, Calendar and DatePicker, Carousel, DataTable (search, sort, pages, row selection) and SVG charts (bar, line, area, pie, sparkline) drawn on the server. Each behaviour module loads only on pages that use it;from pyweb.ui import *imports them all. - Motion (in the spirit of motion.dev):
initial=,animate=,exit=andtransition=on any element, springs that keep their momentum when interrupted, presets (animate="fade-up"), variants with staggered children,while_hover/while_tap/while_focus/while_in_view, exit animations forifandfor,layout(rows glide to their new places, keeping focus and input values),layout_id(shared elements),dragwith constraints and momentum, counting numbers (animate="count"), View Transitions on client navigation, andfrom pyweb.motion import animate, timeline, stagger, scroll_progress, use_transformfor browser code.App(motion=Motion(feel=, speed=, reduced=))changes every animation at once, the UI kit's included, and reduced-motion settings are followed. The server renders the first pose; pages without motion don't load the engine (7.5 KB gzipped). - Customising the kit, every level. - The dev toolbar gets a Theme tab: a live preview on the running app, copy as code, and "Save to app.pyweb", which rewrites only the
App(theme=...)argument. - It also gets a Motion tab: pick an animated element, tune its spring or duration, and replay it. -ui.extend("Button", variant={"brand": {...}})adds your own variants to kit components. -variants(),style()andcx()(cva and tailwind-merge style) are for your own components, on the server and in the browser. - The editor completes variant, size and tone values, presets,Theme(...)/Motion(...)settings and transition keys, and warns about unknown ones or out-of-range springs. - A "UI kit and motion" example (
examples/ui): dialogs, menus, pickers, toasts, a data table and charts, plus staggered, gesture, drag, layout and shared-element animations. It runs on the website, as a live demo and in the playground. MenuItem(href=...)makes a menu item a link.- The UI kit is tested in Chromium, Firefox and WebKit (keyboard behaviour of every component, motion and the examples), with screenshot baselines per component in light and dark, and axe-core finding no serious violations on the examples, the auth pages and
/admin. - Accessibility checks in
pyweb checkand the editor: images without alt, clicks keyboards can't reach, unlabelled fields, unnamed buttons and links, positive tabindex, an empty page language. The examples and templates were fixed where they fell short. - Testing apps with organizations:
client.login(email, org="Acme", org_role="admin")signs in as a member of that organization (created if needed) and makes it the current one;with as_org(org):runs code for an organization;Factory(...).for_org(org)makes tenant rows in it. @app.page(..., org_role=..., feature=...)(and on layouts), like@server: the page needs that role in the current organization, or a plan with that feature (403 otherwise).- Editor: completions for
@server(...)and@app.page(...)options,org_role=,per=,rate=, plan features,tenant=Trueand webhook schemes; warnings for a malformedrate=, an unknown role, and atenant=TrueModel read with.unscoped()outsidewith system():. - A much better MCP server (29 tools, up from 18): - new tools:
pyweb_docs(search every docs page, the guide and the threat model),pyweb_ui(the kit's components, their parameters and source, copying one into your app, making and saving a theme),pyweb_review(screenshots in light and dark at desktop and phone widths with axe-core's audit),pyweb_explain(what your editor shows for a line: where each name runs, problems, completions),pyweb_profile,pyweb_webhook_send(a correctly signed test delivery, then the handler's result),pyweb_teams,pyweb_upgrade,pyweb_deploy_plan,pyweb_openapiandpyweb_security_check; -pyweb_devandpyweb_logssee your runningpyweb dev: whether the app compiles (with the traceback), its logs and the requests your browser made.pyweb devwrites.pyweb/dev.json(its address and a token readable only by you);pyweb_screenshotandpyweb_reviewuse it too; -pyweb_render,pyweb_call,pyweb_screenshotandpyweb_profileact as a signed-in user and organization member (as_user,roles,org,org_role); - MCP 2025-11-25: every tool has a title, read-only/destructive hints and an output schema; arguments are checked before a tool runs; slow tools report progress; logging; completion of resource and prompt arguments; resources for every docs page (pyweb://docs/<page>), kit component (pyweb://kit/<Component>) and the threat model; - eight new prompts:add_teams,make_installable,make_desktop_app,security_review,upgrade_pyweb,design_pass,fix_failing_testanddebug_page; -pyweb mcp --httpserves Streamable HTTP on 127.0.0.1 (sessions, event streams for progress;OriginandHostchecked; a token is required to listen anywhere else). - The documentation ships inside the package, for the MCP server.
pyweb upgradepoints at stylesheets written for the 0.5 sign-in and admin pages' classes.- Playground: apps with teams get a "Team member" visitor next to "Signed in" (both in one demo team, so you can see what each role sees), and installable apps get an Install tab with their manifest and icons.
- Docs: Upgrading to 0.6, testing apps with teams, and the SaaS tutorial rewritten around teams.
- New
desktoptemplate (pyweb new notes --template desktop): a Markdown notes app in its own window that exports a note with the system's Save dialog, with its tests and packaging instructions. - Plain functions from other
.pywebfiles work in browser code, along with the functions and constants they use. mathin browser code.import math(andfrom math import pi) works in browser code, translated to JavaScript'sMath.- Components pass attributes through. A
**attrsparameter takes any other attribute, and{**attrs}spreads a dict onto an element (explicit attributes win, classes merge). - Desktop apps.
pyweb desktop app.pywebopens the app in its own window (pywebview: WebView2, WKWebView, WebKitGTK or Qt), with its database, uploads and per-installation secrets in the OS's data folder. Only the window gets in: a one-time launch cookie, an exactHostand same-origin requests are required, and links to other sites open in the browser.pyweb.desktopgives server code file dialogs, notifications, "reveal in folder" and the data folder;App(desktop=Window(...))sets the window.pyweb build --desktop [--package]writes a Briefcase project with icons for every OS and builds the installer (MSI, DMG,.deb/.rpm).pyweb-stack[desktop]installs what it needs. - Push notifications. A
data-pw-push="subscribe"button asks for permission;push.send(user, "Title", "Body", url="/orders/42")encrypts (RFC 8291), signs (VAPID) and delivers through background jobs, deleting subscriptions the push service says are gone. Only the browsers' push services are accepted as endpoints.pyweb push keymakes aPYWEB_VAPID_KEY;pyweb-stack[push]installs what it needs. - Uploaded files are cleaned up. Files no row refers to are deleted after a day (daily, or
pyweb files clean). - API tokens and OpenAPI.
/account/tokensmakes tokens for calling server functions withAuthorization: Bearer(scoped to functions, optionally expiring, stored as hashes);pyweb openapi app.pywebwrites an OpenAPI 3.1 document from the functions' types, rules and guards. - Your data.
/accountoffers a JSON download of everything stored about the user (auth.export_user()) and deleting the account (auth.delete_user(), after a recent sign-in and typing the email). - Signed-in devices.
/accountlists each session (device, network, last seen) and can sign one out;auth.sessions(user)andauth.end_session(user, id)do the same from code. Apps with migrations need one for the newauth_sessionstable (pyweb upgradesays so); until then sign-in works as before. - Supply chain.
pyweb buildwrites a CycloneDXsbom.json; releases get PEP 740 attestations on PyPI and a CycloneDX file; CI pins every GitHub Action to a commit. - Teams.
app.use_auth(orgs=True)adds organizations, members with roles (owner, admin, member, viewer), emailed invitations and the pages to manage them (/orgs).class Project(Model, tenant=True)keeps each organization's rows to itself: queries, saves, bulk updates, live lists and background jobs are all limited to the current organization.@server(org_role="admin", feature="exports")andrate=..., per="org";auth.plans({...})with features and limits (seats are enforced). On Postgres, migrations add row-level security, so raw SQL is limited to the organization too. See Teams. THREAT_MODEL.md: every threat, its mitigation and the test that proves it (a test keeps the references current). CI fuzzes the RPC and form parsers with Hypothesis and runs an OWASP ZAP baseline scan.- CSP violation reports go to
/__pyweb/csp-report: apyweb.csplog line and thepyweb_csp_violations_totalmetric.
#Changed
- About 2.5× more requests per second over
pyweb serve: pages render on the thread that read the request (the time limit moved into the connection handler), each page's markup compiles to one Python function, and request ids no longer cost a system call each. import pywebtakes 2 ms instead of 87 ms, andpyweb --versionabout a third of the time it did: modules load when first used.- The sign-in, account, organization and admin pages use the UI kit and the app's theme:
App(theme=...)restyles them along with your pages./__pyweb/auth/auth.cssnow only lays them out. - The templates and examples use the UI kit and motion.
todorows animate in and out and filter with a toggle group;countercounts;saas(Teamboard) has a sidebar layout with an account menu, a new-project dialog, toasts, animated live tasks, empty states and the zinc theme; the dashboard's totals count up and it adds the kit's bar chart and a sparkline. The sharedstatic/app.cssonly lays pages out. - The
saastemplate (Teamboard) has teams. Projects and tasks aretenant=TrueModels shared by an organization; each new user gets a team, and the sidebar links to members and invitations and to API tokens. Creating a project publishes aproject.createdwebhook, and the app is installable (pwa=True). Its tests show two teams kept apart and two teammates sharing projects. pyweb checkno longer asks for a policy ontenant=TrueModels: the organization scope already limits who reads them.- The CI benchmark measures fixed copies of the todo and saas apps (
bench/apps/), so redesigning an example doesn't read as a speed change. - The website's live demos are what the server sends (with the kit's and motion's files), and the playground runs apps that use the kit.
- Tracebacks from
.pywebfiles show the source lines. pyweb checkreports the line of a Python syntax error.pyweb.platformis real and supported:platform.desktop,platform.pwa,platform.installedandplatform.webare read per request.platform.mobileandplatform.edgeare always False (they were placeholders);pyweb upgradepoints at them.
#Fixed
- A server function argument annotated
date,datetime,time,DecimalorUUIDarrived as the text the browser sent, unchecked ("banana"for adate). It's now parsed (ISO 8601 for dates and times), and anything else is avalidation_errornaming the field. checked={row["done"]}with a database's0renderedchecked="0", so the server showed every box ticked. Boolean attributes (checked,disabled,selected, ...) now follow truthiness on the server as in the browser.- A page using only components copied with
pyweb ui adddidn't get the kit's stylesheet and behaviours. - An alert's title was smaller than its text.
- The plant shop example's link and dark-mode button colours were below WCAG contrast.
- A
Card(orAlert,Table,Breadcrumb) insideTabshad its content taken for a tab panel and hidden; and the card's header styles reached a data table's header row inside it. - The saas template's daily digest called a query method that doesn't exist (
values_list); it usespluck, and a test runs it. - A menubar arrow key pressed right after opening a menu (before focus moved into it) left that menu open.
lambda n=n: go(n)in an event handler kept the event instead ofn.- Hydrating a page no longer rewrites attributes the server already rendered, so it can't undo what a UI kit script (or the user, typing early) changed in the meantime.
- Markup right after an
if/forblock inside an element (a{children}or text line at the block's indent) was put inside the block; it now follows it. - An optional callback prop that wasn't passed no longer throws when its event fires.
- Markup right after a
defwhose signature spans several lines failed to compile. - Text children re-rendered in the browser showed as a list (
['Medium']). get_or_404()inside a server function answered 500; it now answers 404.Post.id(and other columns added automatically) failed before the Model had been used once.- Log redaction took time quadratic in the length of a word without
=(0.3 ms for a 64-character id, on every logged query parameter while developing); it is now linear. Found by the new benchmark gate. - Form submits with more than 1,000 fields or 100 files are refused (400) instead of being parsed.
- A Model that fails to set up no longer breaks every Model defined after it.
- Models on Python 3.14+ (annotations are evaluated lazily there, PEP 649).
#[0.5.0]
Production apps in one Python file: Models with migrations, forms, an auth kit with an admin, row-level live updates over WebSockets on PyWeb's own server, durable background jobs and schedules, one-command deployment for six targets, built-in observability, and editors and AI assistants that understand your data. Most 0.4 apps run unchanged; see Upgrading to 0.5 and run pyweb upgrade --check.
#Added
- Models on
pyweb.db.class Post(Model): title: str = Field(max=120)works on SQLite, Postgres and MySQL with the same code. Types includeDecimal, timezone-awaredatetime,date,time, JSON (dict/list),bytes,UUID,Text,Email,URLandSlug.Field(...)holds the column's schema and its validation rules (min,max,pattern,choices,format,unique,index,private,auto_now_add, ...);@validates("field")adds custom checks. Saving writes only changed columns; unique violations become field errors. - Relations.
author: Useris a foreign key,tags: list[Tag]is many-to-many,OneToOne(...), with reverse accessors (user.posts).include("author", "tags", "author.profile")loads related rows with one query per relation; reading a relation that wasn't included is an error while developing (so pages can't do N+1 queries) and a logged warning in production. Relation filters (Post.author.has(...),User.posts.any(...)) use subqueries. - Query builder. Immutable, lazy queries with
Post.views > 10,&,|,~, keyword lookups (title__icontains=,id__in=, ...),order, slicing,first/last/get/get_or_404,count/exists,values/pluck,aggregateandgroup_bywithCount/Sum/Avg/Min/Max, bulkupdate/delete, cursor pagination withpage(),get_or_create,upsert,bulk_create, and.live(). - Transactions per request. Every
@servercall is one transaction, started at its first write;@atomic/@atomic(False). Nesteddb.transaction()blocks are savepoints.ValidationErrorfrom an RPC answers 422 with the errors per field. - Migrations.
pyweb db diffcompares Models with the live database and writes Python migrations;upgrade,downgrade,status,adopt,squash,seed. Changes are split into expand steps (safe during a rolling deploy) and contract steps (upgrade --contract), including renames with--rename table.old=new. A lock shared by every server (Postgres advisory lock, MySQLGET_LOCK, or a lock row) makespyweb serve --migratesafe with many servers. SQLite schema changes rebuild tables with foreign keys paused.pyweb devapplies pending migrations, and apps without migrations create tables on first use. - Forms.
<Form action={save_post}>with<Input>,<Textarea>,<Select>,<Checkbox>,<FileInput>,<Submit>and<FormError>builds labelled, accessible fields from the action's Model (or plain typed parameters). Rules are checked in the browser while typing, with the same messages as the server; the form submits without a page load and shows server errors next to each input, and still works as a plain POST without JavaScript (422 re-render with values, 303 on success). CSRF token, cross-site refusal, a one-time key per submit (double clicks run once), only the action's own fields are read,values={row}edits a row through a signed id, andforms.carry()/restore()for multi-step forms. The browser code (forms.js) only loads on pages with a form. - Uploads and storage.
File(types=["image/*"], max_size="2MB")fields andUploadedFileparameters; types checked from the file's bytes;PYWEB_MAX_UPLOAD(default 10MB);PYWEB_STORAGEis a local folder (served with a sandboxing CSP) or S3-compatible storage with presigned URLs and no SDK. - Auth kit.
auth = app.use_auth()adds/signup,/login,/logout,/reset,/accountand/admin, rendered on the server and working without JavaScript. Sign in with a password, an emailed link, a passkey (also offered in the email field's autofill) or GitHub / Google / Microsoft (PKCE +state), with optional authenticator-app codes and recovery codes. Define a page at the same route to replace one;auth.user(),auth.authenticate(),auth.login(),auth.set_roles(),auth.revoke()... for custom flows. Tablesusers,auth_identities,auth_credentials,auth_tokensandauth_eventsare ordinary Models. - Guards.
login=True,roles=[...]andfresh=secondson@app.page,@app.layoutand@server. - Row policies.
Note.policy(read=..., write=...)limits the rows each user can see and change, on every query and save in a request (with system():skips them on purpose). - Admin.
/adminlists, searches, edits and deletes rows of every Model for users with theadminrole; private fields never appear; every change is in the audit log. - Account security. scrypt (or argon2id with
pyweb-stack[auth]) hashes upgraded at sign-in; breached-password check in production; guessing slowed down per account and per IP (shared through Redis) with no lockout; the same answer and timing for unknown emails; emailed links hashed, single-use (also under concurrent clicks) and short-lived; passkey challenges single-use on every server; password resets, password and role changes sign out other sessions, durably in theuserstable (and fail closed if the database can't be checked); emailed links are built fromPYWEB_ORIGIN, never from theHostheader, in production. pyweb.mail.PYWEB_MAIL_URL(SMTP/SMTPS) andPYWEB_MAIL_FROM; while developing, emails are printed and kept inpyweb.mail.OUTBOX.pyweb check --productionreportsuse_auth()withoutPYWEB_ORIGIN.- PyWeb's own server.
pyweb serveandpyweb devnow run onpyweb.net: HTTP/1.1, WebSockets (RFC 6455) and Server-Sent Events on one asyncio loop per process, standard library only. Thousands of open live connections cost a coroutine each instead of a thread (the old server stopped at 256); page renders and RPCs run on a thread pool (PYWEB_THREADS).--workers N/WEB_CONCURRENCYforks processes sharing the port and replaces crashed ones. The parser refuses request smuggling vectors (CL+TE, repeated lengths, folded headers, bad chunk sizes, bare LF) and has timeouts for heads, bodies, idle keep-alive and slow readers; SIGTERM drains gracefully. - One WebSocket per tab for live updates. Every
subscribe()and live query on a page shares/__pyweb/ws(Server-Sent Events used one connection each, and browsers allow six per site), with jittered reconnects that resume where they stopped, and automatic fallback to Server-Sent Events, then polling. The socket checksOrigin(PYWEB_ALLOWED_ORIGINSfor others), re-checks the session every minute and closes when it's revoked, limits subscriptions, message size and rate, and doesn't buffer without limit for slow clients. Works in the ASGI adapter too. - Live queries send patches. Rows with an
id(orkey=) travel as inserts, updates, deletes and moves: changing one row of a long list sends that row only, and the browser redraws only it. A page that missed a change gets the whole result once.Model.query().live()uses the primary key. - Presence.
presence(name)andjoin(room, info, on_members, on_cast): who is on a page, and ephemeral casts (cursors, typing) to everyone else in the room, across processes with Redis. - Feeds made while someone is signed in only work for that session.
live.js: live-update code loads only on pages that use it.- Durable background jobs.
@app.job(retries=, timeout=, queue=, unique_for=)andfn.enqueue(..., delay=, at=, key=). Jobs are stored in the app's database (pyweb_jobs), Redis (PYWEB_JOBS=redis) or memory, and queued inside the request's transaction (a rollback queues nothing). Workers claim with leases (FOR UPDATE SKIP LOCKEDon Postgres/MySQL), so a crashed or killed worker's job runs again elsewhere; failures retry with jittered exponential backoff, then godead(retry from/adminorpyweb jobs retry); timeouts; graceful SIGTERM hands running jobs back.pyweb worker,pyweb jobs list|retry|purge|run, and a worker insidepyweb dev/pyweb serve(PYWEB_WORKER=0to run them separately). - Schedules.
@app.cron("0 3 * * *", tz=..., catchup=...)with PyWeb's own cron parser (daylight saving handled) and@app.every(minutes=5). Every server runs the scheduler and each slot is queued exactly once, with no leader election. - Email outbox. With durable jobs,
pyweb.mail.sendqueues delivery as a retried job that only leaves if the request committed. - Nightly cleanup of finished jobs, expired sign-in links and old audit entries.
db.after_commit(fn): run code once the current transaction commits (dropped on rollback, including a rolled-back savepoint), anddb.after_end(fn)for code that must run either way.- Jobs stored in the app's database are marked done in the job's own transaction, so a job's database writes happen exactly once even if a worker crashes or loses its lease.
pyweb deployplans the production topology. It reads the app (database, jobs, live updates, sign-in, uploads, migrations), decides what production needs for the target and number of machines (Postgres instead of SQLite for several machines or disposable disks, Redis for more than one process, a separate worker, migrations once per deploy, object storage for uploads, the secrets to set), prints the plan with the reason for each decision, and writes the files. Targets:docker,compose(Caddy, load-balanced replicas, Postgres, Redis, worker, migrate step),k8s(web and worker Deployments, migrate init container, probes, PodDisruptionBudget, HorizontalPodAutoscaler, Ingress),fly,renderandrailway.--planprints only;--checkfails CI when the plan has warnings.- A production image: multi-stage, non-root, cached pip installs, health check,
SIGTERMdrain,PYTHON_IMAGE/PYWEB_SPEC/EXTRA_PACKAGESbuild arguments. DATABASE_URLoverrides the URL inApp(database=...)(develop on SQLite, deploy on Postgres, same code).pyweb serveuses$PORT.pyweb check --productionalso reports Models without migrations, unapplied migrations, email withoutPYWEB_MAIL_URL, uploads without object storage, and jobs withPYWEB_WORKER=0.- CI deploys a real stack (2 replicas, worker, Postgres, Redis, Caddy) with
pyweb deploy composeand checks load balancing, jobs on the worker and live updates across replicas. - Read replicas with
DATABASE_REPLICA_URL(read-your-writes inside a request), slow query logging with query plans (PYWEB_SLOW_QUERY_MS),pyweb.db.QUERY_HOOKS, seeds (pyweb.db.seeds) andpyweb.testing.Factory. - Observability. A dev toolbar on every page in
pyweb dev: the SQL each request ran (repeated statements grouped, with an N+1 warning), spans, jobs queued, emails captured, errors, and a list of every request since; it never ships in production builds. JSON logs in production (readable text while developing) where every line carries the request id, trace id, route and user, and secrets (password,token,api_key, ... plusPYWEB_LOG_REDACT) are redacted, including inside messages and URLs. Prometheus/metrics(PYWEB_METRICS_TOKEN; requests, server functions, queries, jobs, live sockets, mail, sign-ins, errors), added up across--workersprocesses;pyweb worker --metrics-port. W3Ctraceparentis continued, returned on every response and carried into the jobs a request queues, so one trace covers the click and the job's work on another machine. OpenTelemetry spans for requests, queries, jobs andwith span("..."):blocks (pip install pyweb-stack[otel],PYWEB_OTEL=1).@app.on_errorhooks receive every unhandled error with its request context. pyweb worker --alive: a health check for worker containers (the worker touches a heartbeat file after each round that reached its job store); compose and Kubernetes use it.pyweb new --template saas: accounts, projects and tasks with row policies,<Form>s, live pages, a background job, a weekday cron email,/admin, seeds, tests and a first migration, ready forpyweb deploy. Templates with a database getmigrations/0001_initial.pyand a README.TestClient.login(email, roles=[...])signs a test in (creating the account with the auth kit) without going through the sign-in form;logout()signs out.seeds.pysees the app's Models by name;pyweb.models.model("Post")looks one up anywhere.- A server function parameter can take its rules from a default:
title: str = Field(min=1, max=120)(same asAnnotated[str, Field(...)]). <Input name="project_id" type="hidden" />is just the input (for ids the page sets withvalues=);label=""hides a field's label but keeps it as the input'saria-label.- Editors know your data. The language server completes Model fields and query methods after
Post., keyword fields inwhere(/create(, relations ininclude(", columns inorder(",Field(options and a<Form>'s fields inname=". It flags form fields the action doesn't have, loops that read a relation their query didn'tinclude()(N+1, pointing at the line), and Models changed without a migration, with a code lens that writes it. VS Code: "Create Migration from Model Changes", "Apply Migrations", and snippets for Models, relations, form pages, live pages, jobs, schedules, row policies anduse_auth. The extension uses the current language client (vscode-languageclient 10), is bundled (12 files instead of 364), needs VS Code 1.91 or later, and is tested in a real VS Code against the real language server in CI. pyweb db check: fails (exit 1) when the Models changed without a migration, by applying the migrations to a scratch database, so it needs no real database. For CI.- MCP tools for data:
pyweb_db_schema(Models, tables, drift),pyweb_db_query(read-only SQL, capped, secrets redacted),pyweb_migrations(status, diff, upgrade),pyweb_jobs(list, retry, run) andpyweb_requests(each request's SQL, N+1 warnings, jobs, errors). - Playground 2. Several files per app (import components from a second
.pywebfile; shared as one link, downloaded as a zip), a Requests tab (each request's SQL with N+1 warnings, spans, jobs, emails, errors), a Database tab (tables and rows, secrets redacted), a visitor picker to see pages signed out, signed in or as an admin, background jobs run right after the request that queued them, and SQLite loaded when an app has a database. New examples: the blog (on Models) and the saas template. Worker.run_inline()runs due jobs on the calling thread (no thread pool).pyweb upgrade --check/--fixlists what an app needs to change for 0.5, with file and line, and applies the safe rewrites:Model.configure(...)→App(database=...), andpyweb db migrate/rollbackandpyweb deploy --target Xin Procfiles, scripts, Dockerfiles and CI files.PYWEB_STRICT_DEPRECATIONS=1turns deprecation warnings into errors. Deprecated in 0.5:Model.configure(), the in-memoryQueue,RedisQueueand@task(use@app.job), andpyweb deploy --target/--compose.pyweb checkwarns about SQL built from strings passed toexecute(), pages that readauth.user().xwithoutlogin=True, and Models owned by a user without a row policy;--strictfails on any warning.
#Changed
- The blog template and example use a Model instead of raw SQL.
pyweb lspanswers requests it doesn't handle with "method not found" (it answerednull), as LSP clients expect.PYWEB_MAX_CONNECTIONSdefaults to 10,000 per process (it was 256 for the threaded server, whichpyweb serve --app module:factorystill uses).pyweb.testing.serveruns PyWeb's server.- SQLite connections enforce foreign keys and use write-ahead logging.
Model.configure()is deprecated in favour ofApp(database=...)/DATABASE_URL; 0.4-style Models keep working (rows still read like dicts:row["name"]).- In production, a Model with no database is an error instead of an in-memory SQLite file.
#Security
- Sessions and feed tokens are verified only with keys derived per purpose. The raw secret, still accepted in 0.4.4 for tokens from older versions, is no longer a key.
- The default Content-Security-Policy allows inline
<style>blocks by their hashes instead of'unsafe-inline'(so injected markup can't add a stylesheet that leaks page content), and addsform-action 'self'.
#Fixed
- Rules on server function parameters (
Annotated[str, Field(max=40)]) were ignored: a direct call could send any value, and forms didn't get the matching browser checks. They're enforced on every call now, with errors per field (422). owner: User = Field(readonly=True)made a plain column instead of a foreign key; options given withField(...)now apply to the relation.pyweb db seed --database URLwrote to the app's own database; apps without migrations yet couldn't be seeded beforepyweb devcreated their tables.pyweb devdidn't reload pages larger than 1 KB after a change: they were gzipped before the reload script could be added.Model.query()...live()in a page made a static page: the compiler only recognisedlive(db, sql).- A value computed from a live query (
left = len([t for t in tasks if not t["done"]])), or from any server-loaded list a handler changes, was computed once on the server and never updated in the browser. It now follows its source there. - A form for a Model with a read-only field (
owner: User = Field(readonly=True)) was refused with "owner is required" before the server function could set the field. - Validation messages named the field twice ("body Body is required").
- Schedules in UTC (including PyWeb's nightly cleanup) no longer need a time zone database, which Windows and Pyodide (the playground) don't ship; other zones explain that
pip install tzdataprovides one. - The server answered a refused connection (503) or a rejected request and closed at once; unread request bytes then made the kernel reset the connection, which could destroy the response. It now closes politely (half-close, drain briefly).
- While developing, a Model's table made on first use inside a request that then failed was rolled back but still counted as made ("no such table" until a restart). Tables are now made when the app loads, and a lazily made one only counts once its transaction commits.
- Audit log entries written during a request that rolls back are kept (written when the transaction ends, committed or not), and a failing audit insert can no longer abort the request's transaction.
Site(..., rate_limit=False)(used bypyweb.testing.serve) passedFalseto the server instead of turning rate limits off.
#[0.4.4]
Security and running in production. No app changes needed, and nobody is signed out by the upgrade.
#Added
- Signing keys per purpose, and rotation. Sessions, live-update feeds and live query specs are signed with separate keys derived from
PYWEB_AUTH_SECRET.PYWEB_AUTH_SECRET_PREVIOUSkeeps tokens from an old secret working while you change it. Tokens from 0.4.3 and earlier still work. - Sessions: each login starts a new session; sessions renew on visits and end 30 days after sign-in;
auth.revoke_user(user_id)signs a user out on every device (in memory, or shared withRedisSessionVersions). - Typed server function arguments:
list[...],dict[...],Optional,Literal, dataclasses, Models andEmailare checked against their type hints, and unknown arguments are refused (422). pyweb/config.py: everyPYWEB_*setting in one place, validated at startup (a bad value stops the server with a clear message).PYWEB_REDIS_URL: shares rate limits (RedisRateLimiter) and live updates between server processes./readyzchecks that every database the app opened answers (503 when one doesn't);/healthzstays a liveness check.- Graceful shutdown: on SIGTERM and ASGI shutdown, live connections end and background jobs get up to 10 seconds to finish.
pyweb deploy --target compose --domain example.computs Caddy in front of the app with automatic HTTPS, keeps the app reachable only through it, and setsPYWEB_TRUST_PROXY=1and Secure cookies. The k8s target trusts its Ingress and uses/readyzfor readiness. The deployment docs explain reverse proxies, with nginx and Caddy examples.pyweb check --productionlists settings that would leave a gap (secret, HTTPS cookies, proxy, Redis with several workers, ...).- npm supply chain:
pyweb.lockrecords a SHA-256 per vendored file andpyweb buildrefuses files that changed. - CI: dependency vulnerability audit (pip-audit), CodeQL code scanning, Dependabot, and signed build provenance for release files.
- A much better playground on the website: syntax highlighting with the error line marked (click the line number to jump to it), a Console that shows
print()output, every server call with its arguments, status and time, and errors from the page; a draggable divider; phone/tablet/desktop preview widths and a reload button; highlighted JavaScript with its gzipped size; Reset, Download (app.pyweb, ready forpyweb dev) and autosave, so edits survive a reload; and a Code/Preview switch on phones. - Docs: a threat model, key rotation, session lifetime, a production checklist, and the new settings.
#Security
- Requests the browser marks
Sec-Fetch-Site: cross-sitecan't call server functions. - Deeply nested JSON bodies crashed the request handler with a
RecursionError; bodies deeper than 32 levels or with more than 10,000 values are now refused. pyweb serveandpyweb devdrop clients that stall (30 s), answer 503 past 256 simultaneous connections and 431 to headers over 16 KB.- At most 20 open live connections per client address (429 beyond).
- Pages that take longer than 30 seconds to render answer 504 instead of holding a thread.
- New response headers:
Permissions-Policy,Cross-Origin-Opener-Policy,Cross-Origin-Resource-Policy, andStrict-Transport-SecuritywhenPYWEB_COOKIE_SECUREis on. Both servers now send the same set. RedisCacheno longer unpickles data unlessallow_pickle=True(unpickling can run code written by anyone with Redis access).
#Fixed
@auth_requiredserver functions rejected sessions older than one hour, while pages accepted them for 7 days.
#[0.4.3]
A review release: bug fixes, security hardening and speed-ups. No API removals; one new setting (PYWEB_TRUST_PROXY).
#Fixed
- Pages showed stale data when a module-level value (
ITEMS = []) was changed by an@serverfunction: the compiler copied its starting value into browser code, and the page re-rendered with it. Values that code changes now come from the server on each request. db.transaction(): a statement error that your code caught rolled back the transaction's earlier writes while later ones still committed. Errors inside a transaction now leave it totransaction()(all or nothing).db.stream()inside a transaction waited for a second connection (a 10 second hang with SQLite in memory); it now uses the transaction's.pyweb servesent SVG, images, fonts, JSON and WebAssembly asapplication/octet-stream(browsers don't show an SVG sent that way).- Your own files in
static/(such asapp.css) were cached by browsers for a year, so deploys didn't show up for returning visitors. They're now revalidated with an ETag (a304when unchanged); content-hashed files,?v=URLs and npm packages are still cached for a year. - Client-side navigation could show a page prefetched before a server call changed its data.
async defserver functions ignoredrpc_timeout.- The ASGI adapter kept only the last of repeated request headers, so HTTP/2 clients sending each cookie separately lost all but one.
pyweb dts: type aliases were never written, members on one line ({ a: string; b?: number }) produced invalid Python, and optional fields before required ones made the stub fail to import.- Very long upload filenames are shortened (keeping the extension) instead of failing to save.
#Security
- RPC rate limits used the
X-Forwarded-Forheader, which any client can set (so the limit was easy to get around), and put every visitor without a session cookie in one shared bucket. They now use the connection's address; behind a reverse proxy setPYWEB_TRUST_PROXY=1(or the number of proxies) to use the address your proxy saw. auth.require_sessionandauth.login_responseonly redirect to paths on your site (//evil.examplebecomes/); the newauth.safe_next()does the same for your own?next=handling.- Magic-link tokens are signed separately from session cookies, so one can't be used as the other. Links issued before the upgrade stop working (they last 15 minutes).
#Performance
- HTML, JavaScript, CSS, JSON and SVG are gzipped for browsers that accept it (the shared runtime goes from 46 KB to 15 KB); static files are compressed once and kept.
- Memory no longer grows without bound in long-running servers: the rate limiter forgets idle callers, the realtime bus forgets channels quiet for an hour, the in-memory cache drops expired entries, and the job queue forgets jobs an hour after they finish.
- The job queue runs jobs on a pool of 8 threads instead of one thread per job, and
wait()returns as soon as the job finishes. pyweb devno longer re-scans virtualenvs in the project folder every 0.4 s, and reloads whenpyweb.lockchanges (afterpyweb add).
#[0.4.2]
#Added
- VS Code extension: PyWeb: Run App (a run button on
.pywebfiles, Ctrl+F5), New App from any template, Check App, Add npm Package, Install or Update PyWeb and Set Up AI Assistant (MCP), which adds the PyWeb MCP server to.vscode/mcp.json. - VS Code extension: closing tags are added as you type, Emmet works in markup, new snippets (
layout,error,stream,livequery,npm,mount), a status item that shows the PyWeb version in use, and an icon.
#Fixed
- VS Code extension: the language server failed with
spawn python ENOENTwhen no Python interpreter was selected. The extension now looks for a Python with PyWeb (the selected interpreter,pyweb,py,python3,python), offers to install PyWeb when it's missing, and restarts when you change interpreter.
#[0.4.1]
#Added
- MCP server:
pyweb_routesmaps every page (route, path and query parameters with types and defaults, title and head tags, layouts, live-data variables), the layouts, error pages and server functions. - MCP server:
pyweb_packagesadds, removes or lists npm packages for browser code, with each package's exported names and thenpm(...)lines to bind them. - MCP server:
add_ai_featureandmake_data_liveprompts. - MCP server:
pyweb_callreturns every chunk a streaming function yields;pyweb_renderreports the title, head tags and the layouts that rendered;pyweb_checkreports layouts, live variables, npm packages and streaming functions. - The AI guide (
pyweb_guide,AGENTS.md) has sections with working examples for multi-page apps, streaming and AI, live data and npm packages. - A new README with screenshots, and docs on publishing the VS Code extension.
#Fixed
- Markup right after a
defline that ends in a comment (def Page(q: str = ""): # ...) failed to compile.
#[0.4.0]
Apps that are bigger, livelier and smarter: npm packages without Node.js, multi-page apps with layouts and client-side navigation, streaming for AI features, and page data that follows the database.
#Added
- npm packages without Node.js.
pyweb add chart.js/autodownloads a package from the npm registry, checks its sha512 checksum, follows its imports from the browser entry point and copies only the files it needs (and its dependencies) intostatic/vendor/, pinning versions inpyweb.lock.pyweb addwith no arguments reinstalls from the lock;pyweb removetakes a package out. Browser code binds exports withChart = npm("chart.js/auto")ornpm("pkg", "Export"). Calling a class constructs it and keyword arguments become an options object. Each page imports only the packages it uses, through an import map that the Content Security Policy allows by hash. CommonJS-only and Node.js-only packages are refused with an explanation, and an uninstalled package is a compile error that names the command to run. ref={el}sets a page variable to an element, in time foron_mount, for libraries that draw into the page.- Changing an attribute of a package's object (
chart.value = 5) re-renders whatever shows it. - Web components (custom elements from npm) work in markup.
pyweb lsp: hover shows an npm binding's installed version and TypeScript signature; completion offers installed packages innpm("and a module's exports aftername..- New docs page: npm packages.
- Layouts.
@app.layoutwraps every page (or, with@app.layout("/admin"), pages under a prefix) in shared markup;{children}marks where the page goes. Layouts nest, have their own server code, state and handlers, and pages can opt out withlayout=Noneor pick one withlayout="Name". - Client-side navigation. Links between pages fetch the next page's HTML and swap it in below the layouts both pages share, so layout state (an open menu, a player) survives. Links are prefetched on hover or focus, back/forward restore the scroll position, and anything unusual falls back to a full page load.
navigate("/path")frompyweb.browserdoes the same from browser code;on_unmountruns when a page is left;App(client_nav=False)turns it off. - Current links. Links to the current page get
aria-current="page"and links to its parent sectionsaria-current="true", on the server and after each navigation. - Head tags.
@app.page(description=..., image=..., noindex=...)andhead(title=..., description=...)in page code add description, Open Graph and Twitter tags;App(base_url=...)adds canonical URLs and absolute image links. - Error pages in
.pyweb.@app.error(404)/@app.error(500)pages takepath,status,messageorrequest_idand use root layouts. - Typed query parameters. Page parameters that aren't in the route are read from the query string and converted by annotation (
int,float,bool,list[...]); bad or missing values answer 400. - New docs page: Layouts & navigation.
- Streaming server functions. A
@serverfunction thatyields sends each value as it's produced (NDJSON over the same RPC endpoint); browser code reads it withasync for.stream.cancel()or leaving the loop aborts the request and closes the generator on the server, so an upstream AI call stops too. Errors raised part-way arrive asRPCError. Works withasync defgenerators, underpyweb serve,pyweb devand ASGI, andTestClient.rpcreturns the streamed values. <Markdown text={...} />(frompyweb) renders Markdown to safe HTML on the server and updates it in the browser as the text changes, with the same rules in both places. Raw HTML is shown as text and links only accept http(s), mailto and relative URLs.ai-chattemplate and example: a streaming chat with Stop and Markdown replies that talks to Anthropic, any OpenAI-compatible server (OpenAI, Ollama, vLLM, ...) or a built-in demo model, chosen by environment variables.pyweb new NAME --template ai-chat.- New docs page: Building AI apps.
- Live data.
rows = live(db, "select ...", params)in a page or layout renders the rows and keeps them current: writes throughpyweb.db(andpyweb.models) announce their table after commit, each distinct query re-runs once per change (bursts coalesced) and sends rows to every page showing it only when they changed. Pages follow a signed feed;db.notify("table")covers writes made elsewhere. WithRedisBusit works across processes, and any process can take over a query from the page's signed description. - New docs page: Live data.
watch(lambda: value, handler)(frompyweb.browser) runs a handler whenever a value changes, for work outside markup such as redrawing a chart or saving a draft.pyweb addapplies packages'browserfield (browser versions of files, modules turned off), so packages such as ethers install.- New examples: dashboard (live queries and a Chart.js chart from npm), site (layouts, navigation, query parameters, a 404 page) and ai-chat. The playground has the site and AI chat examples.
- New docs page: Recipe: wallets & web3 (wallet sign-in with ethers and eth-account).
- A layout's
{children}can sit on a line of its own.
#Fixed
- Subscriptions and cleanups set up in
on_mountnow end when the page is left (they were never stopped).
#Changed
- The experimental
pyweb.livemodule (in-memory live tables) is nowpyweb.livetable;pyweb.liveis the new live-query function. pyweb.npm(TypeScript declarations to dataclasses) is nowpyweb.dts, and its command ispyweb dts.pyweb buildno longer writes an esm.sh import map; packages come frompyweb.lock.- The default Content Security Policy adds
worker-src 'self' blob:so packages can start Web Workers. - The starter stylesheet styles Markdown and chat bubbles.
- The browser runtime is about 14 KB gzipped (was about 11 KB), for client-side navigation and npm support.
- New website design: a colour system where blue means the browser and amber the server, self-hosted Inter / Bricolage Grotesque / JetBrains Mono, dark code windows, and a landing page that shows each line of an app with where it runs (worked out by the compiler) next to the real compiled output.
- The example apps and the
pyweb newstylesheet use the new palette.
#[0.3.0]
Faster pages that feel like an app, apps that span several files, and tools for editors, the browser and AI assistants.
#Added
- Hydration. Pages now adopt the server-rendered DOM instead of rebuilding it: nodes are kept, focus and text typed before the script loads survive, and typed values reach their variables. When the server HTML doesn't match, the page falls back to a client render and logs a warning. The page root carries
data-pw-mode="hydrated"or"rendered". - Live updates.
publish(name, data)in server code pushes to every page that calledsubscribe(channel_feed, handler), over Server-Sent Events with a polling fallback. Feeds come fromchannel(name)while rendering: signed, expiring, and positioned so no message published after the render is missed.pyweb dev,pyweb serveand the ASGI adapter stream;realtime.use_bus()shares the bus (e.g. Redis) between processes. The chat example uses it instead of polling. - Multi-file apps.
from widgets import Card, save, COLORimports components,@serverfunctions and constants fromwidgets.pyweb(orui/cards.pywebasui.cards). Each file keeps its own names in the generated JavaScript, imported files run as real modules on the server,pyweb buildcopies them intodist/, and errors name the file they're in. Pages stay in the app file; circular imports and duplicate server-function names are compile errors. - Editor support.
pyweb lspis a language server (stdio, standard library only): compile errors and security warnings as you type, hover showing where each name runs and why, completion for components, props and tags, go to definition across files, and an outline. The new VS Code extension (editors/vscode) adds highlighting and snippets and starts it; releases attach a.vsix. Setup for Neovim and Helix is in the command-line docs. - Playground on the website: edit an app and run it in the browser, with the real compiler, server rendering,
@serverfunctions, sessions and live updates running on Pyodide. Shows the compiled JavaScript and what runs where, reports errors with a fix, and shares code as links. - MCP tools
pyweb_screenshot(open a page in headless Chromium, run click/fill/press steps, get a screenshot, the page text, console errors and hydration status) andpyweb_test(run the app's pytest tests and report failures). New apps include a startertest_app.py. python -m pyweb.bench --max-ssr-ms N --max-compile-ms Nfails when a benchmark exceeds its budget; CI runs it.
#Removed
- The old
pyweb.lsphelper functions (complete,DocumentState,complete_*,diagnostics_for_compile_error,hover(compiled, name),boundary_lens); they described an earlier API and no editor used them.
#Changed
import pywebno longer needs thesqlite3module (it's imported when a SQLite database is opened), and password hashing falls back to a pure-Python PBKDF2 on Pythons without OpenSSL. Both make PyWeb run on Pyodide./__pyweb/eventsand/__pyweb/pollrequire a signed?feed=; the unauthenticated?channel=form is gone, so channels are no longer readable by anyone who guesses a name.- Server rendering caches compiled template expressions; rendering a page is about twice as fast.
- Generated page modules pass element children as a function and wrap every child in a call (
$t,$dyn), so nodes are created in document order.
#[0.2.0]
Tools for building PyWeb apps with AI assistants.
#Added
pyweb mcp: a Model Context Protocol server (stdio, standard library only) for Claude Code, Cursor, Claude Desktop, VS Code and other MCP clients. Tools:pyweb_guide,pyweb_new_app,pyweb_check(errors with line numbers and fix hints),pyweb_inspect,pyweb_compiled,pyweb_renderandpyweb_call(session cookies persist between calls); resources for the guide and templates; abuild_pyweb_appprompt. Tested against the official MCP Python SDK.- An AI-oriented guide to writing
.pywebapps, shipped in the package. pyweb new --template blank|counter|todo|blog|auth|chat; new projects includeAGENTS.mdandCLAUDE.mdfor coding agents.- The docs site publishes
llms.txtandllms-full.txt, and has a new "AI assistants & MCP" page.
#[0.1.0]
The first public release, published on PyPI as pyweb-stack. The unpublished prototype was labelled "1.0" but only the simplest counter pattern worked in a browser; this release rebuilds the compiler, runtime and server around a design that works end to end, and is verified in a real browser.
#Language and compiler
.pywebparser with a character scanner: tags and expressions may span lines, braces and strings nest inside{...},elifchains, HTML comments, and exact line numbers (the Python half keeps the source's line count; this also fixes crashes on Python 3.10/3.11).- Python → JavaScript translation of a documented subset with Python semantics (truthiness,
==on containers, negative indexing, floor division/modulo, string/list/dict/set methods, Python exceptions). Unsupported code is a compile error withfile:line. Verified differentially against CPython. - State inference: signals (mutated by handlers or bound), computeds, constants; initial values from literals, the browser, or the server. Mutations (
append, item assignment,del, …) are copy-on-write. - Components with props, defaults and
children;on_mounthook; page titles;App(title=, stylesheets=, lang=). @servercalls from handlers compile to awaited typed RPC; async propagates through handler calls.- Only values browser code reads are serialised; values derived from server data are computed on the server. Secret-looking names read by browser code are rejected.
#Runtime
- New browser runtime: dependency-tracked signals, cached computeds, owned effects with disposal, batching; keyed lists and conditionals in marker-bounded regions; two-way binding for text, number, checkbox, radio and select;
javascript:URL blocking; RPC client with typed errors.
#Server
- Pages render per request with real server values;
request,session,redirect,NotFound; typed route parameters. @serverfunctions are registered automatically indev,serve, tests and ASGI.- New ASGI adapter:
pyweb.asgi.create_app. - RPC: JSON-only and same-origin checks, rate limiting, timeouts that actually return on time, async functions, JSON conversion for dataclasses/datetimes/Decimals.
- Content-Security-Policy and security headers on HTML responses.
#Tooling
pyweb dev: live reload and an in-browser compile-error overlay.pyweb buildproduces a self-containeddist/(source, manifest with gzip sizes, hashed assets, working Dockerfile);pyweb serveruns it.- Token-aware JS minifier (the previous one altered string literals).
pyweb.testing.TestClientandpyweb.testing.servefor tests.- Clean
file:line: messagecompile errors from the CLI.
#Data, auth, jobs
?placeholders work on Postgres and MySQL; lazy connection pools.- WebAuthn: challenge, origin and sign-count checks; DER signatures; uses
cryptographywhen installed. - Redis bus and queue work against real Redis.
#Fixed
- Migrations: the
pyweb_migrationsjournal table can now be created on MySQL (VARCHAR(255)key instead ofTEXT). pyweb servecrashed on startup (logger misconfiguration).- Production builds referenced a hashed runtime the page modules never imported.
- Installed packages were missing the browser runtime file.
transaction()did not roll back on Postgres/MySQL pools.sqlite:///file.dbpointed at the filesystem root.RedisBus.since()duplicated and mis-ordered messages;RedisQueue.drain(timeout=0)blocked forever.- Jobs raising
TypeErrorran twice. Query.order_by()ignored-fieldand did not validate a single field.- The deploy Dockerfile ran a non-existent
serve --dirflag.
#Removed
- Modules the framework no longer uses:
pyweb.components(pure-Python element API),pyweb.routing(unused router),pyweb.reactive(server-sideSignal/Computed/Effect/live), andpyweb.compiler.placement(superseded by the compiler's boundary checks). - The
@browserand@shareddecorators, which had no effect. pyweb.compiler.rpc.client_stub/server_handlerand unused AST classes.docs/BUGLOG.md(it described the prototype's internals) and the committedwebsite/dist/; the Pages workflow builds the site.- The regex-based codegen, the virtual test client that only recorded clicks, documentation "snippets" that did not use PyWeb, island and streaming-SSR string helpers without runtime support, and the no-op
--security-scanflag.
#Pre-release prototype (unpublished)
- Initial prototype.