pyweb-stack 0.6.2__py3-none-any.whl → 0.6.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. pyweb/__init__.py +8 -9
  2. pyweb/a11y.py +52 -0
  3. pyweb/ai/docs/02-quickstart.md +5 -0
  4. pyweb/ai/docs/08-pages-routing-assets.md +40 -0
  5. pyweb/ai/docs/11-testing.md +30 -0
  6. pyweb/ai/docs/12-deployment.md +7 -0
  7. pyweb/ai/docs/14-cli.md +7 -4
  8. pyweb/ai/docs/16-limitations-roadmap.md +22 -3
  9. pyweb/ai/docs/18-npm-packages.md +4 -0
  10. pyweb/ai/docs/23-forms.md +29 -2
  11. pyweb/ai/docs/27-upgrading.md +26 -0
  12. pyweb/ai/docs/29-performance.md +36 -0
  13. pyweb/ai/docs/32-desktop.md +4 -0
  14. pyweb/ai/docs/34-ui-and-motion.md +21 -1
  15. pyweb/ai/docs/35-dev-loop.md +25 -0
  16. pyweb/ai/docs/36-routes.md +130 -0
  17. pyweb/ai/docs/37-i18n.md +90 -0
  18. pyweb/ai/docs/THREAT_MODEL.md +24 -11
  19. pyweb/ai/guide.md +16 -0
  20. pyweb/app.py +70 -7
  21. pyweb/app_loader.py +21 -2
  22. pyweb/asgi.py +3 -0
  23. pyweb/auth.py +10 -3
  24. pyweb/authkit/__init__.py +12 -6
  25. pyweb/authkit/admin.py +23 -1
  26. pyweb/authkit/oauth.py +1 -1
  27. pyweb/authkit/pages.py +17 -11
  28. pyweb/bench.py +3 -3
  29. pyweb/browser.py +29 -0
  30. pyweb/build.py +11 -6
  31. pyweb/cache.py +43 -16
  32. pyweb/checks.py +111 -0
  33. pyweb/cli/__init__.py +124 -430
  34. pyweb/compiler/diskcache.py +21 -2
  35. pyweb/compiler/lower.py +59 -1
  36. pyweb/compiler/pipeline.py +18 -1
  37. pyweb/compiler/pyjs.py +7 -0
  38. pyweb/config.py +20 -1
  39. pyweb/context.py +51 -10
  40. pyweb/csp.py +60 -0
  41. pyweb/db/__init__.py +112 -16
  42. pyweb/db/migrate.py +1 -1
  43. pyweb/db/rls.py +22 -13
  44. pyweb/desktop/gate.py +1 -1
  45. pyweb/desktop/shell.py +2 -2
  46. pyweb/devlink.py +2 -2
  47. pyweb/devserver.py +389 -0
  48. pyweb/doctor.py +1 -1
  49. pyweb/errorboundary.py +22 -0
  50. pyweb/forms.py +45 -15
  51. pyweb/hosting.py +42 -3
  52. pyweb/htmlquery.py +143 -0
  53. pyweb/http.py +7 -0
  54. pyweb/i18n.py +437 -0
  55. pyweb/images.py +113 -0
  56. pyweb/jobs/redis.py +21 -13
  57. pyweb/jobs/worker.py +35 -3
  58. pyweb/livedata.py +41 -11
  59. pyweb/lsp.py +39 -1
  60. pyweb/lsp_refs.py +280 -0
  61. pyweb/mcp.py +43 -198
  62. pyweb/mcp_http.py +33 -3
  63. pyweb/mcp_tools.py +1 -1
  64. pyweb/models/__init__.py +11 -0
  65. pyweb/models/query.py +16 -0
  66. pyweb/net/http.py +12 -0
  67. pyweb/net/server.py +69 -16
  68. pyweb/openapi.py +50 -0
  69. pyweb/pagecache.py +144 -0
  70. pyweb/plugins.py +12 -2
  71. pyweb/push.py +25 -9
  72. pyweb/realtime.py +26 -21
  73. pyweb/redisutil.py +65 -0
  74. pyweb/routes.py +408 -0
  75. pyweb/rpc.py +26 -21
  76. pyweb/runtime/browser/boundary.js +48 -0
  77. pyweb/runtime/browser/forms.js +133 -5
  78. pyweb/runtime/browser/i18n.js +42 -0
  79. pyweb/runtime/browser/pwa.js +1 -1
  80. pyweb/runtime/browser/runtime.js +5 -4
  81. pyweb/runtime/browser/ui/index.js +1 -1
  82. pyweb/runtime/browser/ui/stepper.js +99 -0
  83. pyweb/runtime/server/__init__.py +141 -33
  84. pyweb/scaffold.py +212 -0
  85. pyweb/security.py +39 -0
  86. pyweb/serve.py +6 -63
  87. pyweb/share.py +5 -4
  88. pyweb/sourcemap.py +79 -0
  89. pyweb/ssr.py +30 -5
  90. pyweb/ssr_codegen.py +2 -0
  91. pyweb/storage.py +13 -8
  92. pyweb/telemetry/devtools.py +4 -8
  93. pyweb/telemetry/instruments.py +2 -0
  94. pyweb/testing.py +79 -0
  95. pyweb/ui/kit/data.pyweb +35 -4
  96. pyweb/ui/kit/image.pyweb +32 -0
  97. pyweb/ui/kit/stepper.pyweb +39 -0
  98. pyweb/ui/static/ui.css +20 -0
  99. pyweb/upgrade.py +12 -0
  100. pyweb/webhooks.py +8 -5
  101. {pyweb_stack-0.6.2.dist-info → pyweb_stack-0.6.3.dist-info}/METADATA +6 -2
  102. {pyweb_stack-0.6.2.dist-info → pyweb_stack-0.6.3.dist-info}/RECORD +106 -86
  103. {pyweb_stack-0.6.2.dist-info → pyweb_stack-0.6.3.dist-info}/WHEEL +0 -0
  104. {pyweb_stack-0.6.2.dist-info → pyweb_stack-0.6.3.dist-info}/entry_points.txt +0 -0
  105. {pyweb_stack-0.6.2.dist-info → pyweb_stack-0.6.3.dist-info}/licenses/LICENSE +0 -0
  106. {pyweb_stack-0.6.2.dist-info → pyweb_stack-0.6.3.dist-info}/top_level.txt +0 -0
pyweb/__init__.py CHANGED
@@ -19,13 +19,15 @@ _LAZY = {
19
19
  "channel": (".realtime", "channel"), "publish": (".realtime", "publish"), "subscribe": (".realtime", "subscribe"),
20
20
  "npm": (".packages", "npm"),
21
21
  "Markdown": (".markdown", "Markdown"),
22
+ "ErrorBoundary": (".errorboundary", "ErrorBoundary"),
23
+ "_": (".i18n", "gettext"), "gettext": (".i18n", "gettext"), "ngettext": (".i18n", "ngettext"),
22
24
  "Checkbox": (".forms", "Checkbox"), "FileInput": (".forms", "FileInput"), "Form": (".forms", "Form"),
23
25
  "FormError": (".forms", "FormError"), "Input": (".forms", "Input"), "Select": (".forms", "Select"),
24
26
  "Submit": (".forms", "Submit"), "Textarea": (".forms", "Textarea"), "UploadedFile": (".forms", "UploadedFile"),
25
27
  "live": (".livedata", "live"),
26
28
  "browser_api": (".browser", None),
27
29
  }
28
- _SUBMODULES = {"auth", "cache", "jobs", "realtime", "security", "observability", "forms", "testing", "sync",
30
+ _SUBMODULES = {"i18n", "auth", "cache", "jobs", "realtime", "security", "observability", "forms", "testing", "sync",
29
31
  "deploy", "uploads", "lsp", "livetable", "build", "css", "plugins", "platform"}
30
32
 
31
33
 
@@ -68,6 +70,9 @@ __all__ = [
68
70
  "subscribe",
69
71
  "npm",
70
72
  "Markdown",
73
+ "ErrorBoundary",
74
+ "gettext",
75
+ "ngettext",
71
76
  "Form",
72
77
  "Input",
73
78
  "Textarea",
@@ -93,17 +98,11 @@ __all__ = [
93
98
  "observability",
94
99
  "forms",
95
100
  "testing",
96
- "sync",
97
- "livetable",
98
- "deploy",
99
- "uploads",
100
- "lsp",
101
101
  "browser_api",
102
- "build",
103
- "css",
104
- "plugins",
105
102
  "platform",
106
103
  ]
104
+ # Also importable from `pyweb` but not part of `from pyweb import *` (tooling, or still experimental):
105
+ # sync, livetable, deploy, uploads, lsp, build, css, plugins.
107
106
 
108
107
  def _version():
109
108
  """Single source of truth: installed dist metadata, else pyproject."""
pyweb/a11y.py CHANGED
@@ -119,3 +119,55 @@ def check(text, path=None):
119
119
  return []
120
120
  found = sorted(lint_ui(ui) + lint_app(tree))
121
121
  return [{"kind": "a11y-" + rule, "line": line, "message": msg} for line, rule, msg in found]
122
+
123
+
124
+ # ------------------------------------------------------------------ rendered pages
125
+
126
+ def check_html(html):
127
+ """The same rules on a rendered page (what the markup became, components included): a list of
128
+ ``{"rule", "element", "message"}``. ``TestClient.a11y(path)`` calls it."""
129
+ from .htmlquery import Node, parse
130
+ doc = parse(html)
131
+ out = []
132
+
133
+ def report(rule, node, message):
134
+ out.append({"rule": rule, "element": f"<{node.tag}{' id=' + node.attrs['id'] if 'id' in node.attrs else ''}>",
135
+ "message": message})
136
+
137
+ def named(node, by=NAMED_BY):
138
+ return bool(node.text or any((node.attrs.get(a) or "").strip() for a in by)
139
+ or any(isinstance(c, Node) and c.tag == "img" and (c.attrs.get("alt") or "").strip()
140
+ for c in node.children))
141
+
142
+ html_el = doc.find("html")
143
+ if html_el is not None and not (html_el.attrs.get("lang") or "").strip():
144
+ report("html-lang", html_el, "the page has no language: <html lang=\"en\">")
145
+ labelled = {n.attrs.get("for") for n in doc.find_all("label") if n.attrs.get("for")}
146
+ for img in doc.find_all("img"):
147
+ if "alt" not in img.attrs and img.attrs.get("role") != "presentation":
148
+ report("img-alt", img, "image without alt= (alt=\"\" if it's decoration)")
149
+ for field in doc.find_all("input, select, textarea"):
150
+ if field.tag == "input" and (field.attrs.get("type") or "text") in UNLABELLED_TYPES:
151
+ continue
152
+ inside_label, p = False, field.parent
153
+ while p is not None:
154
+ if p.tag == "label":
155
+ inside_label = True
156
+ break
157
+ p = p.parent
158
+ if not (inside_label or field.attrs.get("id") in labelled
159
+ or any((field.attrs.get(a) or "").strip() for a in FIELD_NAMED_BY)):
160
+ report("label", field, "form field without a label (<label for=...>, or aria-label=)")
161
+ for b in doc.find_all("button"):
162
+ if not named(b):
163
+ report("button-name", b, "button without a name: text inside, or aria-label=")
164
+ for a in doc.find_all("a[href]"):
165
+ if not named(a):
166
+ report("link-name", a, "link without a name: text inside, or aria-label=")
167
+ for n in doc.find_all("[tabindex]"):
168
+ try:
169
+ if int(n.attrs["tabindex"]) > 0:
170
+ report("tabindex", n, "positive tabindex changes the keyboard order: use 0 or -1")
171
+ except ValueError:
172
+ pass
173
+ return out
@@ -87,9 +87,14 @@ page Home("/") signals ['count'] rpc []
87
87
  ```bash
88
88
  pyweb check app.pyweb # compile, security and accessibility checks (CI-friendly)
89
89
  pyweb build app.pyweb --out dist --production # hashed, minified, deployable dist/
90
+ export PYWEB_AUTH_SECRET=$(python -c "import secrets; print(secrets.token_hex(32))")
90
91
  pyweb serve dist # production server with /healthz
91
92
  ```
92
93
 
94
+ `pyweb serve` needs `PYWEB_AUTH_SECRET` (it signs sessions, CSRF tokens and
95
+ links) and won't start without it; `PYWEB_ENV=development pyweb serve dist`
96
+ tries a build locally without one.
97
+
93
98
  `dist/` contains your app source, static assets and a `Dockerfile`; see
94
99
  [Deployment](12-deployment.md).
95
100
 
@@ -151,6 +151,46 @@ def Broken(request_id):
151
151
  traceback for 500s; `pyweb serve` shows your page.
152
152
  - If an error page itself fails, the built-in page is used.
153
153
 
154
+ ### One broken part, not a broken page
155
+
156
+ Wrap a part that may fail (a chart from a flaky service, a widget with complex logic) in
157
+ `<ErrorBoundary>`:
158
+
159
+ ```pyweb
160
+ from pyweb import App, ErrorBoundary
161
+
162
+ app = App()
163
+
164
+
165
+ def RevenueChart(data: list):
166
+ <ol class="chart">
167
+ for point in data:
168
+ <li style={{"--v": point["value"]}}>{point["label"]}</li>
169
+ </ol>
170
+
171
+
172
+ def load_stats():
173
+ return {"revenue": [{"label": "May", "value": 12}, {"label": "June", "value": 15}]}
174
+
175
+
176
+ @app.page("/dashboard")
177
+ def Dashboard():
178
+ stats = load_stats()
179
+ <h1>Dashboard</h1>
180
+ <ErrorBoundary fallback="The revenue chart couldn't load.">
181
+ <RevenueChart data={stats["revenue"]} />
182
+ </ErrorBoundary>
183
+ <p>Orders and the rest of the page keep working if the chart fails.</p>
184
+ ```
185
+
186
+ - On the server, if rendering what's inside raises, the page is sent with the fallback in its place
187
+ (and the error is reported like any page error).
188
+ - In the browser, if code inside throws (while the page starts, or in a click or input handler and
189
+ what it changes), that part is replaced by the fallback and a Reload button; the rest of the page
190
+ keeps working.
191
+ - `NotFound` and bad query parameters still answer for the whole page. The code that runs before the
192
+ markup (`stats = load_stats()` above) isn't inside the boundary: catch errors there yourself.
193
+
154
194
  ## Responses other than HTML
155
195
 
156
196
  Return `redirect(url)` from a page to send `303 See Other`. Raise
@@ -41,6 +41,36 @@ def test_notes():
41
41
  | `.cookies` | the cookie jar |
42
42
  | `.app.module` | the executed app module, for direct access to its objects |
43
43
 
44
+ ### Looking inside pages and components
45
+
46
+ ```python
47
+ from pyweb.testing import TestClient, assert_snapshot
48
+
49
+
50
+ def test_todos(client):
51
+ r = client.get("/")
52
+ assert [li.text for li in r.find_all("ul.todos li")] == ["milk", "bread"]
53
+ assert r.find("li.done").text == "milk"
54
+
55
+ badge = client.render("Badge", label="new", tone="warn") # one component, with props
56
+ assert badge.find("span").classes == ["badge", "warn"]
57
+
58
+ assert client.a11y("/") == [] # accessibility of the rendered page
59
+
60
+ assert_snapshot(r.find("main").text, "home-text") # __snapshots__/home-text.txt
61
+ ```
62
+
63
+ - `find` / `find_all` take CSS selectors: `tag`, `#id`, `.class`, `[attr]`, `[attr=value]`, combined
64
+ (`button.primary[disabled]`), descendants (`ul li`) and lists (`h1, h2`). Elements have `.text`
65
+ (what a person reads), `.attrs`, `.get(name)` and `.classes`.
66
+ - `client.render(name, **props)` renders a component (or a page) on its own, in a request, so
67
+ `session` works.
68
+ - `client.a11y(path)` runs the accessibility rules on what the page became (components included):
69
+ images without `alt`, fields without a label, buttons and links without a name, positive
70
+ `tabindex`, a missing page language. An empty list is a pass.
71
+ - `assert_snapshot(value, name)` compares with `__snapshots__/<name>.txt` next to the test (written
72
+ the first time). After a change you meant, run the tests with `PYWEB_UPDATE_SNAPSHOTS=1`.
73
+
44
74
  ## Apps with accounts, data and jobs
45
75
 
46
76
  For an app with a database, give each test its own: change into
@@ -227,6 +227,13 @@ across processes use `RedisCache`, and for
227
227
  | `PYWEB_REDIS_URL` | unset | share rate limits and live updates between server processes |
228
228
  | `PYWEB_MAX_CONNECTIONS` | `10000` | simultaneous connections per server process (`503` beyond) |
229
229
  | `PYWEB_THREADS` | `32` | threads per process rendering pages and running server functions |
230
+ | `PYWEB_DB_POOL` | `10` | database connections each process may open (keep `workers × pool` under the server's limit) |
231
+ | `PYWEB_MAX_QUEUE` | `256` | requests waiting for a thread before new ones get `503` with `Retry-After` |
232
+ | `PYWEB_SHUTDOWN_TIMEOUT` | `25` | seconds to finish requests and jobs after `SIGTERM` |
233
+ | `PYWEB_MIGRATE_ON_START` | unset | `1`: apply pending migrations when the server starts (same as `pyweb serve --migrate`) |
234
+ | `PYWEB_WORKER_HEARTBEAT` | temp dir | file `pyweb worker` touches every round (point a container health check at it) |
235
+ | `PYWEB_METRICS_EVERY` | `5` | seconds between each worker process writing its metrics for `/metrics` (with `--workers`) |
236
+ | `PYWEB_STRICT_RELATIONS` | on outside production | reading a relation you didn't `include()` is an error (`1`) or a logged warning (`0`) |
230
237
  | `PYWEB_ALLOWED_ORIGINS` | unset | other origins allowed to open the pages' WebSocket (comma-separated); by default only the site itself |
231
238
  | `WEB_CONCURRENCY` | `1` | worker processes for `pyweb serve` (same as `--workers`) |
232
239
  | `PYWEB_WORKER` | `1` | `0`: don't run background jobs inside the web server (run `pyweb worker` processes; see [Background jobs](24-jobs.md)) |
pyweb/ai/docs/14-cli.md CHANGED
@@ -7,7 +7,7 @@ pyweb new [NAME] [--template T] [--theme PRESET]
7
7
  (apps with a database also get migrations/0001_initial.py and a README);
8
8
  PRESET = indigo | zinc | slate | rose | ocean | violet | emerald | amber
9
9
  (written into App(theme=...)); with no NAME, in a terminal, it asks
10
- pyweb dev FILE [--port 8000] [--host 127.0.0.1] [--no-reload] [--no-open] [--share]
10
+ pyweb dev FILE [--port 8000] [--host 127.0.0.1] [--no-reload] [--no-open] [--share] [--debug [--debug-port 5678] [--wait]]
11
11
  development server (see The dev loop): saves update the open page
12
12
  in place, keeping page and component state (?fresh starts over);
13
13
  Alt-click opens an element's line in your editor, Alt+Shift-click
@@ -28,10 +28,11 @@ pyweb doctor [FILE] [--production] [--json] [--port 8000]
28
28
  pyweb upgrade [FILE] [--fix] what to change for this PyWeb version (file and line); --fix applies
29
29
  the safe rewrites
30
30
  pyweb inspect FILE [--security] where every name runs and why; RPC table; findings
31
- pyweb build FILE [--out dist] [--production] [--budget PATH=SIZE ...]
31
+ pyweb build FILE [--out dist] [--production] [--sourcemaps] [--budget PATH=SIZE ...]
32
32
  self-contained dist/; --production hashes and minifies
33
33
  pyweb serve [DIR] [--host 0.0.0.0] [--port $PORT|8000] [--workers N] [--migrate]
34
- production server for a built dist/ (N processes)
34
+ production server for a built dist/ (N processes);
35
+ needs PYWEB_AUTH_SECRET (or PYWEB_ENV=development)
35
36
  pyweb ui list | add NAME... [--force] | diff NAME [--dir .]
36
37
  the UI kit's components; copy one into components/ to change
37
38
  it; show how your copy differs from the kit
@@ -76,8 +77,10 @@ pyweb add [PKG[@RANGE] ...] [--app DIR]
76
77
  and pin them in pyweb.lock; no arguments: reinstall from the lock
77
78
  pyweb remove PKG ... [--app DIR] remove npm packages (see npm packages)
78
79
  pyweb dts FILE.d.ts Python dataclasses from TypeScript declarations
80
+ pyweb i18n extract | init LANG | check [--strict] [--app app.pyweb]
81
+ translation catalogs in locales/ (see Translations)
79
82
  pyweb mcp MCP server over stdio for AI assistants (see AI assistants & MCP)
80
- pyweb mcp --http [--port 8765] [--token T] the same over Streamable HTTP (127.0.0.1 only without a token)
83
+ pyweb mcp --http [--port 8765] [--token T] the same over Streamable HTTP (always with a bearer token)
81
84
  pyweb lsp language server over stdio for editors (see below)
82
85
  pyweb test [PATH] run pytest on PATH (a test file, a folder or app.pyweb's folder;
83
86
  default: the current folder, where new apps keep test_app.py)
@@ -40,7 +40,11 @@ can decide up front whether they matter for your app.
40
40
  saves update the page in place with component state kept, Alt-click
41
41
  opens any element's source, Fix with AI and Edit with AI, a
42
42
  time-travel timeline, `pyweb dev --share`, a faster first start and a
43
- guided `pyweb new`.
43
+ guided `pyweb new`. 0.6.3 was a security and reliability release plus
44
+ what apps missed most: HTTP routes and middleware, page caching with
45
+ ETags, translations, `<ErrorBoundary>`, test helpers, source maps and
46
+ `pyweb dev --debug`, CSV export, drag-and-drop uploads, a `Stepper`,
47
+ responsive `<Image>`, and rename and find-references in the editor.
44
48
  - **0.5**: production apps. Models with relations and migrations, forms
45
49
  checked in the browser and on the server, an auth kit (passwords,
46
50
  passkeys, emailed links, OAuth, two-step sign-in, an admin), row-level
@@ -70,8 +74,23 @@ Planned, roughly in order. Nothing here is promised for a date.
70
74
 
71
75
  1. **1.0**: the API, RPC protocol and CLI frozen under semantic versioning,
72
76
  after 0.6 has been used in production for a while.
73
- 2. **File uploads from the playground and the admin.**
74
- 3. **Fix with AI in the editor**, from the same proposals the dev page
77
+ 2. **0.7: the next things apps ask for.**
78
+ - Billing: Stripe Checkout and the customer portal, plans tied to the
79
+ organization's features, webhooks handled for you.
80
+ - An in-app notifications center (a bell, unread counts, live), with
81
+ email and push from the same call.
82
+ - Full-text search on Models (SQLite FTS5, Postgres `tsvector`, MySQL
83
+ `FULLTEXT`) behind one `Model.search()`.
84
+ - A rich-text editor component whose output is sanitized on the server.
85
+ - Feature flags and A/B tests per user or organization.
86
+ - Streaming server rendering: `<Await>` sends the page shell first and
87
+ slow parts as they finish.
88
+ - Pages built ahead of time from data, rebuilt on a schedule or on a
89
+ write (incremental static regeneration).
90
+ - `pyweb typecheck`: pyright over the Python in `.pyweb` files.
91
+ - Admin customization per Model: list columns, filters, actions, forms.
92
+ 3. **File uploads from the playground.**
93
+ 4. **Fix with AI in the editor**, from the same proposals the dev page
75
94
  shows (diff, apply, undo), through the VS Code extension.
76
95
 
77
96
  Ideas, bug reports and pull requests are welcome; see
@@ -208,3 +208,7 @@ their URLs include the version.
208
208
  Trusted Types rule the others have (many libraries write `innerHTML`
209
209
  themselves); the rest of the policy still applies. See
210
210
  [Security](13-security.md#cross-site-scripting).
211
+
212
+
213
+ `PYWEB_NPM_REGISTRY` points `pyweb add` at another registry (a mirror or a private one); the default is
214
+ `https://registry.npmjs.org`.
pyweb/ai/docs/23-forms.md CHANGED
@@ -160,7 +160,14 @@ class User(Model):
160
160
  `storage.url(user.avatar)` (from `pyweb`) gives a link.
161
161
  - A form with no new file keeps the old one.
162
162
  - Plain parameters can take the file itself: `def upload(doc: UploadedFile)`
163
- (`.filename`, `.content_type`, `.size`, `.data`, `.save()`).
163
+ (`.filename`, `.content_type`, `.size`, `.data`, `.save()`), or several:
164
+ `def upload(photos: list[UploadedFile])` makes the input `multiple` and
165
+ gives a list (empty when nothing was chosen).
166
+
167
+ With JavaScript, files can be dropped on the field, the chosen ones are
168
+ listed under it (a preview for images, a Remove button each), and a bar
169
+ shows how much of the upload has been sent. Dropped files that don't match
170
+ `accept=` are left out.
164
171
 
165
172
  Where files go is set by `PYWEB_STORAGE`:
166
173
 
@@ -175,7 +182,27 @@ bucket.
175
182
 
176
183
  ## Multi-step forms
177
184
 
178
- Carry earlier steps' answers in a signed hidden value:
185
+ In one page, the UI kit's `Stepper` shows one step at a time and checks a
186
+ step's fields before moving on:
187
+
188
+ ```
189
+ from pyweb.ui import Stepper, Step
190
+
191
+ <Form action={sign_up}>
192
+ <Stepper submit="Create account">
193
+ <Step title="Account">
194
+ <Input name="email" />
195
+ </Step>
196
+ <Step title="Profile">
197
+ <Input name="name" />
198
+ </Step>
199
+ </Stepper>
200
+ </Form>
201
+ ```
202
+
203
+ The whole form is still one submit, checked again on the server; an error
204
+ on an earlier step's field takes you back to it. Across pages, carry
205
+ earlier steps' answers in a signed hidden value:
179
206
 
180
207
  ```python
181
208
  from pyweb import forms
@@ -13,6 +13,32 @@ pyweb check app.pyweb
13
13
  pytest
14
14
  ```
15
15
 
16
+ ## From 0.6.2 to 0.6.3
17
+
18
+ 0.6.3 closes security gaps, and three of the fixes can change how an
19
+ existing app behaves. `pyweb upgrade --check` points at each one.
20
+
21
+ - **`pyweb serve` needs a secret.** It refuses to start without
22
+ `PYWEB_AUTH_SECRET` (`python -c "import secrets; print(secrets.token_hex(32))"`
23
+ makes one); set `PYWEB_ENV=development` to run a local server without
24
+ one. Guarded server functions are refused when there's no secret instead
25
+ of running unchecked. Sessions made with the old derived development key
26
+ end once.
27
+ - **Postgres tenant tables** get a new row-level security policy
28
+ (`pyweb_tenant_v2`) that shows no rows to a connection that never set
29
+ the organization. Apps that create tables get it on start; with
30
+ migrations, run `pyweb db diff` and `pyweb db upgrade`.
31
+ - **Forms** carry a signed list of the fields they rendered. A page
32
+ rendered by 0.6.2 and submitted after the upgrade gets "reload the page"
33
+ once. A field your server function fills in without an input on the form
34
+ must now be set in the function.
35
+ - An option in `@app.page(...)` that isn't written as a value
36
+ (`login=NEEDS_LOGIN`) is a compile error; write the value itself.
37
+
38
+ Everything new (routes, `cache=`, translations, `<ErrorBoundary>`,
39
+ `Stepper`, `<Image>`) is opt-in. Update the VS Code extension to 0.6.3 for
40
+ rename, find references and quick fixes.
41
+
16
42
  ## One migration, for apps with accounts
17
43
 
18
44
  0.6 lists each signed-in device on `/account`, so people can sign one out.
@@ -77,6 +77,42 @@ threads meet. Your server functions are just Python, so module-level
77
77
  state you change from several requests at once needs a lock there too,
78
78
  the same as with threads on any Python.
79
79
 
80
+ ## Caching pages
81
+
82
+ Every page answered `200` gets an `ETag`. A browser coming back with it gets `304 Not Modified`
83
+ and no body; pages that are the same for everyone are sent with `Cache-Control: no-cache` (keep,
84
+ but check first) instead of `no-store`.
85
+
86
+ For pages many people read and few change, keep the rendered HTML:
87
+
88
+ ```python
89
+ @app.page("/pricing", cache=300)
90
+ def Pricing():
91
+ plans = Plan.where(public=True).order_by("price")
92
+ ...
93
+
94
+
95
+ @app.page("/docs/{slug}", cache=3600, vary=["accept-language"])
96
+ def Doc(slug: str):
97
+ ...
98
+ ```
99
+
100
+ The first visitor's render is kept for up to `cache` seconds and reused for everyone after, sent
101
+ with `Cache-Control: public, max-age=...` so a CDN can keep it too. `vary=` keeps one copy per
102
+ value of `"accept-language"`, `"cookie:NAME"` or `"header:NAME"`; the path and query string are
103
+ always part of the key.
104
+
105
+ Only what's the same for everyone is kept:
106
+
107
+ - a visitor with a session cookie (or an `Authorization` header) always gets a fresh render;
108
+ - a render that read the session, set a cookie (a `<Form>` sets its CSRF cookie), showed a toast
109
+ or opened a live feed (`channel()`, `live()`) isn't stored.
110
+
111
+ A copy is dropped as soon as the process writes to a table the page read while rendering (PyWeb
112
+ watches the queries), or with `pyweb.pagecache.invalidate("/pricing")` (`invalidate()` drops
113
+ them all). With `PYWEB_REDIS_URL` the copies live in Redis, shared by every server process.
114
+ `pyweb dev` never uses them.
115
+
80
116
  ## Finding the slow part of your app
81
117
 
82
118
  ### The dev toolbar
@@ -188,3 +188,7 @@ Unsigned apps work, but the OS warns people before opening them.
188
188
  apps; desktop apps use `desktop.notify()`.
189
189
  - On Linux, pywebview needs WebKitGTK (`gir1.2-webkit2-4.1`) or Qt
190
190
  WebEngine (`pip install "pywebview[qt6]"`).
191
+
192
+
193
+ `PYWEB_AUTHOR` and `PYWEB_AUTHOR_EMAIL` fill in the package's author when `pyweb build --desktop --package`
194
+ isn't given `--author` / `--author-email`.
@@ -97,6 +97,8 @@ Everything is a CSS variable, so plain CSS can change any of it:
97
97
  | `Separator` | `orientation`, `decorative` |
98
98
  | `Skeleton` | `width`, `height`, `radius` |
99
99
  | `Kbd`, `Label`, `Avatar` (`src`, `alt`, `fallback`, `size`), `AspectRatio` (`ratio`), `Progress` (`value`, `max`, `label`) | |
100
+ | `Image` | `src`, `alt` (required), `width`, `height`, `sizes`, `priority`. See [Images](#images) |
101
+ | `Stepper`, `Step` | a form in steps: `Step(title=)`; `Stepper(submit=, next=, back=, default=)`. See [Forms](23-forms.md#multi-step-forms) |
100
102
 
101
103
  The form tags (`<Form>`, `<Input>`, `<Textarea>`, `<Select>`,
102
104
  `<Checkbox>`, `<Submit>`, from `pyweb`) are styled by the kit too.
@@ -322,10 +324,28 @@ Search, sorting (click a header: ascending, descending, off), pages
322
324
  and row selection all run in the browser; the first page is rendered on
323
325
  the server. `rows` is a list of dicts. A live query works: the table
324
326
  follows it. `onselect(keys)` gets the `key` (default `"id"`) of every
325
- selected row. For a plain styled table there are `Table` (`caption`),
327
+ selected row. `export="csv"` adds a "Download CSV" button: the rows that
328
+ match the search, in the table's order (`filename="tasks.csv"`); the
329
+ admin has the same per Model, and a route can send one with
330
+ `pyweb.routes.csv(rows)`. For a plain styled table there are `Table` (`caption`),
326
331
  `TableHeader`, `TableBody`, `TableFooter`, `TableRow` (`selected`),
327
332
  `TableHead` and `TableCell` (`align`).
328
333
 
334
+ ### Images
335
+
336
+ ```html
337
+ <Image src="/static/team.jpg" alt="The team at the offsite" width={800} height={450} />
338
+ ```
339
+
340
+ `width` and `height` are the size it shows at, so the page doesn't jump
341
+ while it loads. For a file in `static/`, the browser gets a `srcset` of
342
+ smaller copies (320 to 2560 pixels wide) and picks the one that fits the
343
+ screen; the server makes them on first request with Pillow
344
+ (`pip install "pyweb-stack[images]"`), never larger than the original and
345
+ without the photo's metadata (camera, location), and keeps them in memory.
346
+ Without Pillow the original is sent. Images load when scrolled to;
347
+ `priority={True}` loads the first big image of a page at once.
348
+
329
349
  ### Charts
330
350
 
331
351
  ```html
@@ -136,6 +136,23 @@ hot reload, never your tools: no toolbar (it shows SQL and request
136
136
  data), inspector, AI help, editor opening or theme saving. Those
137
137
  answer only requests from your machine to `localhost`.
138
138
 
139
+ ## Debugging
140
+
141
+ `pyweb dev --debug` starts `debugpy` (`pip install debugpy`) on `127.0.0.1:5678` (`--debug-port` to
142
+ change it; `--wait` waits for the debugger before serving). Attach from VS Code with **Python
143
+ Debugger: Remote Attach** (or PyCharm's remote debugger) and set breakpoints in the `.pyweb` file:
144
+ its server code runs with its own line numbers.
145
+
146
+ ```json
147
+ {"name": "Attach to pyweb dev", "type": "debugpy", "request": "attach",
148
+ "connect": {"host": "127.0.0.1", "port": 5678}, "justMyCode": true}
149
+ ```
150
+
151
+ In the browser, each page module has a source map in `pyweb dev`: stack traces and the devtools'
152
+ breakpoints point at the `.pyweb` file (an event handler's code at its `def`, state at its
153
+ assignment). `pyweb build --sourcemaps` links the maps in a build too; they don't include your
154
+ source there.
155
+
139
156
  ## Security limits
140
157
 
141
158
  | Feature | Who can use it |
@@ -149,3 +166,11 @@ answer only requests from your machine to `localhost`.
149
166
 
150
167
  The [threat model](https://github.com/MaanavKrishna/PyWeb/blob/main/THREAT_MODEL.md) lists each of these with the tests
151
168
  that prove it.
169
+
170
+
171
+ ### Environment
172
+
173
+ | Variable | What it does |
174
+ |---|---|
175
+ | `PYWEB_NO_OPEN` | `1`: `pyweb dev` doesn't open the browser (also skipped over SSH and in CI) |
176
+ | `PYWEB_SHARE_COMMAND` | the tunnel command for `--share` instead of cloudflared/ssh (`{port}` is filled in) |
@@ -0,0 +1,130 @@
1
+ # Routes & middleware
2
+
3
+ Pages answer with HTML a person reads. Everything else your app answers, a JSON API, a CSV
4
+ download, a feed, a callback from another service, is a **route**: a plain Python function at
5
+ a URL. **Middleware** runs around every request, for timing, headers, logging or answering early.
6
+
7
+ ```python
8
+ from pyweb import App
9
+ from pyweb.routes import csv, json
10
+
11
+ app = App(title="Shop", base_url="https://shop.example")
12
+
13
+
14
+ @app.route("/api/products/{id:int}")
15
+ def product(id: int):
16
+ p = Product.get(id)
17
+ return p.to_dict() if p else json({"error": "not found"}, status=404)
18
+
19
+
20
+ @app.route("/api/products", methods=["POST"], login=True)
21
+ def add_product(body: dict):
22
+ return json(Product.create(name=body["name"]).to_dict(), status=201)
23
+
24
+
25
+ @app.route("/admin/products.csv", roles=["admin"])
26
+ def export():
27
+ return csv(Product.all(), filename="products.csv")
28
+ ```
29
+
30
+ Routes live in your `.pyweb` file (or a module it imports) like server functions, and like them
31
+ they never reach the browser.
32
+
33
+ ## Paths
34
+
35
+ | Pattern | Matches | The handler gets |
36
+ |---|---|---|
37
+ | `/items/{id:int}` | `/items/42` | `id=42` |
38
+ | `/posts/{slug}` | `/posts/hello` (one segment) | `slug="hello"` |
39
+ | `/files/{rest:path}` | `/files/a/b/c.txt` | `rest="a/b/c.txt"` |
40
+ | `/{id:uuid}`, `/{x:float}` | a UUID, a number | `uuid.UUID`, `float` |
41
+
42
+ A path that doesn't convert (`/items/abc` for `{id:int}`) doesn't match. Routes are checked
43
+ before pages; the same path can't be both. A path that matches with the wrong method answers
44
+ `405` with an `Allow` header. `@app.get(path)` and `@app.post(path)` are short for one method.
45
+
46
+ ## What the handler gets and returns
47
+
48
+ Parameters are filled by name: path parameters, query parameters (`?q=...`, typed by the
49
+ annotation: `int`, `float`, `bool`, else `str`; a missing one without a default is `400`),
50
+ `body` (the JSON body, or a form's fields as a dict) and `request` (the request itself).
51
+ `pyweb.request` and `pyweb.session` work as in server functions.
52
+
53
+ | Return | Response |
54
+ |---|---|
55
+ | a `dict` or `list` | JSON |
56
+ | a `str` | `text/plain` (or the route's `content_type=`, e.g. `"text/html; charset=utf-8"`) |
57
+ | `bytes` | a download (`application/octet-stream`) |
58
+ | `None` | `204 No Content` |
59
+ | `json(data, status=)`, `text(...)`, `html(...)`, `csv(rows, filename=)` | exactly that |
60
+ | `redirect("/somewhere")` | `303` |
61
+ | `Response(status, body, headers)` | as is |
62
+
63
+ Raise `NotFound` for a 404 and `RPCError` for the others; anything else is a 500 (and is
64
+ reported like a page error). `csv()` takes dicts, Models or lists; text starting with `=`, `+`,
65
+ `-` or `@` is prefixed with `'` so spreadsheets don't run it as a formula.
66
+
67
+ ## Who can call it
68
+
69
+ | Option | Effect |
70
+ |---|---|
71
+ | `login=True` | signed in, else `401` |
72
+ | `roles=["admin"]` | those roles, else `403` |
73
+ | `fresh=600` | signed in within the last 600 seconds |
74
+ | `rate="30/minute"`, `per="user"` | limited like a server function (`429` with `Retry-After`) |
75
+ | `tokens=True` | API tokens (`Authorization: Bearer pwk_...`) work here; the token's scopes name the route |
76
+ | `cors=["https://partner.example"]` | those origins may call it from their pages (preflight answered) |
77
+ | `csrf=False` | skip the same-site check below (a public endpoint) |
78
+
79
+ A request that changes something (POST, PUT, PATCH, DELETE) and carries the visitor's cookies
80
+ must come from your own site: browsers say where a request came from, and PyWeb refuses one from
81
+ another site. API tokens and the `cors=` origins are the ways in from elsewhere.
82
+
83
+ ## Middleware
84
+
85
+ ```python
86
+ import time
87
+
88
+ @app.middleware
89
+ def timing(request, call_next):
90
+ start = time.perf_counter()
91
+ response = call_next(request)
92
+ response.headers["Server-Timing"] = f"app;dur={(time.perf_counter() - start) * 1000:.1f}"
93
+ return response
94
+
95
+
96
+ @app.middleware
97
+ def maintenance(request, call_next):
98
+ if MAINTENANCE and not request.path.startswith("/healthz"):
99
+ return json({"error": "back soon"}, status=503)
100
+ return call_next(request)
101
+ ```
102
+
103
+ Middleware runs for pages, routes, server functions and forms (not static files), in the order
104
+ it was added: the first one added is the outermost. Return a response to answer without calling
105
+ `call_next`.
106
+
107
+ ## robots.txt and sitemap.xml
108
+
109
+ `/robots.txt` allows everything except PyWeb's own endpoints and `/admin`, and points to the
110
+ sitemap when the app has a `base_url`. `App(robots="...")` replaces the text; `robots=False`
111
+ turns it off. `/sitemap.xml` (with `base_url`) lists every page without parameters that anyone
112
+ may see (no `login=`, no `noindex`); add the others with a generator:
113
+
114
+ ```python
115
+ @app.sitemap
116
+ def posts():
117
+ return [f"/blog/{p.slug}" for p in Post.where(published=True)]
118
+ ```
119
+
120
+ A route or page of your own at either path wins.
121
+
122
+ ## Plugins
123
+
124
+ A `Plugin` can declare routes too (`@plugin.route(...)`, and `@plugin.page(...)` for HTML it
125
+ builds itself); `App(plugins=[...])` registers them with its server functions and Models.
126
+
127
+ ## In the tools
128
+
129
+ `pyweb openapi` describes routes next to server functions, and the MCP `pyweb_routes` tool lists
130
+ them.