strata-python 0.2.5__tar.gz → 0.2.6__tar.gz

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 (84) hide show
  1. {strata_python-0.2.5 → strata_python-0.2.6}/CHANGELOG.md +16 -0
  2. {strata_python-0.2.5 → strata_python-0.2.6}/PKG-INFO +27 -8
  3. {strata_python-0.2.5 → strata_python-0.2.6}/README.md +26 -7
  4. {strata_python-0.2.5 → strata_python-0.2.6}/pyproject.toml +1 -1
  5. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/cli.py +45 -2
  6. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/contracts.py +9 -0
  7. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/db/__init__.py +7 -1
  8. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/db/cli.py +23 -9
  9. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/db/config.py +28 -4
  10. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/db/engine.py +4 -0
  11. strata_python-0.2.6/src/strata_python/db/project.py +149 -0
  12. strata_python-0.2.6/src/strata_python/db/web.py +103 -0
  13. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/public_check.py +122 -19
  14. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/settings.py +99 -25
  15. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/testing.py +13 -0
  16. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/web.py +10 -1
  17. {strata_python-0.2.5 → strata_python-0.2.6}/tests/unit/test_cli.py +65 -0
  18. {strata_python-0.2.5 → strata_python-0.2.6}/tests/unit/test_contracts.py +14 -0
  19. {strata_python-0.2.5 → strata_python-0.2.6}/tests/unit/test_db.py +151 -0
  20. {strata_python-0.2.5 → strata_python-0.2.6}/tests/unit/test_public_check.py +83 -0
  21. {strata_python-0.2.5 → strata_python-0.2.6}/tests/unit/test_settings.py +24 -0
  22. {strata_python-0.2.5 → strata_python-0.2.6}/tests/unit/test_web.py +40 -0
  23. strata_python-0.2.5/src/strata_python/db/project.py +0 -98
  24. {strata_python-0.2.5 → strata_python-0.2.6}/.gitignore +0 -0
  25. {strata_python-0.2.5 → strata_python-0.2.6}/LICENSE +0 -0
  26. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/__init__.py +0 -0
  27. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/check.py +0 -0
  28. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/client.py +0 -0
  29. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/clients/__init__.py +0 -0
  30. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/clients/models.py +0 -0
  31. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/db/__main__.py +0 -0
  32. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/db/_alembic/env.py +0 -0
  33. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/db/_alembic/script.py.mako +0 -0
  34. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/db/guard.py +0 -0
  35. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/db/migrations.py +0 -0
  36. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/db/models.py +0 -0
  37. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/db/pytest_plugin.py +0 -0
  38. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/db/scratch.py +0 -0
  39. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/db/settings.py +0 -0
  40. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/db/testing.py +0 -0
  41. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/db/testserver.py +0 -0
  42. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/files.py +0 -0
  43. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/http.py +0 -0
  44. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/http_server.py +0 -0
  45. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/images.py +0 -0
  46. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/live.py +0 -0
  47. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/media.py +0 -0
  48. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/oslib.py +0 -0
  49. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/pages/__init__.py +0 -0
  50. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/pages/model.py +0 -0
  51. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/pages/render.py +0 -0
  52. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/py.typed +0 -0
  53. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/pytest_plugin.py +0 -0
  54. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/stats.py +0 -0
  55. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/tasks/__init__.py +0 -0
  56. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/tasks/child.py +0 -0
  57. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/tasks/flight.py +0 -0
  58. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/tasks/progress.py +0 -0
  59. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/tasks/queue.py +0 -0
  60. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/tasks/retry.py +0 -0
  61. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/tasks/status.py +0 -0
  62. {strata_python-0.2.5 → strata_python-0.2.6}/src/strata_python/tasks/ticker.py +0 -0
  63. {strata_python-0.2.5 → strata_python-0.2.6}/tests/conftest.py +0 -0
  64. {strata_python-0.2.5 → strata_python-0.2.6}/tests/integration/test_db_cli.py +0 -0
  65. {strata_python-0.2.5 → strata_python-0.2.6}/tests/integration/test_serve.py +0 -0
  66. {strata_python-0.2.5 → strata_python-0.2.6}/tests/integration/test_strata_check.py +0 -0
  67. {strata_python-0.2.5 → strata_python-0.2.6}/tests/unit/job_handlers.py +0 -0
  68. {strata_python-0.2.5 → strata_python-0.2.6}/tests/unit/test_check.py +0 -0
  69. {strata_python-0.2.5 → strata_python-0.2.6}/tests/unit/test_client.py +0 -0
  70. {strata_python-0.2.5 → strata_python-0.2.6}/tests/unit/test_clients_models.py +0 -0
  71. {strata_python-0.2.5 → strata_python-0.2.6}/tests/unit/test_files.py +0 -0
  72. {strata_python-0.2.5 → strata_python-0.2.6}/tests/unit/test_http.py +0 -0
  73. {strata_python-0.2.5 → strata_python-0.2.6}/tests/unit/test_http_server.py +0 -0
  74. {strata_python-0.2.5 → strata_python-0.2.6}/tests/unit/test_images.py +0 -0
  75. {strata_python-0.2.5 → strata_python-0.2.6}/tests/unit/test_live.py +0 -0
  76. {strata_python-0.2.5 → strata_python-0.2.6}/tests/unit/test_media.py +0 -0
  77. {strata_python-0.2.5 → strata_python-0.2.6}/tests/unit/test_oslib.py +0 -0
  78. {strata_python-0.2.5 → strata_python-0.2.6}/tests/unit/test_package.py +0 -0
  79. {strata_python-0.2.5 → strata_python-0.2.6}/tests/unit/test_pages.py +0 -0
  80. {strata_python-0.2.5 → strata_python-0.2.6}/tests/unit/test_plugin.py +0 -0
  81. {strata_python-0.2.5 → strata_python-0.2.6}/tests/unit/test_queue.py +0 -0
  82. {strata_python-0.2.5 → strata_python-0.2.6}/tests/unit/test_stats.py +0 -0
  83. {strata_python-0.2.5 → strata_python-0.2.6}/tests/unit/test_tasks.py +0 -0
  84. {strata_python-0.2.5 → strata_python-0.2.6}/tests/unit/test_testing.py +0 -0
@@ -4,6 +4,22 @@ What each release adds or changes for an app that depends on strata-python, newe
4
4
 
5
5
  ## Unreleased
6
6
 
7
+ ## 0.2.6 (2026-11-23)
8
+
9
+ ### Added
10
+
11
+ - `strata-public-check` reads web source (`.ts`, `.tsx`, `.mts`, `.cts`, `.js`, `.jsx`, `.mjs`, `.cjs`, `.mdx`, `.css`, `.html`, `.svg`, `.vue`, `.env.example`) and skips `storybook-static/` and `baselines/` (#37). Remove the app's own privacy scan of its front end.
12
+ - `[tool.strata-public-check] deny = ["\\bdate of birth\\b", {pattern = "...", kind = "age"}]`: case-insensitive patterns committed in the repo, reported under their kind with the match shown, skipped by an exclude and by `strata-public-check: ignore` like the built-in ones (#38). A bad entry exits 2.
13
+ - `cli.add_openapi(sub, create_app)`: `myapp openapi [-o PATH|-] [--check]` writes `web/openapi.json` for strata-react's `strata-api-types`, via `web.openapi_text(app)` (sorted keys, indent 1, final newline); `testing.assert_openapi_current(create_app, path)` is the unit test; `contracts.ApiModel` keeps defaulted response fields required in the schema (#36).
14
+ - `Setting(..., choices=[...])` and the `one_of(choices)` normaliser: case-insensitive, stored as the choice is spelled, refused with the list; `set` shows the choices and `/api/openapi.json` types the setting as an `enum`. `Settings(..., numbers=True)` sends `whole_between`/`number_between` settings as JSON numbers with `minimum`/`maximum` in the schema (off by default). `PUT /api/settings` takes numbers. `Settings.allowed(key)` (#41).
15
+ - `strata_python.db`: a `strata-db.toml` inside the package (`strata-db init --package src/myapp`, with `[tool.strata-db] file = ...` pointing at it) so `Project.load(__file__)` works from an installed wheel (#40); `local_url(SETTINGS)` and `url_for(app, default=...)` for a SQLite fallback when nothing is configured; `Project.open(url=None, default=...)` connects and migrates; `connect` makes a SQLite file's folder (#39).
16
+ - `strata_python.db.web`: `add_database(app, project, default=...)` opens and migrates the engine on the first request that needs it and disposes it when the server stops; `DbSession` is the per-request session dependency (#39).
17
+
18
+ ### Changed
19
+
20
+ - `strata-public-check` on a folder inside a git checkout reads only the files git would commit (`git ls-files -co --exclude-standard`), so ignored tool output such as `.coverage` is not scanned; a folder git ignores (`dist`) is still read in full when named. A file with no suffix that holds a NUL byte is skipped as binary (#37).
21
+ - `whole_between` and `number_between` are now small callable classes with `lo`/`hi` (they used to be closures); calling them is unchanged.
22
+
7
23
  ## 0.2.5 (2026-11-23)
8
24
 
9
25
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: strata-python
3
- Version: 0.2.5
3
+ Version: 0.2.6
4
4
  Summary: Common code for Python web server apps: OS helpers, settings, FastAPI serving, CLI commands, test fixtures and the strata-check gate
5
5
  Project-URL: Homepage, https://github.com/jburnhams/strata-python
6
6
  Project-URL: Source, https://github.com/jburnhams/strata-python
@@ -53,9 +53,9 @@ Common code for the strata Python web server apps (FastAPI + CLI), the Python co
53
53
  |---|---|
54
54
  | `strata_python.oslib` | Cross-platform file locks, process liveness (`pid_alive`), `kill_tree`, `lower_priority`, `detached_kwargs`, `load_average`, `start_supervised`/`watch_supervisor`/`kill_group` (a child in its own process group that dies with its parent), `venv_python`, `cli_command(module)` |
55
55
  | `strata_python.settings` | `Settings` / `Setting` / `ListSetting`: one JSON file in `~/.<app>` with `<APP>_*` environment overrides, validation (`absolute_path`, `non_empty`, `number_between`, `whole_between`, `iso_date`, `boolean`), typed getters, atomic saves, and `bind(store)` to keep them elsewhere (`strata_python.db.settings.TableStore`) |
56
- | `strata_python.web` | `base_app` (health with the app's own fields and `commit` + typed settings routes), `add_error_handlers` (exceptions to `ErrorBody` responses), `add_system` (`GET /api/system`: folders, disks, services), `source_commit`, `add_web` (built web app or stand-in page at every non-API path), `with_base` (reverse-proxy-safe `<base href>`), `static_file` (path-safe), `serve` |
57
- | `strata_python.cli` | `add_doctor` (imports, labels, optional modules and the app's own `Check`s), `add_set`, `add_serve` for the app's argparse subcommands |
58
- | `strata_python.contracts` | The shapes the apps' APIs share, as pydantic models for `response_model`: `Health`, `SystemInfo`, `ErrorBody`, `Task` (with `TaskState`), `Progress`, `Page[T]`, `FileRef`, `Judgment` |
56
+ | `strata_python.web` | `base_app` (health with the app's own fields and `commit` + typed settings routes), `add_error_handlers` (exceptions to `ErrorBody` responses), `add_system` (`GET /api/system`: folders, disks, services), `source_commit`, `add_web` (built web app or stand-in page at every non-API path), `with_base` (reverse-proxy-safe `<base href>`), `static_file` (path-safe), `serve`, `openapi_text` (the schema as stable text) |
57
+ | `strata_python.cli` | `add_doctor` (imports, labels, optional modules and the app's own `Check`s), `add_set`, `add_serve`, `add_openapi` (the schema file for strata-react's `strata-api-types`) for the app's argparse subcommands |
58
+ | `strata_python.contracts` | The shapes the apps' APIs share, as pydantic models for `response_model`: `Health`, `SystemInfo`, `ErrorBody`, `Task` (with `TaskState`), `Progress`, `Page[T]`, `FileRef`, `Judgment`; `ApiModel`, a base for the app's own responses whose defaulted fields stay required in the schema |
59
59
  | `strata_python.client` | `ServiceClient`, the standard-library base for calling a strata service: JSON calls, `Rejected` (4xx, with the reason and payload) and `Unavailable` (down or 5xx), retried reads, a long-poll `wait`, `available()`, and `env_url` |
60
60
  | `strata_python.tasks` | Work outside a request: `next_state`/`backoff_s`/`RetryLater` (when to retry), `report_progress` and `ProgressReporter` (throttled), `SingleFlight` (one run per key, `Conflict` on a second), `StatusFile` and `Detached` (a process that outlives the server), `Ticker` (a loop that survives its errors), and with the `[db]` extra `tasks.queue` (`Queue`, `Worker`, `jobs_table`: durable jobs with retry, dedupe, resources, cancel and crash recovery) |
61
61
  | `strata_python.files` | Atomic writes (`atomic_path` keeps the extension for ffmpeg, `atomic_open`, `write_json_atomic`, `write_text_atomic`, `write_bytes_atomic`), `read_json(path, default)`, `sha256`/`sha256_hex`, `quick_fingerprint` (size and both ends), `stat_key` (a cache key that follows the file), `inside(root, path)` (refuses `..` and links out), and `DiskCache` (values on disk with an age; `json(key, fetch, max_age_s)`) |
@@ -66,11 +66,11 @@ Common code for the strata Python web server apps (FastAPI + CLI), the Python co
66
66
  | `strata_python.clients.models` | The strata-models client, standard library only: `run`, `submit`, `wait`, `role_model`, `gpu_lease`, a shortcut for every role the service runs (`faces`, `face_kind`, `transcribe`, `ocr`, `speak`, `denoise_audio`, `audio_quality`, `generate_image`, `embed`, `enhance_video`, and `ask` for the language models) and a typed result for each |
67
67
  | `strata_python.http_server` / `live` | A real scripted HTTP server and a real uvicorn server on loopback, for tests that make actual requests |
68
68
  | pytest plugin | Loaded automatically: hermetic home and data folders (`strata_env` adds the app's own variables), a no-network guard, `http_server` and `live_app`, the `fake_urlopen`, `fake_popen`, `fake_run` and `no_sleep` fixtures, `fake_models` (a stand-in strata-models), and the `integration` marker on everything under `tests/integration` |
69
- | `strata_python.testing` | The fakes behind those fixtures (`FakeResponse`, `http_error`, `FakeUrlopen`, `FakePopen`, `FakeRun`, `Sleeper`) `FakeModels`, and the CLI runners `run_cli(main, *args)` and `run_module("myapp", *args, src=...)` |
70
- | `strata_python.db` (extra `[db]`) | The shared database: `connect("myapp")` (the app's schema of one shared Postgres, or a SQLite path), a declarative base with the shared `NAMING_CONVENTION` for typed models, Alembic migrations with no per-app `env.py`, the live-database guard, the `strata-db` command, and the `db_*` fixtures (SQLite by default, a throwaway Postgres with `--pg`) |
69
+ | `strata_python.testing` | The fakes behind those fixtures (`FakeResponse`, `http_error`, `FakeUrlopen`, `FakePopen`, `FakeRun`, `Sleeper`) `FakeModels`, the CLI runners `run_cli(main, *args)` and `run_module("myapp", *args, src=...)`, and `assert_openapi_current(create_app, path)` |
70
+ | `strata_python.db` (extra `[db]`) | The shared database: `connect("myapp")` (the app's schema of one shared Postgres, or a SQLite path), a declarative base with the shared `NAMING_CONVENTION` for typed models, Alembic migrations with no per-app `env.py`, the live-database guard, the `strata-db` command, the `db_*` fixtures (SQLite by default, a throwaway Postgres with `--pg`), and `strata_python.db.web` (`add_database`, `DbSession`) for a server's records |
71
71
  | `strata_python.pages` (extra `[pdf]`) | A scanned page described as blocks, lines, styled spans and figures in scan pixels, drawn as a PDF with real embedded fonts (`render`), and read back as pixels at the scan's dpi (`rasterise`) and as text (`read_text`): for rebuilding scanned books, and for scoring a rebuild with the renderer that prints it |
72
72
  | `strata-check` | The one gate: lockfile, ruff, `ruff format`, pyright strict, ty, unit tests with coverage |
73
- | `strata-public-check` | Fails on email addresses, private IPv4 addresses, home-folder paths and the regexes in `STRATA_PUBLIC_DENY` in a tree, sdist or wheel; run before anything public is published. Silence a false positive with `[tool.strata-public-check] exclude = ["web/package-lock.json"]` (or `--exclude`), or `strata-public-check: ignore` on the line (never applies to `STRATA_PUBLIC_DENY`) |
73
+ | `strata-public-check` | Fails on email addresses, private IPv4 addresses, home-folder paths, the repo's own `[tool.strata-public-check] deny` regexes and the owner's `STRATA_PUBLIC_DENY` ones in a tree, sdist or wheel; run before anything public is published. Reads Python, web source (`.ts`, `.tsx`, `.js`, `.css`, `.html`, `.mdx`, `.svg`...) and config text; in a git checkout only what git would commit, so tool output such as `.coverage` is skipped. Silence a false positive with `[tool.strata-public-check] exclude = ["web/package-lock.json"]` (or `--exclude`), or `strata-public-check: ignore` on the line (never applies to `STRATA_PUBLIC_DENY`) |
74
74
 
75
75
  ## Move an app onto it
76
76
 
@@ -135,6 +135,7 @@ SETTINGS = Settings(
135
135
  Setting("data_dir", default=lambda: "/srv/myapp", normalise=absolute_path),
136
136
  Setting("greeting", default="Hello", normalise=non_empty),
137
137
  Setting("workers", default="2", normalise=whole_between(1, 16)),
138
+ Setting("mode", default="mixed", choices=["mixed", "review", "new"]), # an enum in the API schema
138
139
  ListSetting("source_roots", item=absolute_path, env="MYAPP_SOURCES"), # MYAPP_SOURCES split on os.pathsep
139
140
  ],
140
141
  prefix="MYAPP", # only if the app already runs with other variable names
@@ -147,6 +148,8 @@ SETTINGS.folder("data_dir") # the value as a folder, created if missing
147
148
 
148
149
  Values are canonical strings, and lists of them. Normalisers for the common kinds give one spelling each: `number_between(lo, hi)`, `whole_between(lo, hi)`, `iso_date(allow_blank=True)` and `boolean`, read back with `get_float`, `get_int` and `get_bool`. A `ListSetting` is a JSON list in the file (a string there is split, so a hand edit works), split on `sep` in the environment (`os.pathsep` by default, `sep=","` for names), with `item` normalising each entry. `get_list` returns it, and `all()` and `GET /api/settings` return it as JSON. `get` and `set` show it joined, and `save` takes a list or a joined string.
149
150
 
151
+ A setting that takes one of a fixed set has `choices=[m.value for m in Mode]` (or `normalise=one_of(...)`): a value is matched without regard to case and stored as the choice is spelled, anything else is refused with the list, `set` shows the choices, and the schema in `/api/openapi.json` has an `enum`, so the web app's generated type needs no narrowing by hand. `Settings(..., numbers=True)` also sends `whole_between` and `number_between` settings as JSON numbers, with `minimum` and `maximum` in the schema; it changes what `GET /api/settings` sends, so turn it on with the web app's change. `PUT /api/settings` takes numbers either way.
152
+
150
153
  To keep the values in the app's database instead of the file, add the table to the models and bind at service start, after the migrations. The file's values are copied in the first time, and the CLI and tests without a database keep using the file:
151
154
 
152
155
  ```python
@@ -208,6 +211,8 @@ def main(argv=None):
208
211
  return args.fn(args)
209
212
  ```
210
213
 
214
+ An app with a web front end on strata-react adds `cli.add_openapi(sub, create_app)`: `myapp openapi` writes `web/openapi.json` (or `-o PATH`, `-o -` for stdout) for `strata-api-types`, in a stable form (sorted keys, indent 1, a final newline, nothing from the machine), and `myapp openapi --check` exits 1 when the committed file is out of date. Its unit test is `strata_python.testing.assert_openapi_current(create_app, "web/openapi.json")`. Build response models on `contracts.ApiModel` so a field with a default is not optional (`?`) in the generated types.
215
+
211
216
  Delete the hand-written `doctor`, `set` and `serve` subparsers. Each app's port belongs in its deploy units, not in this library.
212
217
 
213
218
  A doctor that needs more than imports takes labels, optional modules, checks and its own hint, and prints every app's rows in the same columns:
@@ -388,7 +393,21 @@ migrations = "migrations" # the app's Alembic revisions, unchanged
388
393
  ```
389
394
  - Environment: `STRATA_DB_LIVE=1` in the service unit (next to the old variable until every app has moved), and `STRATA_DB_DATABASE` naming the shared database. It has no built-in name any more, because that name is the owner's and this package is public; set it once where the services get their environment. `STRATA_DB_URL` and `<APP>_DATABASE_URL` work as before. Tests and CI: `STRATA_DB_TEST_ADMIN_URL`, `STRATA_DB_TEST=postgres`.
390
395
  - Commands: `strata-db revision -m "..."`, `strata-db check`, `strata-db migrate --live`, `strata-db current --live`, `strata-db new-app`, `strata-db init` (or `python -m strata_python.db`).
391
- - At service start (only there): `Project.load(__file__).upgrade(connect("myapp"))`.
396
+ - At service start (only there): `Project.load(__file__).upgrade(connect("myapp"))`, or `Project.load(__file__).open(default=local_url(SETTINGS))`, which connects and migrates, falling back to `<settings home>/myapp.db` when no database is configured (the folder is made).
397
+ - An app installed as a wheel (a service from `uv tool install`) has no pyproject.toml beside its code. `strata-db init --package src/myapp` declares the keys in `src/myapp/strata-db.toml` instead, with `migrations/` beside it, and puts `[tool.strata-db] file = "src/myapp/strata-db.toml"` in pyproject.toml. Both ship in the wheel, `Project.load(__file__)` finds the file by walking up from the module, and strata-db and the pytest plugin follow the pointer, so there is one declaration and no drift test. To move an existing app, move the keys and the `migrations` folder into the package and leave `file = ...` in the table.
398
+ - A FastAPI server's records:
399
+
400
+ ```python
401
+ from strata_python.db import Project, local_url
402
+ from strata_python.db.web import DbSession, add_database
403
+
404
+ add_database(app, Project.load(__file__), default=lambda: local_url(SETTINGS))
405
+
406
+ @app.get("/api/notes")
407
+ def notes(db: DbSession) -> list[NoteOut]: ...
408
+ ```
409
+
410
+ The engine is opened and migrated on the first request that needs one (a server nobody records on never creates a database), kept on `app.state` and disposed when the server stops, after the app's own lifespan. A failure to open is that request's error and is tried again on the next. Delete the app's `db.py` fallback, its session dependency and the conftest that disposed the engine.
392
411
  - Tests: the plugin is registered with every install and does nothing until the extra is installed and the project has `[tool.strata-db]` (or `strata_db = true` in `[tool.pytest.ini_options]`; `strata_db = false` turns it off). So an app can take a 0.2.x release before it moves its database, even with the old database package still installed. Then `db_session`, `db_engine`, `db_url` (a URL for code that builds its own engine), `db_env` (points the app's own `connect("myapp")` at the test database; make it autouse in `conftest.py` for an app that connects by itself), `db_backend`, `db_project`. Migrations run once into a template and each test gets a copy, so a test costs a file copy. `pytest --pg` (or `--strata-pg`, which no other plugin can take) runs the same tests on a private Postgres the run starts for itself (needs the PostgreSQL server binaries), or on `STRATA_DB_TEST_ADMIN_URL`. Add the standard tests once:
393
412
 
394
413
  ```python
@@ -6,9 +6,9 @@ Common code for the strata Python web server apps (FastAPI + CLI), the Python co
6
6
  |---|---|
7
7
  | `strata_python.oslib` | Cross-platform file locks, process liveness (`pid_alive`), `kill_tree`, `lower_priority`, `detached_kwargs`, `load_average`, `start_supervised`/`watch_supervisor`/`kill_group` (a child in its own process group that dies with its parent), `venv_python`, `cli_command(module)` |
8
8
  | `strata_python.settings` | `Settings` / `Setting` / `ListSetting`: one JSON file in `~/.<app>` with `<APP>_*` environment overrides, validation (`absolute_path`, `non_empty`, `number_between`, `whole_between`, `iso_date`, `boolean`), typed getters, atomic saves, and `bind(store)` to keep them elsewhere (`strata_python.db.settings.TableStore`) |
9
- | `strata_python.web` | `base_app` (health with the app's own fields and `commit` + typed settings routes), `add_error_handlers` (exceptions to `ErrorBody` responses), `add_system` (`GET /api/system`: folders, disks, services), `source_commit`, `add_web` (built web app or stand-in page at every non-API path), `with_base` (reverse-proxy-safe `<base href>`), `static_file` (path-safe), `serve` |
10
- | `strata_python.cli` | `add_doctor` (imports, labels, optional modules and the app's own `Check`s), `add_set`, `add_serve` for the app's argparse subcommands |
11
- | `strata_python.contracts` | The shapes the apps' APIs share, as pydantic models for `response_model`: `Health`, `SystemInfo`, `ErrorBody`, `Task` (with `TaskState`), `Progress`, `Page[T]`, `FileRef`, `Judgment` |
9
+ | `strata_python.web` | `base_app` (health with the app's own fields and `commit` + typed settings routes), `add_error_handlers` (exceptions to `ErrorBody` responses), `add_system` (`GET /api/system`: folders, disks, services), `source_commit`, `add_web` (built web app or stand-in page at every non-API path), `with_base` (reverse-proxy-safe `<base href>`), `static_file` (path-safe), `serve`, `openapi_text` (the schema as stable text) |
10
+ | `strata_python.cli` | `add_doctor` (imports, labels, optional modules and the app's own `Check`s), `add_set`, `add_serve`, `add_openapi` (the schema file for strata-react's `strata-api-types`) for the app's argparse subcommands |
11
+ | `strata_python.contracts` | The shapes the apps' APIs share, as pydantic models for `response_model`: `Health`, `SystemInfo`, `ErrorBody`, `Task` (with `TaskState`), `Progress`, `Page[T]`, `FileRef`, `Judgment`; `ApiModel`, a base for the app's own responses whose defaulted fields stay required in the schema |
12
12
  | `strata_python.client` | `ServiceClient`, the standard-library base for calling a strata service: JSON calls, `Rejected` (4xx, with the reason and payload) and `Unavailable` (down or 5xx), retried reads, a long-poll `wait`, `available()`, and `env_url` |
13
13
  | `strata_python.tasks` | Work outside a request: `next_state`/`backoff_s`/`RetryLater` (when to retry), `report_progress` and `ProgressReporter` (throttled), `SingleFlight` (one run per key, `Conflict` on a second), `StatusFile` and `Detached` (a process that outlives the server), `Ticker` (a loop that survives its errors), and with the `[db]` extra `tasks.queue` (`Queue`, `Worker`, `jobs_table`: durable jobs with retry, dedupe, resources, cancel and crash recovery) |
14
14
  | `strata_python.files` | Atomic writes (`atomic_path` keeps the extension for ffmpeg, `atomic_open`, `write_json_atomic`, `write_text_atomic`, `write_bytes_atomic`), `read_json(path, default)`, `sha256`/`sha256_hex`, `quick_fingerprint` (size and both ends), `stat_key` (a cache key that follows the file), `inside(root, path)` (refuses `..` and links out), and `DiskCache` (values on disk with an age; `json(key, fetch, max_age_s)`) |
@@ -19,11 +19,11 @@ Common code for the strata Python web server apps (FastAPI + CLI), the Python co
19
19
  | `strata_python.clients.models` | The strata-models client, standard library only: `run`, `submit`, `wait`, `role_model`, `gpu_lease`, a shortcut for every role the service runs (`faces`, `face_kind`, `transcribe`, `ocr`, `speak`, `denoise_audio`, `audio_quality`, `generate_image`, `embed`, `enhance_video`, and `ask` for the language models) and a typed result for each |
20
20
  | `strata_python.http_server` / `live` | A real scripted HTTP server and a real uvicorn server on loopback, for tests that make actual requests |
21
21
  | pytest plugin | Loaded automatically: hermetic home and data folders (`strata_env` adds the app's own variables), a no-network guard, `http_server` and `live_app`, the `fake_urlopen`, `fake_popen`, `fake_run` and `no_sleep` fixtures, `fake_models` (a stand-in strata-models), and the `integration` marker on everything under `tests/integration` |
22
- | `strata_python.testing` | The fakes behind those fixtures (`FakeResponse`, `http_error`, `FakeUrlopen`, `FakePopen`, `FakeRun`, `Sleeper`) `FakeModels`, and the CLI runners `run_cli(main, *args)` and `run_module("myapp", *args, src=...)` |
23
- | `strata_python.db` (extra `[db]`) | The shared database: `connect("myapp")` (the app's schema of one shared Postgres, or a SQLite path), a declarative base with the shared `NAMING_CONVENTION` for typed models, Alembic migrations with no per-app `env.py`, the live-database guard, the `strata-db` command, and the `db_*` fixtures (SQLite by default, a throwaway Postgres with `--pg`) |
22
+ | `strata_python.testing` | The fakes behind those fixtures (`FakeResponse`, `http_error`, `FakeUrlopen`, `FakePopen`, `FakeRun`, `Sleeper`) `FakeModels`, the CLI runners `run_cli(main, *args)` and `run_module("myapp", *args, src=...)`, and `assert_openapi_current(create_app, path)` |
23
+ | `strata_python.db` (extra `[db]`) | The shared database: `connect("myapp")` (the app's schema of one shared Postgres, or a SQLite path), a declarative base with the shared `NAMING_CONVENTION` for typed models, Alembic migrations with no per-app `env.py`, the live-database guard, the `strata-db` command, the `db_*` fixtures (SQLite by default, a throwaway Postgres with `--pg`), and `strata_python.db.web` (`add_database`, `DbSession`) for a server's records |
24
24
  | `strata_python.pages` (extra `[pdf]`) | A scanned page described as blocks, lines, styled spans and figures in scan pixels, drawn as a PDF with real embedded fonts (`render`), and read back as pixels at the scan's dpi (`rasterise`) and as text (`read_text`): for rebuilding scanned books, and for scoring a rebuild with the renderer that prints it |
25
25
  | `strata-check` | The one gate: lockfile, ruff, `ruff format`, pyright strict, ty, unit tests with coverage |
26
- | `strata-public-check` | Fails on email addresses, private IPv4 addresses, home-folder paths and the regexes in `STRATA_PUBLIC_DENY` in a tree, sdist or wheel; run before anything public is published. Silence a false positive with `[tool.strata-public-check] exclude = ["web/package-lock.json"]` (or `--exclude`), or `strata-public-check: ignore` on the line (never applies to `STRATA_PUBLIC_DENY`) |
26
+ | `strata-public-check` | Fails on email addresses, private IPv4 addresses, home-folder paths, the repo's own `[tool.strata-public-check] deny` regexes and the owner's `STRATA_PUBLIC_DENY` ones in a tree, sdist or wheel; run before anything public is published. Reads Python, web source (`.ts`, `.tsx`, `.js`, `.css`, `.html`, `.mdx`, `.svg`...) and config text; in a git checkout only what git would commit, so tool output such as `.coverage` is skipped. Silence a false positive with `[tool.strata-public-check] exclude = ["web/package-lock.json"]` (or `--exclude`), or `strata-public-check: ignore` on the line (never applies to `STRATA_PUBLIC_DENY`) |
27
27
 
28
28
  ## Move an app onto it
29
29
 
@@ -88,6 +88,7 @@ SETTINGS = Settings(
88
88
  Setting("data_dir", default=lambda: "/srv/myapp", normalise=absolute_path),
89
89
  Setting("greeting", default="Hello", normalise=non_empty),
90
90
  Setting("workers", default="2", normalise=whole_between(1, 16)),
91
+ Setting("mode", default="mixed", choices=["mixed", "review", "new"]), # an enum in the API schema
91
92
  ListSetting("source_roots", item=absolute_path, env="MYAPP_SOURCES"), # MYAPP_SOURCES split on os.pathsep
92
93
  ],
93
94
  prefix="MYAPP", # only if the app already runs with other variable names
@@ -100,6 +101,8 @@ SETTINGS.folder("data_dir") # the value as a folder, created if missing
100
101
 
101
102
  Values are canonical strings, and lists of them. Normalisers for the common kinds give one spelling each: `number_between(lo, hi)`, `whole_between(lo, hi)`, `iso_date(allow_blank=True)` and `boolean`, read back with `get_float`, `get_int` and `get_bool`. A `ListSetting` is a JSON list in the file (a string there is split, so a hand edit works), split on `sep` in the environment (`os.pathsep` by default, `sep=","` for names), with `item` normalising each entry. `get_list` returns it, and `all()` and `GET /api/settings` return it as JSON. `get` and `set` show it joined, and `save` takes a list or a joined string.
102
103
 
104
+ A setting that takes one of a fixed set has `choices=[m.value for m in Mode]` (or `normalise=one_of(...)`): a value is matched without regard to case and stored as the choice is spelled, anything else is refused with the list, `set` shows the choices, and the schema in `/api/openapi.json` has an `enum`, so the web app's generated type needs no narrowing by hand. `Settings(..., numbers=True)` also sends `whole_between` and `number_between` settings as JSON numbers, with `minimum` and `maximum` in the schema; it changes what `GET /api/settings` sends, so turn it on with the web app's change. `PUT /api/settings` takes numbers either way.
105
+
103
106
  To keep the values in the app's database instead of the file, add the table to the models and bind at service start, after the migrations. The file's values are copied in the first time, and the CLI and tests without a database keep using the file:
104
107
 
105
108
  ```python
@@ -161,6 +164,8 @@ def main(argv=None):
161
164
  return args.fn(args)
162
165
  ```
163
166
 
167
+ An app with a web front end on strata-react adds `cli.add_openapi(sub, create_app)`: `myapp openapi` writes `web/openapi.json` (or `-o PATH`, `-o -` for stdout) for `strata-api-types`, in a stable form (sorted keys, indent 1, a final newline, nothing from the machine), and `myapp openapi --check` exits 1 when the committed file is out of date. Its unit test is `strata_python.testing.assert_openapi_current(create_app, "web/openapi.json")`. Build response models on `contracts.ApiModel` so a field with a default is not optional (`?`) in the generated types.
168
+
164
169
  Delete the hand-written `doctor`, `set` and `serve` subparsers. Each app's port belongs in its deploy units, not in this library.
165
170
 
166
171
  A doctor that needs more than imports takes labels, optional modules, checks and its own hint, and prints every app's rows in the same columns:
@@ -341,7 +346,21 @@ migrations = "migrations" # the app's Alembic revisions, unchanged
341
346
  ```
342
347
  - Environment: `STRATA_DB_LIVE=1` in the service unit (next to the old variable until every app has moved), and `STRATA_DB_DATABASE` naming the shared database. It has no built-in name any more, because that name is the owner's and this package is public; set it once where the services get their environment. `STRATA_DB_URL` and `<APP>_DATABASE_URL` work as before. Tests and CI: `STRATA_DB_TEST_ADMIN_URL`, `STRATA_DB_TEST=postgres`.
343
348
  - Commands: `strata-db revision -m "..."`, `strata-db check`, `strata-db migrate --live`, `strata-db current --live`, `strata-db new-app`, `strata-db init` (or `python -m strata_python.db`).
344
- - At service start (only there): `Project.load(__file__).upgrade(connect("myapp"))`.
349
+ - At service start (only there): `Project.load(__file__).upgrade(connect("myapp"))`, or `Project.load(__file__).open(default=local_url(SETTINGS))`, which connects and migrates, falling back to `<settings home>/myapp.db` when no database is configured (the folder is made).
350
+ - An app installed as a wheel (a service from `uv tool install`) has no pyproject.toml beside its code. `strata-db init --package src/myapp` declares the keys in `src/myapp/strata-db.toml` instead, with `migrations/` beside it, and puts `[tool.strata-db] file = "src/myapp/strata-db.toml"` in pyproject.toml. Both ship in the wheel, `Project.load(__file__)` finds the file by walking up from the module, and strata-db and the pytest plugin follow the pointer, so there is one declaration and no drift test. To move an existing app, move the keys and the `migrations` folder into the package and leave `file = ...` in the table.
351
+ - A FastAPI server's records:
352
+
353
+ ```python
354
+ from strata_python.db import Project, local_url
355
+ from strata_python.db.web import DbSession, add_database
356
+
357
+ add_database(app, Project.load(__file__), default=lambda: local_url(SETTINGS))
358
+
359
+ @app.get("/api/notes")
360
+ def notes(db: DbSession) -> list[NoteOut]: ...
361
+ ```
362
+
363
+ The engine is opened and migrated on the first request that needs one (a server nobody records on never creates a database), kept on `app.state` and disposed when the server stops, after the app's own lifespan. A failure to open is that request's error and is tried again on the next. Delete the app's `db.py` fallback, its session dependency and the conftest that disposed the engine.
345
364
  - Tests: the plugin is registered with every install and does nothing until the extra is installed and the project has `[tool.strata-db]` (or `strata_db = true` in `[tool.pytest.ini_options]`; `strata_db = false` turns it off). So an app can take a 0.2.x release before it moves its database, even with the old database package still installed. Then `db_session`, `db_engine`, `db_url` (a URL for code that builds its own engine), `db_env` (points the app's own `connect("myapp")` at the test database; make it autouse in `conftest.py` for an app that connects by itself), `db_backend`, `db_project`. Migrations run once into a template and each test gets a copy, so a test costs a file copy. `pytest --pg` (or `--strata-pg`, which no other plugin can take) runs the same tests on a private Postgres the run starts for itself (needs the PostgreSQL server binaries), or on `STRATA_DB_TEST_ADMIN_URL`. Add the standard tests once:
346
365
 
347
366
  ```python
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "strata-python"
7
- version = "0.2.5" # the single source of truth: `strata_python.__version__` reads it back with importlib.metadata
7
+ version = "0.2.6" # the single source of truth: `strata_python.__version__` reads it back with importlib.metadata
8
8
  description = "Common code for Python web server apps: OS helpers, settings, FastAPI serving, CLI commands, test fixtures and the strata-check gate"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -5,6 +5,7 @@
5
5
  checks=[Check("ffmpeg", program("ffmpeg"))])
6
6
  add_set(sub, SETTINGS)
7
7
  add_serve(sub, lambda host, port: web.serve(create_app(), ["--host", host, "--port", str(port)]), default_port=8360)
8
+ add_openapi(sub, create_app) # myapp openapi [-o web/openapi.json | -] [--check]
8
9
  args = parser.parse_args(argv); return args.fn(args)
9
10
 
10
11
  Each command sets `fn` on its parser; the handler returns the exit code."""
@@ -15,10 +16,14 @@ import shutil
15
16
  import sys
16
17
  from collections.abc import Callable, Iterable
17
18
  from dataclasses import dataclass
18
- from typing import Any, Literal
19
+ from pathlib import Path
20
+ from typing import TYPE_CHECKING, Any, Literal
19
21
 
20
22
  from strata_python.settings import Settings
21
23
 
24
+ if TYPE_CHECKING:
25
+ from fastapi import FastAPI
26
+
22
27
  Sub = Any # argparse's subparsers object is a private generic type; only add_parser is used
23
28
 
24
29
  Status = Literal["ok", "missing", "slow", "broken"]
@@ -128,7 +133,8 @@ def add_set(sub: Sub, settings: Settings) -> None:
128
133
  settings.save({args.key: None if args.value == "default" else args.value})
129
134
  except ValueError as e:
130
135
  sys.exit(str(e))
131
- print(f"{args.key} = {settings.get(args.key)}")
136
+ allowed = settings.allowed(args.key)
137
+ print(f"{args.key} = {settings.get(args.key)}" + (f" (one of: {', '.join(allowed)})" if allowed else ""))
132
138
  return 0
133
139
 
134
140
  p = sub.add_parser("set", help=f'show or change a setting ({", ".join(settings.keys)}); value "default" resets it')
@@ -148,3 +154,40 @@ def add_serve(sub: Sub, run: Callable[[str, int], None], *, default_port: int) -
148
154
  p.add_argument("--host", default="127.0.0.1")
149
155
  p.add_argument("--port", type=int, default=default_port)
150
156
  p.set_defaults(fn=cmd_serve)
157
+
158
+
159
+ def add_openapi(sub: Sub, create_app: "Callable[[], FastAPI]", *, default: Path = Path("web/openapi.json")) -> None:
160
+ """`openapi [-o PATH|-] [--check]`: write the app's schema (`web.openapi_text`) to `default`, another path or
161
+ stdout, for strata-react's `strata-api-types`, which reads the file so CI needs no server. `--check` writes
162
+ nothing and exits 1 when the file differs, so a Python-only CI job can gate it too. The app is built only when
163
+ the command runs, so `create_app` may be slow."""
164
+
165
+ def cmd_openapi(args: argparse.Namespace) -> int:
166
+ from strata_python import web # here, so the app's other commands do not import FastAPI
167
+
168
+ text = web.openapi_text(create_app())
169
+ out: str = args.output
170
+ if out == "-":
171
+ if args.check:
172
+ sys.exit("--check compares a file; give -o PATH")
173
+ sys.stdout.write(text)
174
+ return 0
175
+ path = Path(out)
176
+ if args.check:
177
+ current = path.read_text(encoding="utf-8") if path.is_file() else None
178
+ if current == text:
179
+ return 0
180
+ print(
181
+ f"{path} is {'missing' if current is None else 'out of date'}: run the openapi command", file=sys.stderr
182
+ )
183
+ return 1
184
+ path.parent.mkdir(parents=True, exist_ok=True)
185
+ with open(path, "w", encoding="utf-8", newline="\n") as f: # LF on Windows too, or the check never agrees
186
+ f.write(text)
187
+ print(f"wrote {path}")
188
+ return 0
189
+
190
+ p = sub.add_parser("openapi", help=f"write the API schema for the web app's types (default {default.as_posix()})")
191
+ p.add_argument("-o", "--output", default=str(default), help='file to write, or "-" for stdout')
192
+ p.add_argument("--check", action="store_true", help="write nothing; exit 1 if the file differs")
193
+ p.set_defaults(fn=cmd_openapi)
@@ -13,6 +13,7 @@ generated from it instead of copied.
13
13
  Page[T] one page of a list: items, the cursor for the next page (None at the end), the total when it is known
14
14
  FileRef a file by content and place: sha256, size, mtime, root, rel (the path under that root)
15
15
  Judgment one pairwise choice by a person or a model: a, b, the winner (a, b or tie), who, when, undone when
16
+ ApiModel a base for an app's own response shapes: a field with a default is still required in the schema
16
17
 
17
18
  Times are timezone-aware datetimes, sent as ISO 8601 with their offset: the apps had both ISO text and float epochs,
18
19
  and only one of those reads correctly in a browser. Use `utc(epoch)` to turn a stored float into one."""
@@ -30,6 +31,14 @@ def utc(epoch: float | None) -> datetime.datetime | None:
30
31
  return None if epoch is None else datetime.datetime.fromtimestamp(epoch, datetime.UTC)
31
32
 
32
33
 
34
+ class ApiModel(BaseModel):
35
+ """A base for an app's own response models. pydantic marks a field with a default as optional in the schema, so
36
+ the generated TypeScript gets a `?` though the server always sends it; this config makes the response schema
37
+ say what is sent. Use it for responses: a request body built on it has an `-Input` and an `-Output` schema."""
38
+
39
+ model_config = ConfigDict(json_schema_serialization_defaults_required=True)
40
+
41
+
33
42
  class Health(BaseModel):
34
43
  """What `GET /api/health` answers. Extra fields are the app's own (strata-models adds `gpu`)."""
35
44
 
@@ -19,7 +19,8 @@ extra: `strata-python[db]`.
19
19
  s.add(Note(text="hi")); s.commit()
20
20
 
21
21
  Migrations: `strata-db revision -m "..."` (autogenerate), `strata-db migrate`, `strata-db check`; or in code
22
- `Project.load(__file__).upgrade(engine)` at service start. Tests: the plugin's `db_session` / `db_engine` / `db_url`
22
+ `Project.load(__file__).upgrade(engine)` (or `.open()`, connect and migrate) at service start; a FastAPI server
23
+ uses `strata_python.db.web.add_database` and its `DbSession` dependency. Tests: the plugin's `db_session` / `db_engine` / `db_url`
23
24
  / `db_env` fixtures and `strata_python.db.testing`. See the README.
24
25
 
25
26
  The names load on first use: the pytest plugin imports `strata_python.db.guard` in every app with strata-python
@@ -35,6 +36,9 @@ if TYPE_CHECKING:
35
36
  from .config import (
36
37
  DatabaseNotConfigured as DatabaseNotConfigured,
37
38
  )
39
+ from .config import (
40
+ local_url as local_url,
41
+ )
38
42
  from .config import (
39
43
  normalise_url as normalise_url,
40
44
  )
@@ -74,6 +78,7 @@ _WHERE = {
74
78
  "DatabaseNotConfigured": "config",
75
79
  "normalise_url": "config",
76
80
  "resolve_url": "config",
81
+ "local_url": "config",
77
82
  "url_for": "config",
78
83
  "connect": "engine",
79
84
  "session": "engine",
@@ -93,6 +98,7 @@ __all__ = [ # noqa: RUF022 (grouped as _WHERE is)
93
98
  "DatabaseNotConfigured",
94
99
  "normalise_url",
95
100
  "resolve_url",
101
+ "local_url",
96
102
  "url_for",
97
103
  "connect",
98
104
  "session",
@@ -1,6 +1,6 @@
1
1
  """strata-db: the app-facing command line (run from anywhere inside the app's repo; also `python -m strata_python.db`).
2
2
 
3
- strata-db init --app NAME --models pkg.models:Base [--engine portable|postgres]
3
+ strata-db init --app NAME --models pkg.models:Base [--engine portable|postgres] [--package src/pkg]
4
4
  add [tool.strata-db] to pyproject.toml and create migrations/
5
5
  strata-db new-app [NAME] on the shared server: owner role NAME (NOLOGIN, you are a member) and schema NAME in
6
6
  the shared database, owned by it, no USAGE for PUBLIC (other app roles cannot see it).
@@ -33,7 +33,7 @@ from . import migrations as m
33
33
  from .config import normalise_url, resolve_url, shared_database
34
34
  from .engine import connect
35
35
  from .guard import LIVE, LiveDatabaseRefused, allow_live
36
- from .project import TABLE, Project
36
+ from .project import FILE, TABLE, Project
37
37
  from .scratch import live_admin_url, pg_available, scratch_database
38
38
  from .testing import scratch_engine
39
39
 
@@ -41,18 +41,29 @@ NAME = re.compile(r"[a-z][a-z0-9_]*") # role and schema names: nothing that nee
41
41
 
42
42
 
43
43
  def cmd_init(a: argparse.Namespace) -> None:
44
+ """Write the declaration: into pyproject.toml, or with --package into the package's strata-db.toml (migrations
45
+ beside it, so an installed wheel carries both) with a pointer to it in pyproject.toml."""
44
46
  pp = Path.cwd() / "pyproject.toml"
45
47
  body = pp.read_text(encoding="utf-8") if pp.exists() else f'[project]\nname = "{a.app}"\nversion = "0.1.0"\n'
46
48
  if f"[tool.{TABLE}]" in body:
47
49
  sys.exit(f"{pp} already has [tool.{TABLE}]")
48
- body = (
49
- body.rstrip("\n") + f'\n\n[tool.{TABLE}]\napp = "{a.app}"\nmodels = "{a.models}"\nmigrations = "migrations"\n'
50
- )
50
+ keys = f'app = "{a.app}"\nmodels = "{a.models}"\nmigrations = "migrations"\n'
51
51
  if a.engine != "portable":
52
- body += f'engine = "{a.engine}"\n'
52
+ keys += f'engine = "{a.engine}"\n'
53
+ if a.package:
54
+ pkg = Path(a.package)
55
+ if not (Path.cwd() / pkg / "__init__.py").is_file():
56
+ sys.exit(f"{pkg} is not a package folder (no __init__.py)")
57
+ (Path.cwd() / pkg / FILE).write_text(keys, encoding="utf-8")
58
+ (Path.cwd() / pkg / "migrations").mkdir(exist_ok=True)
59
+ body = body.rstrip("\n") + f'\n\n[tool.{TABLE}]\nfile = "{(pkg / FILE).as_posix()}"\n'
60
+ where = f"{(pkg / FILE).as_posix()} (pointed to from {pp.name}); {(pkg / 'migrations').as_posix()}/ ready"
61
+ else:
62
+ body = body.rstrip("\n") + f"\n\n[tool.{TABLE}]\n{keys}"
63
+ (Path.cwd() / "migrations").mkdir(exist_ok=True)
64
+ where = f"[tool.{TABLE}] to {pp}; migrations/ ready"
53
65
  pp.write_text(body, encoding="utf-8")
54
- (Path.cwd() / "migrations").mkdir(exist_ok=True)
55
- print(f"wrote [tool.{TABLE}] to {pp}; migrations/ ready. Next: strata-db revision -m 'initial'")
66
+ print(f"wrote {where}. Next: strata-db revision -m 'initial'")
56
67
 
57
68
 
58
69
  def cmd_new_app(a: argparse.Namespace) -> None:
@@ -103,7 +114,9 @@ def cmd_revision(a: argparse.Namespace) -> None:
103
114
  path = m.revision(eng, p.migrations_dir, p.metadata, a.message, autogenerate=not a.empty)
104
115
  eng.dispose()
105
116
  if path:
106
- print(f"wrote {Path(path).relative_to(p.root).as_posix()}: review it, then commit it")
117
+ shown = Path(path).resolve()
118
+ shown = shown.relative_to(Path.cwd().resolve()) if shown.is_relative_to(Path.cwd().resolve()) else shown
119
+ print(f"wrote {shown.as_posix()}: review it, then commit it")
107
120
  else:
108
121
  print("no changes: the models match the migrations")
109
122
 
@@ -162,6 +175,7 @@ def main(argv: list[str] | None = None) -> None:
162
175
  s.add_argument("--app", required=True)
163
176
  s.add_argument("--models", required=True)
164
177
  s.add_argument("--engine", choices=["portable", "postgres"], default="portable")
178
+ s.add_argument("--package", metavar="DIR", help="declare in DIR/strata-db.toml, so an installed wheel has it")
165
179
  s.set_defaults(f=cmd_init)
166
180
  s = sub.add_parser("new-app", help="role and schema on the shared server")
167
181
  s.add_argument("name", nargs="?")
@@ -12,6 +12,9 @@ has no schemas.
12
12
 
13
13
  The shared database has no built-in name: the name is the owner's, and this package is public (AGENTS.md rule 4).
14
14
 
15
+ An app that should still work before it is given a database (a checkout, a new deployment) passes a `default`, usually
16
+ `local_url(SETTINGS)`: a SQLite file in its settings folder. It is used only when nothing above is set.
17
+
15
18
  A real Postgres database is opt-in (see `strata_python.db.guard`): url_for() and connect() refuse one unless the
16
19
  process has `STRATA_DB_LIVE=1`, and refuse it always during tests.
17
20
  """
@@ -20,6 +23,10 @@ from __future__ import annotations
20
23
 
21
24
  import os
22
25
  import re
26
+ from typing import TYPE_CHECKING
27
+
28
+ if TYPE_CHECKING:
29
+ from strata_python.settings import Settings
23
30
 
24
31
  URL = "STRATA_DB_URL"
25
32
  DATABASE = "STRATA_DB_DATABASE"
@@ -67,19 +74,36 @@ def with_search_path(url: str, schema: str) -> str:
67
74
  return url + ("&" if "?" in url else "?") + f"options=-csearch_path%3D{schema}"
68
75
 
69
76
 
70
- def resolve_url(app: str, schema: str | None = None) -> str:
71
- """Where `app`'s data is (see the module docstring), without the live-database check."""
77
+ def local_url(home: Settings | str | os.PathLike[str], name: str | None = None) -> str:
78
+ """A SQLite file for an app with no database configured: `<home>/<name>.db`, where home is a folder or the app's
79
+ `Settings` (its folder, `<APP>_HOME` or `~/.<app>`, and its name). `connect` makes the folder."""
80
+ from strata_python.settings import Settings
81
+
82
+ if isinstance(home, Settings):
83
+ folder, name = home.home(), name or home.app
84
+ else:
85
+ folder = os.fspath(home)
86
+ if not name:
87
+ raise ValueError("local_url(folder) needs the app name")
88
+ return normalise_url(os.path.join(folder, f"{name}.db"))
89
+
90
+
91
+ def resolve_url(app: str, schema: str | None = None, *, default: str | None = None) -> str:
92
+ """Where `app`'s data is (see the module docstring), without the live-database check. `default` (a URL or a
93
+ path) is used when nothing is configured, instead of raising DatabaseNotConfigured."""
72
94
  for var in (URL, env_name(app)):
73
95
  if value := os.environ.get(var):
74
96
  return with_search_path(normalise_url(value), schema or app)
97
+ if default is not None and not shared_database():
98
+ return with_search_path(normalise_url(default), schema or app) # as an environment URL (review finding)
75
99
  return schema_url(schema or app)
76
100
 
77
101
 
78
- def url_for(app: str, schema: str | None = None) -> str:
102
+ def url_for(app: str, schema: str | None = None, *, default: str | None = None) -> str:
79
103
  """resolve_url(), refused (guard.LiveDatabaseRefused) when it is a real Postgres database and the process has
80
104
  not opted in with `STRATA_DB_LIVE=1`, or is running tests."""
81
105
  from .guard import check_url
82
106
 
83
- url = resolve_url(app, schema)
107
+ url = resolve_url(app, schema, default=default)
84
108
  check_url(url, f"url_for({app!r})")
85
109
  return url
@@ -2,6 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import os
5
6
  import re
6
7
  import sqlite3
7
8
  from collections.abc import Generator
@@ -27,6 +28,9 @@ def connect(app_or_url: str, **kw: Any) -> Engine:
27
28
  engine = create_engine(url, **kw)
28
29
  if engine.dialect.name == "sqlite":
29
30
  sqlite_pragmas(engine)
31
+ file = engine.url.database
32
+ if file and file != ":memory:" and not file.startswith("file:"):
33
+ os.makedirs(os.path.dirname(os.path.abspath(file)), exist_ok=True) # a fallback in a folder not made yet
30
34
  return engine
31
35
 
32
36