strata-python 0.2.0__tar.gz → 0.2.1__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 (51) hide show
  1. strata_python-0.2.1/CHANGELOG.md +39 -0
  2. strata_python-0.2.1/PKG-INFO +274 -0
  3. strata_python-0.2.1/README.md +233 -0
  4. {strata_python-0.2.0 → strata_python-0.2.1}/pyproject.toml +37 -18
  5. {strata_python-0.2.0 → strata_python-0.2.1}/src/strata_python/__init__.py +2 -1
  6. strata_python-0.2.1/src/strata_python/db/__init__.py +113 -0
  7. strata_python-0.2.1/src/strata_python/db/__main__.py +5 -0
  8. strata_python-0.2.1/src/strata_python/db/_alembic/env.py +24 -0
  9. strata_python-0.2.1/src/strata_python/db/_alembic/script.py.mako +28 -0
  10. strata_python-0.2.1/src/strata_python/db/cli.py +199 -0
  11. strata_python-0.2.1/src/strata_python/db/config.py +85 -0
  12. strata_python-0.2.1/src/strata_python/db/engine.py +53 -0
  13. strata_python-0.2.1/src/strata_python/db/guard.py +159 -0
  14. strata_python-0.2.1/src/strata_python/db/migrations.py +243 -0
  15. strata_python-0.2.1/src/strata_python/db/models.py +50 -0
  16. strata_python-0.2.1/src/strata_python/db/project.py +85 -0
  17. strata_python-0.2.1/src/strata_python/db/pytest_plugin.py +151 -0
  18. strata_python-0.2.1/src/strata_python/db/scratch.py +143 -0
  19. strata_python-0.2.1/src/strata_python/db/testing.py +43 -0
  20. strata_python-0.2.1/src/strata_python/db/testserver.py +205 -0
  21. {strata_python-0.2.0 → strata_python-0.2.1}/src/strata_python/pytest_plugin.py +70 -1
  22. strata_python-0.2.1/src/strata_python/testing.py +257 -0
  23. {strata_python-0.2.0 → strata_python-0.2.1}/tests/conftest.py +2 -2
  24. strata_python-0.2.1/tests/integration/test_db_cli.py +131 -0
  25. strata_python-0.2.1/tests/unit/test_db.py +836 -0
  26. {strata_python-0.2.0 → strata_python-0.2.1}/tests/unit/test_plugin.py +56 -0
  27. strata_python-0.2.1/tests/unit/test_testing.py +123 -0
  28. strata_python-0.2.0/PKG-INFO +0 -82
  29. strata_python-0.2.0/README.md +0 -54
  30. {strata_python-0.2.0 → strata_python-0.2.1}/.gitignore +0 -0
  31. {strata_python-0.2.0 → strata_python-0.2.1}/LICENSE +0 -0
  32. {strata_python-0.2.0 → strata_python-0.2.1}/src/strata_python/check.py +0 -0
  33. {strata_python-0.2.0 → strata_python-0.2.1}/src/strata_python/cli.py +0 -0
  34. {strata_python-0.2.0 → strata_python-0.2.1}/src/strata_python/http_server.py +0 -0
  35. {strata_python-0.2.0 → strata_python-0.2.1}/src/strata_python/live.py +0 -0
  36. {strata_python-0.2.0 → strata_python-0.2.1}/src/strata_python/oslib.py +0 -0
  37. {strata_python-0.2.0 → strata_python-0.2.1}/src/strata_python/public_check.py +0 -0
  38. {strata_python-0.2.0 → strata_python-0.2.1}/src/strata_python/py.typed +0 -0
  39. {strata_python-0.2.0 → strata_python-0.2.1}/src/strata_python/settings.py +0 -0
  40. {strata_python-0.2.0 → strata_python-0.2.1}/src/strata_python/web.py +0 -0
  41. {strata_python-0.2.0 → strata_python-0.2.1}/tests/integration/test_serve.py +0 -0
  42. {strata_python-0.2.0 → strata_python-0.2.1}/tests/integration/test_strata_check.py +0 -0
  43. {strata_python-0.2.0 → strata_python-0.2.1}/tests/unit/test_check.py +0 -0
  44. {strata_python-0.2.0 → strata_python-0.2.1}/tests/unit/test_cli.py +0 -0
  45. {strata_python-0.2.0 → strata_python-0.2.1}/tests/unit/test_http_server.py +0 -0
  46. {strata_python-0.2.0 → strata_python-0.2.1}/tests/unit/test_live.py +0 -0
  47. {strata_python-0.2.0 → strata_python-0.2.1}/tests/unit/test_oslib.py +0 -0
  48. {strata_python-0.2.0 → strata_python-0.2.1}/tests/unit/test_package.py +0 -0
  49. {strata_python-0.2.0 → strata_python-0.2.1}/tests/unit/test_public_check.py +0 -0
  50. {strata_python-0.2.0 → strata_python-0.2.1}/tests/unit/test_settings.py +0 -0
  51. {strata_python-0.2.0 → strata_python-0.2.1}/tests/unit/test_web.py +0 -0
@@ -0,0 +1,39 @@
1
+ # Changelog
2
+
3
+ What each release adds or changes for an app that depends on strata-python, newest first. Every breaking change says what to do in one line. Versions follow [semver](https://semver.org); while the version is 0.x a minor release may break, so depend on `strata-python>=0.N,<0.N+1`. Why each change was made is in [DEVLOG.md](DEVLOG.md).
4
+
5
+ ## Unreleased
6
+
7
+ ## 0.2.1 (2026-11-14)
8
+
9
+ ### Added
10
+
11
+ - `strata_python.testing`: the test doubles every app copied into `tests/utils/fakes.py` (`FakeResponse`, `http_error`, `FakeUrlopen`, `FakePopen`, `FakeRun`, plus `Sleeper`), and CLI runners `run_cli(main, *args, check=True)` and `run_module(module, *args, src=..., check=True)` returning `CliResult(stdout, stderr, code)`. Delete the app's `fakes.py` and import from here.
12
+ - Plugin fixtures `fake_urlopen`, `fake_popen`, `fake_run` and `no_sleep`, so the app's conftest no longer defines them. `fake_popen` gives each test its own `.instances`. `FakeUrlopen.calls` entries are `Call` objects that still answer `call["url"]`.
13
+ - `strata_env = ["KEY=VALUE", ...]` in `[tool.pytest.ini_options]` sets the app's own variables for every test (`{env}` is the isolated folder), for what each app's `isolated_env` copy added.
14
+ - `strata-python[dev]`: ruff, pyright, ty, httpx and the pytest plugins at the versions `strata-check` is tested with. An app's dev group becomes `dev = ["strata-python[dev]"]`; delete those packages from it.
15
+ - `strata-python[db]` and `strata_python.db`: the shared-database code apps took from a git pin of the database package, now typed and released here. `connect`, `session`, `make_base` (the same naming convention, so existing revisions do not drift), `Project` from `[tool.strata-db]`, `upgrade`, `downgrade`, `drift`, `check_migrations`, `lint_revisions`, `stairway`, the live-database guard (`LiveDatabaseRefused`), scratch databases, a private throwaway Postgres for tests (now on Windows too), the `strata-db` command (`init`, `new-app`, `revision`, `migrate`, `check`, `current`; also `python -m strata_python.db`), the fixtures `db_engine`, `db_session`, `db_url`, `db_env`, `db_backend`, `db_project` with `--pg`, and the standard tests in `strata_python.db.testing`. The names are `STRATA_DB_*` (`URL`, `DATABASE`, `LIVE`, `TESTING`, `TEST`, `TEST_ADMIN_URL`, `ADMIN_URL`); throwaway databases are `strata_db_*`. To move: rename the app's table to `[tool.strata-db]`, import from `strata_python.db`, set `STRATA_DB_LIVE=1` and `STRATA_DB_DATABASE` in its service environment, and drop the git dependency (README, step 8).
16
+ - Tests under `tests/integration` get the `integration` marker automatically, and the marker is registered; delete the app's `pytest_collection_modifyitems`. Set `strata_auto_integration = false` to opt out.
17
+
18
+ ### Changed
19
+
20
+ - The shared dependencies are capped below their next release that may break (`fastapi<1`, `uvicorn<1`, `pydantic<3`, `pytest<10`), so a breaking upstream release reaches the apps through a strata-python release, not on its own.
21
+ - `FakeRun.check_output` raises `CalledProcessError` when `.code` is set, as the real `check_output` does; the apps' copies returned the output.
22
+
23
+ ## 0.2.0 (2026-11-14)
24
+
25
+ The first release on PyPI. Apps tracked a git commit before this.
26
+
27
+ ### Changed
28
+
29
+ - **Install from PyPI.** Replace the `[tool.uv.sources] strata-python = { git = ... }` entry with the dependency `strata-python>=0.2,<0.3`, then run `uv lock`.
30
+
31
+ ### Added
32
+
33
+ - `strata-public-check`: fails on email addresses, private IPv4 addresses, home-folder paths and the regexes in `STRATA_PUBLIC_DENY`, in a folder, an sdist or a wheel. Run it in a public app's CI.
34
+ - `Settings(..., prefix="MA")` names the environment variables an app already uses (from the pre-PyPI commits; listed here because no earlier release exists).
35
+ - The MIT licence.
36
+
37
+ ## Before 0.2.0 (git commits only)
38
+
39
+ `oslib`, `settings`, `web`, `cli`, `http_server`, `live`, the pytest plugin (`isolated_env`, `no_network`, `http_server`, `live_app`) and `strata-check`, taken from python-app-template.
@@ -0,0 +1,274 @@
1
+ Metadata-Version: 2.5
2
+ Name: strata-python
3
+ Version: 0.2.1
4
+ Summary: Common code for Python web server apps: OS helpers, settings, FastAPI serving, CLI commands, test fixtures and the strata-check gate
5
+ Project-URL: Homepage, https://github.com/jburnhams/strata-python
6
+ Project-URL: Source, https://github.com/jburnhams/strata-python
7
+ Project-URL: Changelog, https://github.com/jburnhams/strata-python/blob/main/CHANGELOG.md
8
+ Author: jburnhams
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: cli,fastapi,pytest,settings
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Framework :: FastAPI
14
+ Classifier: Framework :: Pytest
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.11
22
+ Requires-Dist: fastapi<1,>=0.115
23
+ Requires-Dist: pydantic<3,>=2.9
24
+ Requires-Dist: pytest<10,>=8
25
+ Requires-Dist: tzdata; sys_platform == 'win32'
26
+ Requires-Dist: uvicorn<1,>=0.32
27
+ Provides-Extra: db
28
+ Requires-Dist: alembic<2,>=1.13; extra == 'db'
29
+ Requires-Dist: psycopg[binary]<4,>=3.2; extra == 'db'
30
+ Requires-Dist: sqlalchemy<3,>=2.0; extra == 'db'
31
+ Provides-Extra: dev
32
+ Requires-Dist: httpx<1,>=0.27; extra == 'dev'
33
+ Requires-Dist: pyright<2,>=1.1.400; extra == 'dev'
34
+ Requires-Dist: pytest-cov<8,>=5; extra == 'dev'
35
+ Requires-Dist: pytest-randomly<6,>=3; extra == 'dev'
36
+ Requires-Dist: pytest-timeout<3,>=2; extra == 'dev'
37
+ Requires-Dist: pytest-xdist<4,>=3; extra == 'dev'
38
+ Requires-Dist: ruff<0.18,>=0.17; extra == 'dev'
39
+ Requires-Dist: ty<0.1,>=0.0.99; extra == 'dev'
40
+ Description-Content-Type: text/markdown
41
+
42
+ # strata-python
43
+
44
+ Common code for the strata Python web server apps (FastAPI + CLI), the Python counterpart of [strata-react](https://github.com/jburnhams/strata-react). Every app made from [python-app-template](https://github.com/jburnhams/python-app-template) used to carry its own drifting copy of these modules; they live here once. It is opinionated and built for those apps rather than as a general-purpose library, but it is public, MIT-licensed and on PyPI.
45
+
46
+ | Module | What it gives an app |
47
+ |---|---|
48
+ | `strata_python.oslib` | Cross-platform file locks, process liveness (`pid_alive`), `kill_tree`, `lower_priority`, `venv_python`, `cli_command(module)` |
49
+ | `strata_python.settings` | `Settings` / `Setting`: one JSON file in `~/.<app>` with `<APP>_*` environment overrides, validation (`absolute_path`, `non_empty`), atomic saves |
50
+ | `strata_python.web` | `base_app` (health + settings routes), `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` |
51
+ | `strata_python.cli` | `add_doctor`, `add_set`, `add_serve` for the app's argparse subcommands |
52
+ | `strata_python.http_server` / `live` | A real scripted HTTP server and a real uvicorn server on loopback, for tests that make actual requests |
53
+ | 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, and the `integration` marker on everything under `tests/integration` |
54
+ | `strata_python.testing` | The fakes behind those fixtures (`FakeResponse`, `http_error`, `FakeUrlopen`, `FakePopen`, `FakeRun`, `Sleeper`) and the CLI runners `run_cli(main, *args)` and `run_module("myapp", *args, src=...)` |
55
+ | `strata_python.db` (extra `[db]`) | The shared database: `connect("myapp")` (the app's schema of one shared Postgres, or a SQLite path), `make_base()` 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`) |
56
+ | `strata-check` | The one gate: lockfile, ruff, `ruff format`, pyright strict, ty, unit tests with coverage |
57
+ | `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 |
58
+
59
+ ## Move an app onto it
60
+
61
+ The goal: an app keeps only its plumbing and business logic, and everything else comes from here. Work through the steps in order, one commit each, running `scripts/check` after every step. Each step says what to delete, so the app gets smaller as it goes. What changed in each release, and how to upgrade, is in [CHANGELOG.md](CHANGELOG.md).
62
+
63
+ ### 1. Depend on the release
64
+
65
+ ```toml
66
+ # pyproject.toml
67
+ [project]
68
+ dependencies = [
69
+ "strata-python>=0.2,<0.3", # brings FastAPI, uvicorn, pydantic and pytest; while 0.x, cap below the next minor
70
+ # ... only what is the app's own: torch, opencv, yt-dlp ...
71
+ ]
72
+
73
+ [dependency-groups]
74
+ dev = ["strata-python[dev]"] # ruff, pyright, ty, httpx and the pytest plugins, at the versions strata-check expects
75
+ ```
76
+
77
+ Delete from the app's own lists everything strata-python already brings (fastapi, uvicorn, pydantic, pytest, ruff, pyright, ty, pytest-cov, pytest-xdist, pytest-randomly, pytest-timeout, httpx) and any `[tool.uv.sources] strata-python = { git = ... }` entry, then run `uv lock`. To try an unreleased commit, put a `git` source with `rev = "<sha>"` back for the moment.
78
+
79
+ The shared versions are decided here: strata-python sets a minimum (what its CI tested) and a cap (the next release that may break) for each, and its own dependabot keeps them current. Each app still has its own `uv.lock`, so one dependabot PR a week per app is the floor; make it one, not one per package:
80
+
81
+ ```yaml
82
+ # .github/dependabot.yml in the app
83
+ version: 2
84
+ updates:
85
+ - package-ecosystem: uv
86
+ directory: /
87
+ schedule: { interval: weekly }
88
+ groups: { python: { patterns: ["*"] } } # strata-python and everything else in one PR
89
+ - package-ecosystem: github-actions
90
+ directory: /
91
+ schedule: { interval: monthly }
92
+ groups: { actions: { patterns: ["*"] } }
93
+ ```
94
+
95
+ Security updates still arrive on their own as soon as they are published; keep them on.
96
+
97
+ ### 2. The gate
98
+
99
+ `scripts/check` becomes one line, and the app's own `scripts/check.py` goes:
100
+
101
+ ```bash
102
+ #!/bin/bash
103
+ DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
104
+ cd "$DIR/.." && exec uv run --locked strata-check "$@"
105
+ ```
106
+
107
+ It runs the lockfile check, ruff, `ruff format`, pyright strict, ty and the unit tests with coverage. `--fast` skips the tests and `--fix` applies safe ruff fixes. An optional `[tool.strata-check]` sets `paths` (default `src`, `tests`, `scripts`) and `tests` (default `tests/unit`). CI calls the same script. A public app also runs `uv run strata-public-check . dist/*` in CI, with `STRATA_PUBLIC_DENY` as a repository secret.
108
+
109
+ ### 3. Settings
110
+
111
+ Replace the app's `settings.py` (its key list, getters, file handling and environment lookups) with a declaration:
112
+
113
+ ```python
114
+ from strata_python.settings import Setting, Settings, absolute_path, non_empty
115
+
116
+ SETTINGS = Settings(
117
+ "myapp", # ~/.myapp/settings.json, moved with MYAPP_HOME
118
+ [
119
+ Setting("data_dir", default=lambda: "/srv/myapp", normalise=absolute_path),
120
+ Setting("greeting", default="Hello", normalise=non_empty),
121
+ ],
122
+ prefix="MYAPP", # only if the app already runs with other variable names
123
+ )
124
+
125
+ SETTINGS.get("greeting") # MYAPP_GREETING, else the file, else the default
126
+ SETTINGS.save({"greeting": "Hi"}) # validated and written atomically; None resets to the default
127
+ SETTINGS.folder("data_dir") # the value as a folder, created if missing
128
+ ```
129
+
130
+ Values are strings today. An app with int, float or list settings converts at the point of use (`int(SETTINGS.get("workers"))`, `SETTINGS.get("roots").split(os.pathsep)`) until typed settings land here.
131
+
132
+ ### 4. The server
133
+
134
+ ```python
135
+ from strata_python import web
136
+
137
+
138
+ def create_app():
139
+ app = web.base_app("myapp", __version__, SETTINGS) # GET /api/health, GET and PUT /api/settings, /api/docs
140
+ # ... the app's own /api routes ...
141
+ web.add_web(app, STATIC_DIR, LANDING_HTML) # last: /assets, top-level files, and index.html at every other path
142
+ return app
143
+ ```
144
+
145
+ Delete the app's own `/api/health` and `/api/settings` routes, its `/assets` mount, SPA fallback, `with_base` and `static_file` copies and its `uvicorn.run` wrapper. `web.serve(app, argv, default_port=...)` replaces the last of these. A route whose reply needs more than `{ok, version}` adds its own route beside them.
146
+
147
+ ### 5. The CLI
148
+
149
+ ```python
150
+ import argparse
151
+
152
+ from strata_python import cli, web
153
+
154
+
155
+ def main(argv=None):
156
+ parser = argparse.ArgumentParser(prog="myapp")
157
+ sub = parser.add_subparsers(dest="cmd", required=True)
158
+ cli.add_doctor(sub, "myapp", __version__, ("fastapi", "uvicorn")) # versions, and whether each import works
159
+ cli.add_set(sub, SETTINGS) # myapp set KEY [VALUE|default]
160
+ cli.add_serve(sub, lambda host, port: web.serve(create_app(), ["--host", host, "--port", str(port)]), default_port=8000)
161
+ # ... the app's own subcommands, each with set_defaults(fn=...) ...
162
+ args = parser.parse_args(argv)
163
+ return args.fn(args)
164
+ ```
165
+
166
+ Delete the hand-written `doctor`, `set` and `serve` subparsers. Each app's port belongs in its deploy units, not in this library.
167
+
168
+ ### 6. OS helpers
169
+
170
+ Delete the app's `oslib.py` and import from `strata_python.oslib`: `file_lock(f)`, `pid_alive(pid)`, `kill_tree(pid, sig)`, `lower_priority(nice)`, `venv_python(venv)` and `cli_command(module)`. `cli_command` now takes the module name (`cli_command("myapp")`). Local `alive(pid)`, `_alive` and `lower_priority()` copies go too. Helpers this library does not have yet (process-group supervision, load average) stay in the app until they move here, and the app's file says so.
171
+
172
+ ### 7. Tests
173
+
174
+ The pytest plugin loads itself once strata-python is installed. Configure it in `pyproject.toml`:
175
+
176
+ ```toml
177
+ [tool.pytest.ini_options]
178
+ strata_env_prefix = "MYAPP" # MYAPP_HOME and MYAPP_DATA point into a fresh folder for every test
179
+ strata_tuning_vars = ["MYAPP_WORKERS"] # removed for every test: what a developer sets to try things
180
+ strata_env = [ # set for every test; {env} is that folder
181
+ "MYAPP_SWEEP_SECONDS=0",
182
+ "MYAPP_PROJECTS={env}/projects",
183
+ ]
184
+ ```
185
+
186
+ Then delete these from the app:
187
+
188
+ - `tests/utils/fakes.py`, or keep only the doubles that are the app's own (a fake model, a fake yt-dlp).
189
+ - The `fake_urlopen`, `fake_popen` and `fake_run` fixtures, and any `no_sleep`.
190
+ - `pytest_collection_modifyitems`, which added the `integration` marker. The plugin registers the marker and adds it under `tests/integration`.
191
+ - The `isolated_env` (or `isolated_home`) and `no_network` fixtures. The app's extra variables move to `strata_env`. Keep a small autouse fixture only for what is not a variable, such as patching a module default.
192
+ - The integration `cli` and `cli_subprocess` fixtures. They become short fixtures in `tests/integration/conftest.py`:
193
+
194
+ ```python
195
+ from pathlib import Path
196
+
197
+ import pytest
198
+
199
+ from strata_python.testing import run_cli, run_module
200
+
201
+ SRC = str(Path(__file__).parents[2] / "src")
202
+
203
+
204
+ @pytest.fixture
205
+ def cli():
206
+ from myapp import cli as app_cli
207
+
208
+ return lambda *args, check=True: run_cli(app_cli.main, *args, check=check)
209
+
210
+
211
+ @pytest.fixture
212
+ def cli_subprocess(isolated_env):
213
+ return lambda *args, check=True: run_module("myapp", *args, src=SRC, check=check)
214
+ ```
215
+
216
+ What every test gets:
217
+
218
+ | Fixture | Use it for |
219
+ |---|---|
220
+ | `isolated_env` (autouse) | Home, app home and data in a fresh folder, tuning variables removed, `strata_env` set. Returns the folder |
221
+ | `no_network` (autouse) | An outbound connection fails the test; loopback is fine |
222
+ | `http_server` | **First choice for HTTP**: a real server on loopback. `http_server.route("GET", "/items/1", {"id": 1})`, `once=True` for a sequence, then `http_server.requests`. A request no route answered fails the test |
223
+ | `live_app` | `with live_app(create_app()) as base:` runs the app on a real port for a client under test |
224
+ | `fake_urlopen` | Many quick cases at a web API's edge: `fake_urlopen.reply(http_error(429), {"ok": 1})`, then `fake_urlopen.calls[0].url`, `.method`, `.headers["user-agent"]`, `.body` (parsed JSON) |
225
+ | `fake_popen` | Code that starts a long-running process: nothing starts; `fake_popen.instances[-1].cmd` and `.kw`; set `.returncode = 0` to finish it |
226
+ | `fake_run` | Code that runs a program: `fake_run.returns["ffprobe"] = b"..."`, `fake_run.code = 1`, then `fake_run.calls` |
227
+ | `no_sleep` | Retries and backoff without waiting: `no_sleep.delays` |
228
+
229
+ `strata_python.testing` holds the classes behind them (`FakeResponse`, `http_error`, `FakeUrlopen`, `FakePopen`, `FakeRun`, `Sleeper`) for a test that needs one directly. Prefer the real thing: `http_server` over `fake_urlopen`, the actual program over `fake_run`. A fake is for a true external edge where speed matters.
230
+
231
+ ### 8. Database (apps with one)
232
+
233
+ Replaces the git-pinned database package, with the same behaviour under new names.
234
+
235
+ ```toml
236
+ # pyproject.toml
237
+ dependencies = ["strata-python[db]>=0.2,<0.3"] # SQLAlchemy 2, Alembic, psycopg 3
238
+
239
+ [tool.strata-db] # was the old package's own table: rename it, the keys are the same
240
+ app = "myapp" # owner role and schema (lower case, digits, _)
241
+ models = "myapp.models:Base"
242
+ migrations = "migrations" # the app's Alembic revisions, unchanged
243
+ # engine = "postgres" # only for an app that uses Postgres-only features
244
+ ```
245
+
246
+ - Imports: the old package's names come from `strata_python.db` (`connect`, `session`, `make_base`, `Project`, `upgrade`, `drift`, `check_migrations`, `LiveDatabaseRefused`); the standard tests from `strata_python.db.testing`. The naming convention is byte-identical, so existing revisions and databases do not drift.
247
+ - 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`.
248
+ - 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`).
249
+ - At service start (only there): `Project.load(__file__).upgrade(connect("myapp"))`.
250
+ - Tests: the plugin is registered with every install and does nothing until the extra is there. 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` 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:
251
+
252
+ ```python
253
+ # tests/unit/test_database.py
254
+ from strata_python.db.testing import test_migrations, test_schema_matches_models # noqa: F401
255
+ ```
256
+
257
+ Never build a test schema with `Base.metadata.create_all()`: the tests would pass with broken migrations. And never write a guard of your own: under pytest every psycopg connection to a database that is not a throwaway `strata_db_*` one fails with `LiveDatabaseRefused`, in the test process and its subprocesses.
258
+ - CI: run the tests with `--pg` as well for an app that deploys on Postgres, since SQLite hides Postgres-only behaviour (types, defaults, locking). The fixtures need the PostgreSQL server binaries on the runner (`sudo apt-get install -y postgresql` if they are missing; this repo's `ci.yml` shows the step), or `STRATA_DB_TEST_ADMIN_URL` pointing at a service container.
259
+
260
+ Delete: the git source for the old package, its `[tool.*]` table, any home-made "unset the URL" or "block the database" fixture, and any `create_all()` in tests.
261
+
262
+ ### Done when
263
+
264
+ - `grep -rn "def fake_urlopen\|def no_network\|def isolated_env\|pytest_collection_modifyitems\|class FakeRun\|uvicorn.run\|/api/health" src tests` finds nothing the app still needs.
265
+ - The app has no `oslib.py`, `settings.py` with file handling, `fakes.py` copy or `scripts/check.py`.
266
+ - `scripts/check` and the integration tests pass, and the app's changelog names the strata-python version it moved to.
267
+
268
+ ### Keep it current
269
+
270
+ Read the `Unreleased` section and each new version in [CHANGELOG.md](CHANGELOG.md) when dependabot raises a bump. A `### Breaking` line ends with what to change. When the app finds code it shares with another app, it belongs here: open a PR on this repo instead of copying it.
271
+
272
+ ## Develop
273
+
274
+ `uv sync`, then `scripts/check` (add `--fast` to skip the tests, `--fix` for safe ruff fixes). Integration tests (`uv run pytest tests/integration`) run the gate on a tiny project, `serve` in a separate process and `strata-db` as a command. The database tests use a throwaway Postgres: the private server needs the PostgreSQL server binaries on the machine (initdb refuses to run as root), or point `STRATA_DB_TEST_ADMIN_URL` at a throwaway server. Read [AGENTS.md](AGENTS.md) before changing anything; every change gets a [CHANGELOG.md](CHANGELOG.md) line for the apps and a [DEVLOG.md](DEVLOG.md) entry for us. Merging to main releases: `release.yml` bumps the version through its own PR, tags it and creates the GitHub release, and `pypi-publish.yml` uploads it to PyPI.
@@ -0,0 +1,233 @@
1
+ # strata-python
2
+
3
+ Common code for the strata Python web server apps (FastAPI + CLI), the Python counterpart of [strata-react](https://github.com/jburnhams/strata-react). Every app made from [python-app-template](https://github.com/jburnhams/python-app-template) used to carry its own drifting copy of these modules; they live here once. It is opinionated and built for those apps rather than as a general-purpose library, but it is public, MIT-licensed and on PyPI.
4
+
5
+ | Module | What it gives an app |
6
+ |---|---|
7
+ | `strata_python.oslib` | Cross-platform file locks, process liveness (`pid_alive`), `kill_tree`, `lower_priority`, `venv_python`, `cli_command(module)` |
8
+ | `strata_python.settings` | `Settings` / `Setting`: one JSON file in `~/.<app>` with `<APP>_*` environment overrides, validation (`absolute_path`, `non_empty`), atomic saves |
9
+ | `strata_python.web` | `base_app` (health + settings routes), `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`, `add_set`, `add_serve` for the app's argparse subcommands |
11
+ | `strata_python.http_server` / `live` | A real scripted HTTP server and a real uvicorn server on loopback, for tests that make actual requests |
12
+ | 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, and the `integration` marker on everything under `tests/integration` |
13
+ | `strata_python.testing` | The fakes behind those fixtures (`FakeResponse`, `http_error`, `FakeUrlopen`, `FakePopen`, `FakeRun`, `Sleeper`) and the CLI runners `run_cli(main, *args)` and `run_module("myapp", *args, src=...)` |
14
+ | `strata_python.db` (extra `[db]`) | The shared database: `connect("myapp")` (the app's schema of one shared Postgres, or a SQLite path), `make_base()` 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`) |
15
+ | `strata-check` | The one gate: lockfile, ruff, `ruff format`, pyright strict, ty, unit tests with coverage |
16
+ | `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 |
17
+
18
+ ## Move an app onto it
19
+
20
+ The goal: an app keeps only its plumbing and business logic, and everything else comes from here. Work through the steps in order, one commit each, running `scripts/check` after every step. Each step says what to delete, so the app gets smaller as it goes. What changed in each release, and how to upgrade, is in [CHANGELOG.md](CHANGELOG.md).
21
+
22
+ ### 1. Depend on the release
23
+
24
+ ```toml
25
+ # pyproject.toml
26
+ [project]
27
+ dependencies = [
28
+ "strata-python>=0.2,<0.3", # brings FastAPI, uvicorn, pydantic and pytest; while 0.x, cap below the next minor
29
+ # ... only what is the app's own: torch, opencv, yt-dlp ...
30
+ ]
31
+
32
+ [dependency-groups]
33
+ dev = ["strata-python[dev]"] # ruff, pyright, ty, httpx and the pytest plugins, at the versions strata-check expects
34
+ ```
35
+
36
+ Delete from the app's own lists everything strata-python already brings (fastapi, uvicorn, pydantic, pytest, ruff, pyright, ty, pytest-cov, pytest-xdist, pytest-randomly, pytest-timeout, httpx) and any `[tool.uv.sources] strata-python = { git = ... }` entry, then run `uv lock`. To try an unreleased commit, put a `git` source with `rev = "<sha>"` back for the moment.
37
+
38
+ The shared versions are decided here: strata-python sets a minimum (what its CI tested) and a cap (the next release that may break) for each, and its own dependabot keeps them current. Each app still has its own `uv.lock`, so one dependabot PR a week per app is the floor; make it one, not one per package:
39
+
40
+ ```yaml
41
+ # .github/dependabot.yml in the app
42
+ version: 2
43
+ updates:
44
+ - package-ecosystem: uv
45
+ directory: /
46
+ schedule: { interval: weekly }
47
+ groups: { python: { patterns: ["*"] } } # strata-python and everything else in one PR
48
+ - package-ecosystem: github-actions
49
+ directory: /
50
+ schedule: { interval: monthly }
51
+ groups: { actions: { patterns: ["*"] } }
52
+ ```
53
+
54
+ Security updates still arrive on their own as soon as they are published; keep them on.
55
+
56
+ ### 2. The gate
57
+
58
+ `scripts/check` becomes one line, and the app's own `scripts/check.py` goes:
59
+
60
+ ```bash
61
+ #!/bin/bash
62
+ DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
63
+ cd "$DIR/.." && exec uv run --locked strata-check "$@"
64
+ ```
65
+
66
+ It runs the lockfile check, ruff, `ruff format`, pyright strict, ty and the unit tests with coverage. `--fast` skips the tests and `--fix` applies safe ruff fixes. An optional `[tool.strata-check]` sets `paths` (default `src`, `tests`, `scripts`) and `tests` (default `tests/unit`). CI calls the same script. A public app also runs `uv run strata-public-check . dist/*` in CI, with `STRATA_PUBLIC_DENY` as a repository secret.
67
+
68
+ ### 3. Settings
69
+
70
+ Replace the app's `settings.py` (its key list, getters, file handling and environment lookups) with a declaration:
71
+
72
+ ```python
73
+ from strata_python.settings import Setting, Settings, absolute_path, non_empty
74
+
75
+ SETTINGS = Settings(
76
+ "myapp", # ~/.myapp/settings.json, moved with MYAPP_HOME
77
+ [
78
+ Setting("data_dir", default=lambda: "/srv/myapp", normalise=absolute_path),
79
+ Setting("greeting", default="Hello", normalise=non_empty),
80
+ ],
81
+ prefix="MYAPP", # only if the app already runs with other variable names
82
+ )
83
+
84
+ SETTINGS.get("greeting") # MYAPP_GREETING, else the file, else the default
85
+ SETTINGS.save({"greeting": "Hi"}) # validated and written atomically; None resets to the default
86
+ SETTINGS.folder("data_dir") # the value as a folder, created if missing
87
+ ```
88
+
89
+ Values are strings today. An app with int, float or list settings converts at the point of use (`int(SETTINGS.get("workers"))`, `SETTINGS.get("roots").split(os.pathsep)`) until typed settings land here.
90
+
91
+ ### 4. The server
92
+
93
+ ```python
94
+ from strata_python import web
95
+
96
+
97
+ def create_app():
98
+ app = web.base_app("myapp", __version__, SETTINGS) # GET /api/health, GET and PUT /api/settings, /api/docs
99
+ # ... the app's own /api routes ...
100
+ web.add_web(app, STATIC_DIR, LANDING_HTML) # last: /assets, top-level files, and index.html at every other path
101
+ return app
102
+ ```
103
+
104
+ Delete the app's own `/api/health` and `/api/settings` routes, its `/assets` mount, SPA fallback, `with_base` and `static_file` copies and its `uvicorn.run` wrapper. `web.serve(app, argv, default_port=...)` replaces the last of these. A route whose reply needs more than `{ok, version}` adds its own route beside them.
105
+
106
+ ### 5. The CLI
107
+
108
+ ```python
109
+ import argparse
110
+
111
+ from strata_python import cli, web
112
+
113
+
114
+ def main(argv=None):
115
+ parser = argparse.ArgumentParser(prog="myapp")
116
+ sub = parser.add_subparsers(dest="cmd", required=True)
117
+ cli.add_doctor(sub, "myapp", __version__, ("fastapi", "uvicorn")) # versions, and whether each import works
118
+ cli.add_set(sub, SETTINGS) # myapp set KEY [VALUE|default]
119
+ cli.add_serve(sub, lambda host, port: web.serve(create_app(), ["--host", host, "--port", str(port)]), default_port=8000)
120
+ # ... the app's own subcommands, each with set_defaults(fn=...) ...
121
+ args = parser.parse_args(argv)
122
+ return args.fn(args)
123
+ ```
124
+
125
+ Delete the hand-written `doctor`, `set` and `serve` subparsers. Each app's port belongs in its deploy units, not in this library.
126
+
127
+ ### 6. OS helpers
128
+
129
+ Delete the app's `oslib.py` and import from `strata_python.oslib`: `file_lock(f)`, `pid_alive(pid)`, `kill_tree(pid, sig)`, `lower_priority(nice)`, `venv_python(venv)` and `cli_command(module)`. `cli_command` now takes the module name (`cli_command("myapp")`). Local `alive(pid)`, `_alive` and `lower_priority()` copies go too. Helpers this library does not have yet (process-group supervision, load average) stay in the app until they move here, and the app's file says so.
130
+
131
+ ### 7. Tests
132
+
133
+ The pytest plugin loads itself once strata-python is installed. Configure it in `pyproject.toml`:
134
+
135
+ ```toml
136
+ [tool.pytest.ini_options]
137
+ strata_env_prefix = "MYAPP" # MYAPP_HOME and MYAPP_DATA point into a fresh folder for every test
138
+ strata_tuning_vars = ["MYAPP_WORKERS"] # removed for every test: what a developer sets to try things
139
+ strata_env = [ # set for every test; {env} is that folder
140
+ "MYAPP_SWEEP_SECONDS=0",
141
+ "MYAPP_PROJECTS={env}/projects",
142
+ ]
143
+ ```
144
+
145
+ Then delete these from the app:
146
+
147
+ - `tests/utils/fakes.py`, or keep only the doubles that are the app's own (a fake model, a fake yt-dlp).
148
+ - The `fake_urlopen`, `fake_popen` and `fake_run` fixtures, and any `no_sleep`.
149
+ - `pytest_collection_modifyitems`, which added the `integration` marker. The plugin registers the marker and adds it under `tests/integration`.
150
+ - The `isolated_env` (or `isolated_home`) and `no_network` fixtures. The app's extra variables move to `strata_env`. Keep a small autouse fixture only for what is not a variable, such as patching a module default.
151
+ - The integration `cli` and `cli_subprocess` fixtures. They become short fixtures in `tests/integration/conftest.py`:
152
+
153
+ ```python
154
+ from pathlib import Path
155
+
156
+ import pytest
157
+
158
+ from strata_python.testing import run_cli, run_module
159
+
160
+ SRC = str(Path(__file__).parents[2] / "src")
161
+
162
+
163
+ @pytest.fixture
164
+ def cli():
165
+ from myapp import cli as app_cli
166
+
167
+ return lambda *args, check=True: run_cli(app_cli.main, *args, check=check)
168
+
169
+
170
+ @pytest.fixture
171
+ def cli_subprocess(isolated_env):
172
+ return lambda *args, check=True: run_module("myapp", *args, src=SRC, check=check)
173
+ ```
174
+
175
+ What every test gets:
176
+
177
+ | Fixture | Use it for |
178
+ |---|---|
179
+ | `isolated_env` (autouse) | Home, app home and data in a fresh folder, tuning variables removed, `strata_env` set. Returns the folder |
180
+ | `no_network` (autouse) | An outbound connection fails the test; loopback is fine |
181
+ | `http_server` | **First choice for HTTP**: a real server on loopback. `http_server.route("GET", "/items/1", {"id": 1})`, `once=True` for a sequence, then `http_server.requests`. A request no route answered fails the test |
182
+ | `live_app` | `with live_app(create_app()) as base:` runs the app on a real port for a client under test |
183
+ | `fake_urlopen` | Many quick cases at a web API's edge: `fake_urlopen.reply(http_error(429), {"ok": 1})`, then `fake_urlopen.calls[0].url`, `.method`, `.headers["user-agent"]`, `.body` (parsed JSON) |
184
+ | `fake_popen` | Code that starts a long-running process: nothing starts; `fake_popen.instances[-1].cmd` and `.kw`; set `.returncode = 0` to finish it |
185
+ | `fake_run` | Code that runs a program: `fake_run.returns["ffprobe"] = b"..."`, `fake_run.code = 1`, then `fake_run.calls` |
186
+ | `no_sleep` | Retries and backoff without waiting: `no_sleep.delays` |
187
+
188
+ `strata_python.testing` holds the classes behind them (`FakeResponse`, `http_error`, `FakeUrlopen`, `FakePopen`, `FakeRun`, `Sleeper`) for a test that needs one directly. Prefer the real thing: `http_server` over `fake_urlopen`, the actual program over `fake_run`. A fake is for a true external edge where speed matters.
189
+
190
+ ### 8. Database (apps with one)
191
+
192
+ Replaces the git-pinned database package, with the same behaviour under new names.
193
+
194
+ ```toml
195
+ # pyproject.toml
196
+ dependencies = ["strata-python[db]>=0.2,<0.3"] # SQLAlchemy 2, Alembic, psycopg 3
197
+
198
+ [tool.strata-db] # was the old package's own table: rename it, the keys are the same
199
+ app = "myapp" # owner role and schema (lower case, digits, _)
200
+ models = "myapp.models:Base"
201
+ migrations = "migrations" # the app's Alembic revisions, unchanged
202
+ # engine = "postgres" # only for an app that uses Postgres-only features
203
+ ```
204
+
205
+ - Imports: the old package's names come from `strata_python.db` (`connect`, `session`, `make_base`, `Project`, `upgrade`, `drift`, `check_migrations`, `LiveDatabaseRefused`); the standard tests from `strata_python.db.testing`. The naming convention is byte-identical, so existing revisions and databases do not drift.
206
+ - 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`.
207
+ - 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`).
208
+ - At service start (only there): `Project.load(__file__).upgrade(connect("myapp"))`.
209
+ - Tests: the plugin is registered with every install and does nothing until the extra is there. 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` 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:
210
+
211
+ ```python
212
+ # tests/unit/test_database.py
213
+ from strata_python.db.testing import test_migrations, test_schema_matches_models # noqa: F401
214
+ ```
215
+
216
+ Never build a test schema with `Base.metadata.create_all()`: the tests would pass with broken migrations. And never write a guard of your own: under pytest every psycopg connection to a database that is not a throwaway `strata_db_*` one fails with `LiveDatabaseRefused`, in the test process and its subprocesses.
217
+ - CI: run the tests with `--pg` as well for an app that deploys on Postgres, since SQLite hides Postgres-only behaviour (types, defaults, locking). The fixtures need the PostgreSQL server binaries on the runner (`sudo apt-get install -y postgresql` if they are missing; this repo's `ci.yml` shows the step), or `STRATA_DB_TEST_ADMIN_URL` pointing at a service container.
218
+
219
+ Delete: the git source for the old package, its `[tool.*]` table, any home-made "unset the URL" or "block the database" fixture, and any `create_all()` in tests.
220
+
221
+ ### Done when
222
+
223
+ - `grep -rn "def fake_urlopen\|def no_network\|def isolated_env\|pytest_collection_modifyitems\|class FakeRun\|uvicorn.run\|/api/health" src tests` finds nothing the app still needs.
224
+ - The app has no `oslib.py`, `settings.py` with file handling, `fakes.py` copy or `scripts/check.py`.
225
+ - `scripts/check` and the integration tests pass, and the app's changelog names the strata-python version it moved to.
226
+
227
+ ### Keep it current
228
+
229
+ Read the `Unreleased` section and each new version in [CHANGELOG.md](CHANGELOG.md) when dependabot raises a bump. A `### Breaking` line ends with what to change. When the app finds code it shares with another app, it belongs here: open a PR on this repo instead of copying it.
230
+
231
+ ## Develop
232
+
233
+ `uv sync`, then `scripts/check` (add `--fast` to skip the tests, `--fix` for safe ruff fixes). Integration tests (`uv run pytest tests/integration`) run the gate on a tiny project, `serve` in a separate process and `strata-db` as a command. The database tests use a throwaway Postgres: the private server needs the PostgreSQL server binaries on the machine (initdb refuses to run as root), or point `STRATA_DB_TEST_ADMIN_URL` at a throwaway server. Read [AGENTS.md](AGENTS.md) before changing anything; every change gets a [CHANGELOG.md](CHANGELOG.md) line for the apps and a [DEVLOG.md](DEVLOG.md) entry for us. Merging to main releases: `release.yml` bumps the version through its own PR, tags it and creates the GitHub release, and `pypi-publish.yml` uploads it to PyPI.