- All dependencies to current releases (97 known vulnerabilities -> 0), Python 3.14, uv pinned, requirements-test.txt, lxml/dateutil pinned - CSRF tokens on admin forms, logout and IndieAuth consent - IndieAuth client and crosspost link-card fetches via safe_get - FLASK_DEBUG/FLASK_ENV default off/production; image sets them - Foreign keys enforced on pooled connections; migration 018 removes orphans - Rate limits shared across processes (rate_limits, migration 019) - datetime.utcnow() and sqlite3 default adapters replaced - compose.yaml fixed; duplicate dev_auth.py and test.ini removed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
152 lines
6.4 KiB
Markdown
152 lines
6.4 KiB
Markdown
# Python Coding Standards
|
|
|
|
**Status**: Active
|
|
**Last Updated**: 2026-11-03 (v2.10.1)
|
|
|
|
How Python code in StarPunk is written. The project rule comes first:
|
|
"Every line of code must justify its existence. When in doubt, leave it
|
|
out." Patterns specific to small helper functions are in
|
|
[utility-function-patterns.md](utility-function-patterns.md).
|
|
|
|
## Base style
|
|
|
|
- [PEP 8](https://peps.python.org/pep-0008/) naming and layout, Python 3.14. Use `datetime.now(timezone.utc)`, not the deprecated `datetime.utcnow()`.
|
|
- **Match the file you are editing.** 4-space indents everywhere; quote
|
|
style varies between modules (newer code uses double quotes); keep lines
|
|
to roughly 100 characters.
|
|
- Keep diffs about the change. Don't reformat or re-order code you aren't
|
|
otherwise touching.
|
|
|
|
### Formatters and linters
|
|
|
|
`black`, `flake8` and `mypy` are in `requirements-dev.txt`, but they are
|
|
**not enforced**: there is no configuration file, no pre-commit hook, and CI
|
|
runs only pytest. The existing code is not Black-formatted (running
|
|
`black` over `starpunk/` would rewrite most files). So:
|
|
|
|
- Don't run `black` on whole files or directories.
|
|
- Use `uv run flake8 --select=F <file>` to catch unused imports, undefined
|
|
names and similar real errors in files you changed.
|
|
- Type hints are checked by review, not by mypy.
|
|
|
|
## Naming
|
|
|
|
| Kind | Style | Examples |
|
|
|---|---|---|
|
|
| Modules | `snake_case.py`, named for what they do | `webmention_ssrf.py`, `websub_worker.py` |
|
|
| Functions, variables | `snake_case`, verbs for functions | `create_note`, `validate_url_for_fetch` |
|
|
| Classes | `PascalCase` | `WebSubWorker`, `ConnectionPool` |
|
|
| Constants | `UPPER_SNAKE_CASE`, module level | `MAX_SLUG_LENGTH`, `RESERVED_SLUGS` |
|
|
| Private | leading underscore | `_consume_login_state`, `_Watchdog` |
|
|
| Exceptions | `...Error`, one base per module | `NoteError` → `NoteNotFoundError` |
|
|
|
|
## Type hints and docstrings
|
|
|
|
- New and changed public functions get type hints on parameters and return
|
|
values. Use built-in generics (`list[str]`, `dict[str, int]`) and
|
|
`X | None` in new code; `Optional[...]` is also present in older modules.
|
|
- Every module starts with a docstring saying what it is for. Mention the
|
|
ADR or spec it implements and, for later changes, the release
|
|
(`v2.10.1: every queue item is handled on its own, ...`).
|
|
- Public functions get a docstring: one summary line, then `Args:`,
|
|
`Returns:` and `Raises:` sections where they add information.
|
|
- Comments explain **why** (a spec requirement, an incident, a security
|
|
reason), not what the next line does.
|
|
|
|
## Project patterns
|
|
|
|
### Configuration
|
|
|
|
Read settings from `current_app.config` (or `app.config` during startup),
|
|
never `os.getenv` outside `starpunk/config.py`. A new setting is:
|
|
|
|
1. read in `load_config()` with its default and type conversion
|
|
(`int(...)`, `== "true"`);
|
|
2. validated in `validate_config()` if a wrong value would break startup;
|
|
3. documented in `.env.example` with its default.
|
|
|
|
### Database
|
|
|
|
- Get connections with `get_db()` from `starpunk.database` (connection
|
|
pool). Use parameterised queries (`?` placeholders) only, never string
|
|
formatting.
|
|
- Schema changes are new numbered files in `migrations/`; never edit an
|
|
applied migration. See
|
|
[git-branching-strategy.md](git-branching-strategy.md#migrations).
|
|
|
|
### Outbound HTTP
|
|
|
|
New code that requests a URL which came from outside (webmention sources
|
|
and targets, WebSub callbacks, Micropub photo URLs) uses
|
|
`starpunk/webmention_ssrf.py` (`safe_get`, `safe_post`): it refuses private
|
|
addresses, pins the resolved address, caps the response size and enforces a
|
|
hard deadline. Send its `user_agent()` string. Plain `httpx` is for fixed,
|
|
configured endpoints (OIDC provider, crossposting APIs, `ADMIN_ME`).
|
|
|
|
Older code has its own checks instead: IndieAuth client metadata
|
|
(`indieauth.py`, `validate_url_for_fetch` then `httpx.get`) and link-card
|
|
fetching for crossposts (`syndication._fetch_public`). Moving them onto
|
|
`safe_get` is welcome when touching that code.
|
|
|
|
### Errors
|
|
|
|
- Raise specific exceptions from the module's own hierarchy
|
|
(`MicropubValidationError`, `SyndicationError`, `MigrationError`).
|
|
- Catch the narrowest exception you can handle. Broad `except Exception`
|
|
belongs only at boundaries that must keep running (worker loops, one
|
|
queue item at a time) and must log the error.
|
|
- Protocol endpoints return the error format their spec requires (e.g.
|
|
Micropub `{"error": ..., "error_description": ...}` with the right status).
|
|
See [ADR-055](../decisions/ADR-055-error-handling-philosophy.md).
|
|
|
|
### Routes
|
|
|
|
- Routes live in blueprints in `starpunk/routes/`, one module per area
|
|
(`public`, `admin`, `auth`, `indieauth`, `micropub`, `webmention`,
|
|
`websub`, `search`, `dev_auth`).
|
|
- Prefer one view per HTTP method; a single view for `GET` and `POST` is
|
|
fine where a spec defines one endpoint for both (`/micropub`).
|
|
- Admin views use `@require_auth` from `starpunk.auth`. State-changing
|
|
admin actions are `POST` only.
|
|
- Keep views thin: parsing and response in the route, logic in a module
|
|
(`notes.py`, `micropub.py`, `websub.py`).
|
|
|
|
### Background work
|
|
|
|
Long-running work runs in worker threads started by `create_app()`
|
|
(webmention, WebSub, syndication). Workers:
|
|
|
|
- skip starting when `app.config["TESTING"]` is true;
|
|
- must cope with every gunicorn process running its own copy: claim work
|
|
in the database so an item is processed once;
|
|
- handle each queue item on its own, so one bad item can't stop the loop;
|
|
- run inside `app.app_context()`.
|
|
|
|
### Logging
|
|
|
|
Use `current_app.logger` (structured logging with request correlation IDs,
|
|
[ADR-054](../decisions/ADR-054-structured-logging-architecture.md)). Never
|
|
log secrets, tokens or full request bodies.
|
|
|
|
## Tests
|
|
|
|
See [testing-checklist.md](testing-checklist.md). In short: pytest
|
|
functions or `Test...` classes with descriptive names
|
|
(`test_unsubscribe_ignores_lease_seconds`), fixtures from
|
|
`tests/conftest.py`, no real network access.
|
|
|
|
## Anti-patterns
|
|
|
|
- Abstractions with one caller, configuration nobody sets, code for
|
|
features not yet planned
|
|
- Mutable default arguments
|
|
- Magic numbers: name them as module constants
|
|
- Silent failures: an error is raised, returned or logged, never swallowed
|
|
- Reformatting unrelated code in a feature change
|
|
|
|
## References
|
|
|
|
- [PEP 8](https://peps.python.org/pep-0008/), [PEP 257](https://peps.python.org/pep-0257/), [PEP 484](https://peps.python.org/pep-0484/)
|
|
- [utility-function-patterns.md](utility-function-patterns.md)
|
|
- [ADR-055: Error handling philosophy](../decisions/ADR-055-error-handling-philosophy.md)
|