strata-python 0.2.4__py3-none-any.whl → 0.2.6__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.
- strata_python/cli.py +45 -2
- strata_python/contracts.py +9 -0
- strata_python/db/__init__.py +7 -1
- strata_python/db/cli.py +23 -9
- strata_python/db/config.py +28 -4
- strata_python/db/engine.py +4 -0
- strata_python/db/project.py +58 -7
- strata_python/db/web.py +103 -0
- strata_python/files.py +247 -0
- strata_python/http.py +326 -0
- strata_python/images.py +107 -0
- strata_python/media.py +323 -0
- strata_python/public_check.py +122 -19
- strata_python/settings.py +99 -25
- strata_python/stats.py +196 -0
- strata_python/tasks/__init__.py +2 -1
- strata_python/tasks/status.py +1 -16
- strata_python/testing.py +13 -0
- strata_python/web.py +10 -1
- {strata_python-0.2.4.dist-info → strata_python-0.2.6.dist-info}/METADATA +84 -21
- {strata_python-0.2.4.dist-info → strata_python-0.2.6.dist-info}/RECORD +24 -18
- {strata_python-0.2.4.dist-info → strata_python-0.2.6.dist-info}/WHEEL +0 -0
- {strata_python-0.2.4.dist-info → strata_python-0.2.6.dist-info}/entry_points.txt +0 -0
- {strata_python-0.2.4.dist-info → strata_python-0.2.6.dist-info}/licenses/LICENSE +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: strata-python
|
|
3
|
-
Version: 0.2.
|
|
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
|
|
@@ -37,6 +37,8 @@ Requires-Dist: pytest-timeout<3,>=2; extra == 'dev'
|
|
|
37
37
|
Requires-Dist: pytest-xdist<4,>=3; extra == 'dev'
|
|
38
38
|
Requires-Dist: ruff<0.18,>=0.17; extra == 'dev'
|
|
39
39
|
Requires-Dist: ty<0.1,>=0.0.99; extra == 'dev'
|
|
40
|
+
Provides-Extra: images
|
|
41
|
+
Requires-Dist: pillow<14,>=13; extra == 'images'
|
|
40
42
|
Provides-Extra: pdf
|
|
41
43
|
Requires-Dist: pillow<14,>=13; extra == 'pdf'
|
|
42
44
|
Requires-Dist: pypdfium2<6,>=4.30; extra == 'pdf'
|
|
@@ -51,19 +53,24 @@ Common code for the strata Python web server apps (FastAPI + CLI), the Python co
|
|
|
51
53
|
|---|---|
|
|
52
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)` |
|
|
53
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`) |
|
|
54
|
-
| `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` |
|
|
55
|
-
| `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 |
|
|
56
|
-
| `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 |
|
|
57
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` |
|
|
58
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
|
+
| `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)`) |
|
|
62
|
+
| `strata_python.http` | `Http(user_agent, min_interval=...)`, the polite client for other people's APIs: a gap per host across threads (and processes with `throttle_file`), Retry-After as seconds or a date, a cool-down for a host that keeps saying 429, retries that never replay a write, a size cap, an optional `DiskCache`, and errors returned as a `Reply` (`raise_for_status()`, `get_json()` for code that wants exceptions) |
|
|
63
|
+
| `strata_python.media` | `probe(path)` (a typed `Probe`: duration, format, tags, streams, chapters, ffprobe's warnings), `duration`, `ffmpeg(args, progress=...)` raising `MediaError` with ffmpeg's own reason, `available()` |
|
|
64
|
+
| `strata_python.images` (extra `[images]`) | `thumbnail(src, px, cache_dir=...)` (an upright JPEG, made once, keyed on the file, never enlarged, the app's own reader through `make=`), `open_upright`, `flatten` (alpha and 16-bit greys to 8-bit RGB), `jpeg_bytes` |
|
|
65
|
+
| `strata_python.stats` | Pairwise rankings and eval statistics in pure Python: `bradley_terry` (ties, an optional side advantage, Elo-scale `ratings()`), `intervals` (bootstrap), `head_to_head`, `votes_from(judgments)`, `wilson`, `mcnemar`, `holm` |
|
|
59
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 |
|
|
60
67
|
| `strata_python.http_server` / `live` | A real scripted HTTP server and a real uvicorn server on loopback, for tests that make actual requests |
|
|
61
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` |
|
|
62
|
-
| `strata_python.testing` | The fakes behind those fixtures (`FakeResponse`, `http_error`, `FakeUrlopen`, `FakePopen`, `FakeRun`, `Sleeper`) `FakeModels`,
|
|
63
|
-
| `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,
|
|
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 |
|
|
64
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 |
|
|
65
72
|
| `strata-check` | The one gate: lockfile, ruff, `ruff format`, pyright strict, ty, unit tests with coverage |
|
|
66
|
-
| `strata-public-check` | Fails on email addresses, private IPv4 addresses, home-folder paths and the
|
|
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`) |
|
|
67
74
|
|
|
68
75
|
## Move an app onto it
|
|
69
76
|
|
|
@@ -128,6 +135,7 @@ SETTINGS = Settings(
|
|
|
128
135
|
Setting("data_dir", default=lambda: "/srv/myapp", normalise=absolute_path),
|
|
129
136
|
Setting("greeting", default="Hello", normalise=non_empty),
|
|
130
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
|
|
131
139
|
ListSetting("source_roots", item=absolute_path, env="MYAPP_SOURCES"), # MYAPP_SOURCES split on os.pathsep
|
|
132
140
|
],
|
|
133
141
|
prefix="MYAPP", # only if the app already runs with other variable names
|
|
@@ -140,13 +148,15 @@ SETTINGS.folder("data_dir") # the value as a folder, created if missing
|
|
|
140
148
|
|
|
141
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.
|
|
142
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
|
+
|
|
143
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:
|
|
144
154
|
|
|
145
155
|
```python
|
|
146
156
|
from strata_python.db.settings import TableStore, settings_table
|
|
147
157
|
|
|
148
|
-
SETTINGS_TABLE = settings_table(Base.metadata)
|
|
149
|
-
SETTINGS.bind(TableStore(engine, SETTINGS_TABLE))
|
|
158
|
+
SETTINGS_TABLE = settings_table(Base.metadata) # in models.py, so the migrations create it
|
|
159
|
+
SETTINGS.bind(TableStore(engine, SETTINGS_TABLE)) # any object with load() and update(changes) is a store
|
|
150
160
|
```
|
|
151
161
|
|
|
152
162
|
### 4. The server
|
|
@@ -165,11 +175,15 @@ def create_app():
|
|
|
165
175
|
Two more that replace code most servers carry:
|
|
166
176
|
|
|
167
177
|
```python
|
|
168
|
-
web.add_error_handlers(app)
|
|
169
|
-
|
|
170
|
-
web.add_system(
|
|
171
|
-
|
|
172
|
-
|
|
178
|
+
web.add_error_handlers(app) # ValueError 400, PermissionError 403, KeyError and FileNotFoundError 404,
|
|
179
|
+
# tasks.Conflict 409, client.Rejected 502, client.Unavailable 503: {detail, payload}
|
|
180
|
+
web.add_system(
|
|
181
|
+
app,
|
|
182
|
+
__version__,
|
|
183
|
+
commit=web.source_commit(__file__),
|
|
184
|
+
folders={"data": lambda: SETTINGS.get("data_dir")},
|
|
185
|
+
services={"strata-models": "http://127.0.0.1:8366"},
|
|
186
|
+
) # GET /api/system, a SystemInfo
|
|
173
187
|
```
|
|
174
188
|
|
|
175
189
|
Delete the app's `guard()` (or each route's `try/except` raising `HTTPException`), passing its own exceptions as `add_error_handlers(app, {BookLocked: 423})`, and its `/api/system` route. Give `base_app` the same `commit=` so `/api/health` says which source the server runs. Declare a route's answer with a shape from `strata_python.contracts` (`response_model=Page[Task]`) where the app already returns that shape, so the web app's types can come from `/api/openapi.json`.
|
|
@@ -197,6 +211,8 @@ def main(argv=None):
|
|
|
197
211
|
return args.fn(args)
|
|
198
212
|
```
|
|
199
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
|
+
|
|
200
216
|
Delete the hand-written `doctor`, `set` and `serve` subparsers. Each app's port belongs in its deploy units, not in this library.
|
|
201
217
|
|
|
202
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:
|
|
@@ -219,9 +235,9 @@ A check returns `(status, text)` with status `ok`, `missing`, `slow` (works, but
|
|
|
219
235
|
Drop the `strata-models-client` path or git dependency and change the import. The functions, their arguments and the exceptions are the same:
|
|
220
236
|
|
|
221
237
|
```python
|
|
222
|
-
from strata_python.clients import models as sm
|
|
238
|
+
from strata_python.clients import models as sm # was: import strata_models_client as sm
|
|
223
239
|
|
|
224
|
-
page = sm.OcrPage.from_json(sm.ocr("/path/page.png", app="strata-scan"))
|
|
240
|
+
page = sm.OcrPage.from_json(sm.ocr("/path/page.png", app="strata-scan")) # typed: page.lines[0].words[0].box
|
|
225
241
|
talk = sm.Transcript.from_json(sm.transcribe("/path/talk.wav", app="strata-360"))
|
|
226
242
|
with sm.gpu_lease("strata-stills", vram_gb=4):
|
|
227
243
|
run_my_own_cuda_code()
|
|
@@ -246,15 +262,48 @@ Replace the app's job dicts and loops with `strata_python.tasks`:
|
|
|
246
262
|
```python
|
|
247
263
|
from strata_python.tasks.queue import Job, Queue, Worker
|
|
248
264
|
|
|
249
|
-
QUEUE = Queue(engine, JOBS, on_fail=cascade)
|
|
265
|
+
QUEUE = Queue(engine, JOBS, on_fail=cascade) # on_fail(conn, job, error), in the failing transaction
|
|
250
266
|
QUEUE.enqueue("ocr", {"page": 3}, domain="book:12", dedupe=True, resources=["gpu"], timeout_s=600)
|
|
251
|
-
WORKER = Worker(
|
|
252
|
-
QUEUE
|
|
253
|
-
|
|
267
|
+
WORKER = Worker(
|
|
268
|
+
QUEUE, {"ocr": ocr_page}, concurrency=2
|
|
269
|
+
).start() # a job process per thread, reused; recovers dead workers' jobs
|
|
270
|
+
QUEUE.page(state="running", after=cursor) # Page[Task] for GET /api/jobs
|
|
271
|
+
QUEUE.cancel(job_id)
|
|
272
|
+
QUEUE.retry(job_id)
|
|
273
|
+
QUEUE.prune(older_than_s=30 * 86400)
|
|
254
274
|
```
|
|
255
275
|
|
|
256
276
|
A handler is a module-level `fn(job) -> result` that reads `job.options` and reports progress. By default jobs run in job processes (`python -m strata_python.tasks.child`, one per worker thread, kept between jobs and importing the handlers by name), so a cancel, a timeout or `WORKER.stop()` kills the job and every tool it started, and jobs die with the server; a quick job costs about half a millisecond more than on a thread (3.5 ms against 2.9 ms a job on SQLite), since only a kill starts a new process. `max_jobs=N` replaces a process after N jobs, for code that leaks. The worker checks at start-up that every handler can be imported. `Worker(lower_priority=True)` runs the jobs at idle CPU and disk priority. `Worker(isolate=False)` runs handlers on the server's threads instead, where they return early when `job.stopping`. In tests, `QUEUE.step(handlers)` claims and runs one job in the test's own thread.
|
|
257
277
|
|
|
278
|
+
### 6c. Files, web APIs, media, pictures and rankings
|
|
279
|
+
|
|
280
|
+
Each of these replaces code that two to six apps wrote for themselves; move to it when you next touch that code.
|
|
281
|
+
|
|
282
|
+
- **Writes.** Every `tmp = path + ".tmp"; ...; os.replace(tmp, path)` becomes `write_json_atomic(path, data)` (or `write_text_atomic`, `write_bytes_atomic`, `with atomic_open(path, "wb") as f:`). A tool that writes the file itself writes to `with atomic_path(out) as tmp:`; the temp name keeps the extension, so `ffmpeg ... tmp` still picks the format. Reads that tolerate a missing or broken file are `read_json(path, default)`. Delete the app's `_save`, `write_status` and `.part` helpers.
|
|
283
|
+
- **Hashes and keys.** `sha256(path)` (bytes, for a `LargeBinary` column) and `sha256_hex(path)` replace listory's two copies, filecat's and stills' scripts'. `quick_fingerprint(path)` is 360's `clips.fingerprint` idea on SHA-256 (an app that stored the old 12-character SHA-1 keeps its own until it re-keys). A cache that must follow a file's changes keys on `stat_key(path, px, version)`.
|
|
284
|
+
- **Paths from a request.** `files.inside(root, name)` before opening a file a request names; it raises `ValueError` (400 with `add_error_handlers`) for `..`, an absolute path elsewhere, or a link out of the root.
|
|
285
|
+
- **Other people's APIs.** One `Http` per service, at module level so its gap is shared:
|
|
286
|
+
|
|
287
|
+
```python
|
|
288
|
+
from strata_python.files import DiskCache
|
|
289
|
+
from strata_python.http import Http
|
|
290
|
+
|
|
291
|
+
NOMINATIM = Http(
|
|
292
|
+
"myapp/1.0 (reverse geocoding of my own tracks)",
|
|
293
|
+
min_interval=1.1,
|
|
294
|
+
throttle_file=cache_dir / ".nominatim",
|
|
295
|
+
cache=DiskCache(cache_dir),
|
|
296
|
+
)
|
|
297
|
+
reply = NOMINATIM.get(URL, params={"lat": lat, "lon": lon, "format": "json"}, cache_s=30 * 86400)
|
|
298
|
+
if reply.ok:
|
|
299
|
+
place = reply.json() # reply.status == 0 when unreachable; reply.limited when rate limited
|
|
300
|
+
```
|
|
301
|
+
|
|
302
|
+
The User-Agent names the app and what it is for, never a person. Delete the app's `_throttle`, `_retry_after`, `_cool_until`, `_open`/`_get` wrappers and its response cache; listory's `providers.base.Http` keeps its own `emit` through `observe=`. A provider result worth keeping (not an HTTP body) is `DiskCache(...).json(key, fetch, max_age_s)`.
|
|
303
|
+
- **ffprobe and ffmpeg.** `media.probe(path)` replaces every hand-written `ffprobe -show_entries` call; read `info.duration`, `info.audio.sample_rate`, `info.video.fps`, `info.chapters`, `info.tags`, and `info.raw` for anything else. `media.ffmpeg(args)` adds `-nostdin -hide_banner -v error -y` and raises `MediaError` with ffmpeg's last lines; `progress=` reports seconds written. Map `MediaError` in `add_error_handlers` if the app answers it over HTTP. A doctor row is `cli.program("ffmpeg")`.
|
|
304
|
+
- **Thumbnails** (`strata-python[images]`): `images.thumbnail(src, px, cache_dir=settings.thumbs_dir())` returns the cached JPEG's path for a `FileResponse`. An app with its own reader (stills' raw previews, 360's video frames) passes `make=lambda path, px: ...` returning a Pillow image. Bump `version=` when the way a thumbnail is made changes.
|
|
305
|
+
- **Rankings and evals.** `stats.bradley_terry(votes, side=True)` with votes as `(a, b, "a" | "b" | "tie")` (or `stats.votes_from(judgments)`), `.ratings()` for the Elo scale, `stats.intervals(votes)` for how far to trust a gap; `wilson`, `mcnemar` and `holm` for eval write-ups. The numpy bootstraps over items in strata-models' evals stay there until a second app needs them.
|
|
306
|
+
|
|
258
307
|
### 7. Tests
|
|
259
308
|
|
|
260
309
|
The pytest plugin loads itself once strata-python is installed. Configure it in `pyproject.toml`:
|
|
@@ -344,7 +393,21 @@ migrations = "migrations" # the app's Alembic revisions, unchanged
|
|
|
344
393
|
```
|
|
345
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`.
|
|
346
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`).
|
|
347
|
-
- 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.
|
|
348
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:
|
|
349
412
|
|
|
350
413
|
```python
|
|
@@ -1,48 +1,54 @@
|
|
|
1
1
|
strata_python/__init__.py,sha256=eF-f5-pwPokTJjoq063Hr78JTnjPkVm-3hQBN9tXqDs,1723
|
|
2
2
|
strata_python/check.py,sha256=lFjXuPjVIWn6dBu2yMKIW-76RloUREijuMHCRsBW4Z8,2932
|
|
3
|
-
strata_python/cli.py,sha256=
|
|
3
|
+
strata_python/cli.py,sha256=guO3aDiSe8Ri4-0aHDLCwUKMiu6rLpnSo7leWzf0Ehw,8170
|
|
4
4
|
strata_python/client.py,sha256=S-cfDQqbO0dJ951TAiFyW2CbkFQkN1OWnUBCYaTO3Lg,7911
|
|
5
|
-
strata_python/contracts.py,sha256=
|
|
5
|
+
strata_python/contracts.py,sha256=DNyCi8pKXrfaRIadJ3DuAH8YUbXh4fVVY5T21sAJf98,6379
|
|
6
|
+
strata_python/files.py,sha256=jJMFnzsigY29f6EcpjEtbBnc-66FCOuw875epYMOSjg,11423
|
|
7
|
+
strata_python/http.py,sha256=dltLx14TqQGuLhFeFoYyNZiOVAXx7ZEeXPQwPjaT2hc,16152
|
|
6
8
|
strata_python/http_server.py,sha256=64uYWy4zFxughOgtvkssGXMJDZ7jhRj1bxUIfnzte8w,4475
|
|
9
|
+
strata_python/images.py,sha256=nNQ7fQxkpmnTf5iotYlR7VejxCfthXgIpMEGTsLvNVE,4872
|
|
7
10
|
strata_python/live.py,sha256=kNY6h6gMxBo9l78UoGUIWjcADeZi4eZuAEp0jqDowEE,1215
|
|
11
|
+
strata_python/media.py,sha256=66Pk1_CTHyApKlWD8LuzS08O3EOx-7dNaj9AkEbNxmw,12647
|
|
8
12
|
strata_python/oslib.py,sha256=vfZDUCNZnTjjjB704eoyNXlPFCz2yVR3puFljE0Z1gE,12137
|
|
9
|
-
strata_python/public_check.py,sha256=
|
|
13
|
+
strata_python/public_check.py,sha256=2N1X15D578QFgN32TUazFDj6SOHtAJhjOgoZNOQu_vU,13398
|
|
10
14
|
strata_python/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
11
15
|
strata_python/pytest_plugin.py,sha256=BaD-XokrX1PMMj0Cqxj9IJTb6EXBp7ozQZ6SSCDumMg,7223
|
|
12
|
-
strata_python/settings.py,sha256=
|
|
13
|
-
strata_python/
|
|
14
|
-
strata_python/
|
|
16
|
+
strata_python/settings.py,sha256=YeQMJwyqFNX7L3bbgbwRN1hdfzBem9uWxqg_WVswT-A,18688
|
|
17
|
+
strata_python/stats.py,sha256=nc6qXELpMg7eK0xjFo45M1FK7FR3q89be3VCJzExKYc,8354
|
|
18
|
+
strata_python/testing.py,sha256=WvakeIAJtdeOrIDq32WWXfWkfBkMQ2cUU279L0Ebhs0,20888
|
|
19
|
+
strata_python/web.py,sha256=-AWb9Ad2e870zbr4OT1oZS1IpOZ0nd-jdpu4ICOHejE,13528
|
|
15
20
|
strata_python/clients/__init__.py,sha256=xivuysmYG7rbCGProVNvdSs-h4xVFQsuqUY6EwzuJbk,182
|
|
16
21
|
strata_python/clients/models.py,sha256=vxnvINQ_xQRbU848BTnGyjlTcr1-bhv6GAkrCN5ZDuU,30314
|
|
17
|
-
strata_python/db/__init__.py,sha256=
|
|
22
|
+
strata_python/db/__init__.py,sha256=Vx28OmktWBhEM9gj1VxoxNuJDvdtpYoJ3-prrzoBR40,4009
|
|
18
23
|
strata_python/db/__main__.py,sha256=nHCtenRtjL_Ouig4FHh60dax2oILeVdoIIKrxXEc6Ss,106
|
|
19
|
-
strata_python/db/cli.py,sha256=
|
|
20
|
-
strata_python/db/config.py,sha256=
|
|
21
|
-
strata_python/db/engine.py,sha256=
|
|
24
|
+
strata_python/db/cli.py,sha256=kCNHDlFIzECtvExUGBaJ0BK4ZqesGHS7Jjnhh-gWIpI,10896
|
|
25
|
+
strata_python/db/config.py,sha256=1Bjz5T5jOTeeB_6e9I2BJB62aqM8UDjoGd2JsJ7NLaE,5098
|
|
26
|
+
strata_python/db/engine.py,sha256=fcHJeLiIXDxWzXzSkG3HD_QM3VI1VtksSvFfQzR_0O8,2165
|
|
22
27
|
strata_python/db/guard.py,sha256=HyRtDMRgTWFgT9D4gNomA18ErR1mqJbzJgtU7xAqBG8,6722
|
|
23
28
|
strata_python/db/migrations.py,sha256=Hb77afQNjtKS2DD-zmen4BscbAx9DRjLHtcPOdzuaGo,12138
|
|
24
29
|
strata_python/db/models.py,sha256=bWg1xgn-VgDLnFe0Ps_2hiYD5fp-_8W8mCErATS3RQs,3005
|
|
25
|
-
strata_python/db/project.py,sha256=
|
|
30
|
+
strata_python/db/project.py,sha256=JKkjYOWtiVJ5YQdDctLlI2L9nfyk76wMq8SJKJCTdVA,6393
|
|
26
31
|
strata_python/db/pytest_plugin.py,sha256=opJb5AI8Dy8IYqkx6IcZV1KBeMB4DHmnaEKd36h_r9Q,8978
|
|
27
32
|
strata_python/db/scratch.py,sha256=mlb4a1MTevhBS3WWIJOvUiyggLGeBR9NbXi8Jh8Rf2k,5059
|
|
28
33
|
strata_python/db/settings.py,sha256=sg1xDhqYhTzUx8_8-VKJBlpb1qRKKYhujJYZ8KeIbbY,2635
|
|
29
34
|
strata_python/db/testing.py,sha256=U39cwmg_6Dp4XPyc1Z2NWVgSGI_Q93Y--78_7PgEwes,1979
|
|
30
35
|
strata_python/db/testserver.py,sha256=I5__od7FEjNBcYYcJqmzLA_5t1wRqJ85NBukZMebS4Q,8806
|
|
36
|
+
strata_python/db/web.py,sha256=CmSVg7BNuP_uHmG7WsnN0VF7xYKskuyDQBb37EdapYo,4223
|
|
31
37
|
strata_python/db/_alembic/env.py,sha256=gXzRn02h59PB_1RaABkaT6GuyuzPQCZh3Z5ml2JlS34,1125
|
|
32
38
|
strata_python/db/_alembic/script.py.mako,sha256=04kgeBtNMa4cCnG8CfQcKt6P6rnloIfj8wy0u_DBydM,704
|
|
33
39
|
strata_python/pages/__init__.py,sha256=6QsTqJbFiuLCxywt8C0D6nyXRXjpzI1Xoo5u6rK9toQ,665
|
|
34
40
|
strata_python/pages/model.py,sha256=8Skz3eishAZiNHIHzScI0g60wGpH6jZ3vNc0LpMZ4q4,9821
|
|
35
41
|
strata_python/pages/render.py,sha256=Q3_xliHCkDoGKXNLT3KksaYtfNnm0T2-p-7FhOu6loQ,12421
|
|
36
|
-
strata_python/tasks/__init__.py,sha256=
|
|
42
|
+
strata_python/tasks/__init__.py,sha256=jX-aXJFaivpjt6-WfHd_Xg4YVzLQeRYvAvyjKUTGwbw,1561
|
|
37
43
|
strata_python/tasks/child.py,sha256=1ZpQwlFx0bbNXD5UKmPrlcEogCf-MrPGSOSK8TpqllA,11133
|
|
38
44
|
strata_python/tasks/flight.py,sha256=FjWl7M1Y1qV5Mcr3Qwu6H464sobzpYEjQAKcz_GjPH4,5704
|
|
39
45
|
strata_python/tasks/progress.py,sha256=AqfrrDA-ZBkha98ex0kQIzwk45TiTe_pX1FhYyi2u2I,3636
|
|
40
46
|
strata_python/tasks/queue.py,sha256=b4in3XnplTlapL_ECTs_WYJcittYj3iKz7q_fQ8_HDY,32188
|
|
41
47
|
strata_python/tasks/retry.py,sha256=NztmOf3Q-rl5y3CZlfP1qcDqPT0jOiIDjMfD-MUkr5s,3995
|
|
42
|
-
strata_python/tasks/status.py,sha256=
|
|
48
|
+
strata_python/tasks/status.py,sha256=cZvYghNAGJRlpVIJAtUSb5pW19UbxR6bNQU4etJMYN4,7440
|
|
43
49
|
strata_python/tasks/ticker.py,sha256=V6JLWgAGV5sIGeX1vp4t35omuRvvB6AYWv_lzJAq69Y,2860
|
|
44
|
-
strata_python-0.2.
|
|
45
|
-
strata_python-0.2.
|
|
46
|
-
strata_python-0.2.
|
|
47
|
-
strata_python-0.2.
|
|
48
|
-
strata_python-0.2.
|
|
50
|
+
strata_python-0.2.6.dist-info/METADATA,sha256=dDY27gm38DSVlkMD1G1_GIVYjyYut3TsTEfbb_YAwIM,37541
|
|
51
|
+
strata_python-0.2.6.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
52
|
+
strata_python-0.2.6.dist-info/entry_points.txt,sha256=6RVv-uDumVQ-KY2YdvKwd5R3l6P9WQD4kPtPOKKEM-I,256
|
|
53
|
+
strata_python-0.2.6.dist-info/licenses/LICENSE,sha256=9yVMCPoK7unONyTAiDYjMTt3MZPGJ639nWOwxyNsZGg,1066
|
|
54
|
+
strata_python-0.2.6.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|