diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml index aeda2628..eb6d5752 100644 --- a/.github/workflows/build-docs.yml +++ b/.github/workflows/build-docs.yml @@ -34,6 +34,30 @@ jobs: - name: Install docs dependencies run: | pip install -r requirements-docs.txt + # Web generator page: assets from this commit's wheel, checked against + # the CLI before anything is deployed. + - uses: actions/setup-node@v4 + with: + node-version: "22" + - uses: actions/cache@v4 + with: + path: .cache/web-generator + key: web-generator-${{ hashFiles('scripts/web_generator/pyodide.toml') }} + - name: Build and install the fastkit wheel + run: | + python -m pip wheel --no-deps -w dist . + python -m pip install dist/fastapi_fastkit-*.whl + - name: Build the web generator assets + run: >- + python scripts/web_generator/build_assets.py + --wheel dist/fastapi_fastkit-*.whl + --out docs/en/assets/fastkit-generator + --commit "$GITHUB_SHA" + - name: Compare web output with the CLI + run: >- + python scripts/web_generator/compare_with_cli.py + --assets docs/en/assets/fastkit-generator + --cases tests/fixtures/web_generator/cases.json - run: echo "cache_id=$(date --utc '+%V')" >> $GITHUB_ENV - uses: actions/cache@v4 with: @@ -41,4 +65,4 @@ jobs: path: .cache restore-keys: | mkdocs-material- - - run: mkdocs gh-deploy --force + - run: mkdocs gh-deploy --strict --force diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml index e57cd86e..333d5091 100644 --- a/.github/workflows/labeler.yml +++ b/.github/workflows/labeler.yml @@ -1,12 +1,19 @@ name: "Pull Request Labeler" on: -- pull_request_target + pull_request: + types: [opened, synchronize, reopened] + +permissions: {} jobs: labeler: + # pull_request_target is blocked on public repositories by GitHub's default + # policy; with pull_request a fork's token cannot write labels, so forks + # are skipped and labelled by hand. + if: github.event.pull_request.head.repo.full_name == github.repository permissions: contents: read pull-requests: write runs-on: ubuntu-latest steps: - - uses: actions/labeler@v5 + - uses: actions/labeler@v6 diff --git a/.github/workflows/template-security-scan.yml b/.github/workflows/template-security-scan.yml index faaf6c1d..0760c1f3 100644 --- a/.github/workflows/template-security-scan.yml +++ b/.github/workflows/template-security-scan.yml @@ -53,12 +53,20 @@ jobs: fi req_file="$template_dir/requirements.txt-tpl" + dev_req_file="$template_dir/requirements-dev.txt-tpl" if [ -f "$req_file" ]; then echo "🔍 Scanning $template_name..." - # Create temp requirements file + # One temp requirements file with the runtime pins and, when the + # template splits them out, the dev pins. The dev file's + # "-r requirements.txt" line is dropped: the runtime pins are + # already in the file and the include would not resolve here. temp_req=$(mktemp) cp "$req_file" "$temp_req" + if [ -f "$dev_req_file" ]; then + printf '\n' >> "$temp_req" + grep -v -E '^[[:space:]]*-r[[:space:]]' "$dev_req_file" >> "$temp_req" || true + fi audit_file="$TEMP_DIR/${template_name}.json" err_file="$TEMP_DIR/${template_name}.err" diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 32b243bd..2479e2c0 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -55,7 +55,9 @@ jobs: # PDM is already installed via setup-pdm action - name: Install dependencies - run: pdm install -G dev + # test-runtime: FastAPI and friends, so the tests that start generated + # applications run instead of skipping. + run: pdm install -G dev -G test-runtime - name: Run tests with coverage if: runner.os == 'Linux' @@ -102,7 +104,9 @@ jobs: pip install poetry - name: Install dependencies - run: pdm install -G dev + # test-runtime: FastAPI and friends, so the tests that start generated + # applications run instead of skipping. + run: pdm install -G dev -G test-runtime - name: Fail on implicit text encodings in fastapi_fastkit env: diff --git a/.github/workflows/translate-docs.yml b/.github/workflows/translate-docs.yml index 4ffadeef..70c32453 100644 --- a/.github/workflows/translate-docs.yml +++ b/.github/workflows/translate-docs.yml @@ -8,15 +8,14 @@ on: required: false type: string api_provider: - description: 'AI API provider for translation' + description: 'AI API provider for translation (OpenAI-compatible)' required: true type: choice options: - openai - - anthropic default: openai specific_files: - description: 'Specific files to translate (space-separated, relative to docs/en/). Example: index.md user-guide/installation.md' + description: 'Specific files to translate (space-separated, relative to docs/en/). Example: index.md start/installation.md' required: false type: string create_pr: @@ -51,35 +50,47 @@ jobs: with: python-version: '3.12' + # The package itself renders the generated blocks after translating. - name: Install dependencies run: | python -m pip install --upgrade pip - pip install openai anthropic + pip install . openai - name: Configure Git run: | git config --global user.name "github-actions[bot]" git config --global user.email "github-actions[bot]@users.noreply.github.com" + # The next step opens the pull request, so the script never does (--no-pr). - name: Run translation env: TRANSLATION_API_KEY: ${{ secrets.TRANSLATION_API_KEY }} + API_PROVIDER: ${{ inputs.api_provider }} + TARGET_LANGUAGE: ${{ inputs.target_language }} + SPECIFIC_FILES: ${{ inputs.specific_files }} run: | - ARGS="--api-provider ${{ inputs.api_provider }}" + ARGS=(--api-provider "$API_PROVIDER" --no-pr) - if [ -n "${{ inputs.target_language }}" ]; then - ARGS="$ARGS --target-lang ${{ inputs.target_language }}" + if [ -n "$TARGET_LANGUAGE" ]; then + ARGS+=(--target-lang "$TARGET_LANGUAGE") fi - if [ -n "${{ inputs.specific_files }}" ]; then - ARGS="$ARGS --files ${{ inputs.specific_files }}" + if [ -n "$SPECIFIC_FILES" ]; then + read -r -a FILES <<< "$SPECIFIC_FILES" + ARGS+=(--files "${FILES[@]}") fi - if [ "${{ inputs.create_pr }}" = "false" ]; then - ARGS="$ARGS --no-pr" - fi + python scripts/translate.py "${ARGS[@]}" - python scripts/translate.py $ARGS + - name: Render generated blocks + env: + TARGET_LANGUAGE: ${{ inputs.target_language }} + run: | + if [ -n "$TARGET_LANGUAGE" ]; then + python scripts/docs_blocks.py --lang "$TARGET_LANGUAGE" + else + python scripts/docs_blocks.py + fi - name: Create Pull Request if: inputs.create_pr == true diff --git a/.github/workflows/web-generator.yml b/.github/workflows/web-generator.yml new file mode 100644 index 00000000..34574816 --- /dev/null +++ b/.github/workflows/web-generator.yml @@ -0,0 +1,79 @@ +name: Web generator + +# The docs site's web generator runs fastkit in the browser with Pyodide. +# This job runs the page's generator core under Node with the same assets and +# compares every case with the `fastkit init` CLI from the same wheel, then +# builds the docs site and checks the page in every locale. + +on: + pull_request: + paths: + - "src/**" + - "docs/**" + - "README.md" + - "CHANGELOG.md" + - "scripts/mkdocs_hooks/**" + - "scripts/docs_blocks.py" + - "scripts/web_generator/**" + - "tests/fixtures/web_generator/**" + - "pyproject.toml" + - "mkdocs.yml" + - "requirements-docs.txt" + - ".github/workflows/web-generator.yml" + push: + branches: + - main + +permissions: + contents: read + +jobs: + web-vs-cli: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Set up Node + uses: actions/setup-node@v4 + with: + node-version: "22" + + - name: Cache Pyodide downloads + uses: actions/cache@v4 + with: + path: .cache/web-generator + key: web-generator-${{ hashFiles('scripts/web_generator/pyodide.toml') }} + + - name: Build and install the fastkit wheel + run: | + python -m pip install --upgrade pip + python -m pip wheel --no-deps -w dist . + python -m pip install dist/fastapi_fastkit-*.whl + + - name: Build the web generator assets + run: >- + python scripts/web_generator/build_assets.py + --wheel dist/fastapi_fastkit-*.whl + --out docs/en/assets/fastkit-generator + --commit "$GITHUB_SHA" + + - name: Compare web output with the CLI + run: >- + python scripts/web_generator/compare_with_cli.py + --assets docs/en/assets/fastkit-generator + --cases tests/fixtures/web_generator/cases.json + + - name: Build the docs site + run: | + python -m pip install -r requirements-docs.txt + mkdocs build --strict -d site + + - name: Check the web generator page + run: python scripts/web_generator/check_site.py site diff --git a/.gitignore b/.gitignore index f157d7e5..6708401a 100644 --- a/.gitignore +++ b/.gitignore @@ -22,6 +22,10 @@ temp/ *_api_key.txt translation_cache/ +# Web generator assets (built by scripts/web_generator/build_assets.py) and downloads +docs/en/assets/fastkit-generator/ +.cache/web-generator/ + .pdm-python ### VisualStudioCode template .vscode/* diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index d295fec3..962cb9bb 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -17,7 +17,7 @@ repos: entry: black --config pyproject.toml --check . language: python types: [python] - additional_dependencies: ['black>=24.10.0'] + additional_dependencies: ['black==26.10.1'] pass_filenames: false - id: isort-check @@ -25,7 +25,7 @@ repos: entry: isort --sp pyproject.toml --check-only --diff . language: python types: [python] - additional_dependencies: ['isort>=5.13.2'] + additional_dependencies: ['isort==9.0.1'] pass_filenames: false - id: isort-fix @@ -33,7 +33,7 @@ repos: entry: isort --sp pyproject.toml . language: python types: [python] - additional_dependencies: ['isort>=5.13.2'] + additional_dependencies: ['isort==9.0.1'] pass_filenames: false - id: black-fix @@ -41,7 +41,7 @@ repos: entry: black --config pyproject.toml . language: python types: [python] - additional_dependencies: ['black>=24.10.0'] + additional_dependencies: ['black==26.10.1'] pass_filenames: false - id: mypy @@ -50,12 +50,12 @@ repos: language: python types: [python] additional_dependencies: - - mypy>=1.12.0 - - rich>=13.9.2 - - click>=8.1.7 - - pyyaml>=6.0.0 - - jinja2>=3.1 - - types-PyYAML>=6.0.12 + - mypy==2.3.1 + - rich==15.0.0 + - click==8.3.2 + - pyyaml==6.0.3 + - jinja2==3.1.6 + - types-PyYAML==6.0.12.20260408 pass_filenames: false ci: diff --git a/CHANGELOG.md b/CHANGELOG.md index bd6fc5f0..27007391 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,108 @@ # Changelog +## v2.0.0 + +### Highlights + +- **Web generator:** a page on the documentation site creates a project in your browser and downloads it as a zip with the same files as `fastkit init ... --no-venv`. It shows the matching command line and the next steps, works in all seven documentation languages, and uploads nothing you enter. +- **Levels and one `fastkit init`:** `init` is the single way to create a project. It asks for a name and a level, from a single `main.py` to a production layout: `hello`, `single-file`, `layered`, `domain` and `production` (PostgreSQL, Alembic, JWT, coverage, structured logging, ruff, GitHub Actions, Docker). `init --template ` copies a bundled template and replaces `startdemo`. +- **Features you can read:** each selected feature gets a section in the project's `README.md`, generated code explains a FastAPI concept at its first use with a link to the FastAPI documentation, and at the `layered` level and above with a SQL database the example `/items` API stores its items in that database. +- **Next steps:** after creating a project, fastkit prints the commands that apply to it (environment, `.env`, database, server, tests, `addroute`, the next level) and writes the steps for a fresh checkout into the project's `README.md`. +- **`fastkit doctor`** checks an existing project for problems that newer templates fixed; with `--fix` it applies the safe fixes after showing them. +- **Documentation** is rebuilt around a Learn track that follows one project from `hello` to `production`, and is available in English, Korean, Japanese, Chinese, Spanish, French and German. +- **New `fastapi-hello` template:** one `main.py` and its tests, for people who have never written a FastAPI app. + +### Breaking changes + +[Upgrade from fastkit 1.x](https://bnbong.github.io/FastAPI-fastkit/how-to/upgrade-from-1x/) explains what to change in commands, scripts and saved configurations. Projects generated with 1.x keep working. + +- **Commands:** `init` asks no stack question (`minimal` / `standard` / `full`); levels and features generate the code for what they add. Without a terminal `init` asks nothing and needs `--project-name` (or `--config`); answers piped to stdin are no longer read, and `--interactive` is accepted and has no effect. `startdemo` keeps working as an alias of `init --template` and prints a one-line note. +- **Removed templates:** instead of `fastapi-async-crud` and `fastapi-psql-orm` use `fastapi-sqlmodel` (async; SQLite, PostgreSQL or MySQL) or a level with `--database`; instead of `fastapi-dockerized` use `fastapi-default` or `--feature deployment=Docker`; instead of `fastapi-empty` use `--level single-file`. +- **Saved configurations** still load, but a `minimal` preset, or no preset, now creates a `single-file` project (`fastapi-single-module`). The CORS and Pagination options are no longer offered, because every project includes them, and `fastapi-pagination` is no longer installed. +- **One HTTP contract** for every template except `fastapi-hello`, the code `init` generates for its options and the routes `addroute` writes: + +| | v1.5.2 | v2.0.0 | +|---|---|---| +| Business routes | `/items` at the root in `fastapi-default` and `fastapi-custom-response`; `init` auth routes at `/auth/...` | Under `API_V1_PREFIX` (default `/api/v1`), e.g. `/api/v1/items`, `/api/v1/auth/...` | +| Liveness | `/api/v1/health` in `fastapi-domain-starter`, `fastapi-sqlmodel`, `fastapi-auth-jwt`, `fastapi-llm-agent`; elsewhere `/health` returning `{"status": "healthy"}` | `GET /health` at the root, always `{"status": "ok"}` | +| Readiness | none | `GET /ready` where a database or cache exists: 200 `{"status": "ok"}` or 503 `{"status": "unavailable"}` | +| List endpoints | Plain JSON array (`fastapi-mcp`: `page` / `page_size`) | `limit` (1-100, default 20) and `offset`; body `{"items", "total", "limit", "offset"}` | +| Create | 201 | 201 with a `Location` header | +| Delete | 200 with a message (most templates) | 204, empty body | +| Update | PUT applied partial updates in some templates | PUT replaces the resource; PATCH updates the fields sent | +| Not found | Varies | 404 `{"detail": " not found"}` | +| Collection path | `/items/` in `fastapi-mcp` and `fastapi-custom-response` | `/items` (no trailing slash) | +| Schemas | `ItemResponse`, `ItemPublic` | `ItemCreate`, `ItemUpdate`, `ItemRead` | + +- **Settings and secrets:** every project except `hello` reads its configuration from one settings module that loads `.env`, and outside `development` it refuses to start with a missing, example or shorter than 32-byte `SECRET_KEY` (in `development` an example key only warns). Every 401 carries `WWW-Authenticate`. +- **`fastapi-mcp`:** `API_V1_STR` is renamed `API_V1_PREFIX` and the OpenAPI schema moves to `/openapi.json`. `POST /api/v1/auth/login` is removed (use `POST /api/v1/auth/token`), `/auth/me` becomes `GET /api/v1/users/me`, `/auth/users` becomes `GET /api/v1/users` (superusers only), and `/mcp-routes/*` is replaced by `GET /api/v1/mcp-server`. Only the six item operations are MCP tools. Send the MCP key as `X-MCP-API-Key` (`Authorization: Bearer ` still works), so that `Authorization` can carry a user token. +- **`fastapi-auth-jwt`:** a rejected refresh token answers 400 `{"error": "invalid_grant"}` instead of 401, token responses add `expires_in`, and `GET /api/v1/users` returns the page envelope. +- **`fastapi-sqlmodel`:** `ItemPublic` is renamed `ItemRead`, and the schema is left to Alembic by default (`CREATE_TABLES_ON_STARTUP=false`): run `alembic upgrade head` before the first start. +- **`fastapi-llm-agent`:** the server generates conversation ids; send `conversation_id` only to continue a conversation, and an unknown id answers 404. +- **`fastapi-custom-response`:** errors, including validation errors and unhandled exceptions, use the response envelope, and 500 responses no longer contain exception text. +- **`init` options:** with Session-based or OAuth2 authentication `GET /auth/me` moves to `GET /api/v1/users/me` and logout answers 204; FastAPI-Users needs PostgreSQL, MySQL or SQLite; the WebSocket connection list moves from `/api/v1/ws/connections` to `/api/v1/connections` (`/ws` is unchanged). +- **Exit statuses:** `init` and `startdemo` exit with 1 when they refuse to run or fail (including an in-place overwrite without a terminal or `--yes`) and with 2 on invalid options. `addroute` exits with 1 on errors and refuses route names that are not lower-case ASCII. `deleteproject` exits with 1 when the project does not exist, is not a fastkit project or cannot be deleted. `runserver` in a project without `.venv` exits with 1 unless you choose to continue with the current Python. + +### Upgrade notes for existing projects + +Upgrading fastkit does not change an existing project. Run `fastkit doctor` in it to see what can be checked and fixed automatically, then: + +1. **Clients of a regenerated project:** apply the contract changes above (paths under `/api/v1`, `/health`, the list envelope, 204 on delete). +2. **Docker:** images built from the new Dockerfiles set `ENVIRONMENT=production` and do not contain `.env`; pass the settings at run time, including a `SECRET_KEY` of at least 32 bytes, as the comment at the end of the project's `Dockerfile` shows. For a project created from a level that is `docker run -p 8000:8000 --env-file .env -e ENVIRONMENT=production ` (the generated `.env` sets `ENVIRONMENT=development`); `fastapi-sqlmodel` and `fastapi-auth-jwt` pass `SECRET_KEY` with `-e` instead, because the `DATABASE_URL` in their `.env` would replace the image's SQLite path. +3. **`fastapi-auth-jwt` and `fastapi-sqlmodel` projects that adopt the new template code:** run `alembic upgrade head` for the new migration (timezone-aware timestamps). +4. **Projects from the removed templates** need no change and keep working with `addroute`, `doctor` and `runserver`; `doctor` still recognises their example secrets. To move to PostgreSQL or MySQL with `fastapi-sqlmodel`, set `DATABASE_URL` and install the matching driver extra. +5. **Scripts:** replace piped answers with options, e.g. `fastkit init --project-name api --level layered --database SQLite -y`, or with `--config`. To move from `startdemo`, use `fastkit init --template --project-name ` and pass `--author`, `--author-email` and `--description`, or let `git config` fill author and email. +6. **The old stacks:** the closest replacements are `--level single-file` for `minimal`, and a level with `--database` and `--feature migrations=Alembic` or `--feature async_tasks=Celery` for `standard` and `full`. +7. **`single-file` projects generated with features** now keep the template's `/health`, so its OpenAPI operation id is `health_health_get` instead of `health_check_health_get`; regenerate API clients that use operation ids. + +### CLI + +- New `init` options: `--level`, `--database`, `--feature AXIS=VALUE`, `--extra-package`, `--template`, `--in-place`, and `--name` for `--project-name`. Author and email default to `git config` (an empty author is left out of `pyproject.toml`), and the package manager to uv when it is installed, otherwise pip (choose another in the customise step or with `--package-manager`). `-y` uses the defaults without asking. +- `init` prints a summary, the files it created and the next steps; its internal steps appear only with `fastkit --debug init`. It refuses a project name that is also the name of one of the project's dependencies (such as `sqlmodel`), because the package manager would not install that dependency. +- `--save-config` works for every `init` run except `--dry-run` and records the level or template. In a config file `project_name` is the only required key, `version` (a PEP 440 version, quoted in YAML) sets the project's version, and `--project-name`, `--author`, `--author-email` and `--description` override the file's values. +- `init --template` and `startdemo` check the template name before asking anything, suggest close matches and point to `fastkit list-templates`. Their summary and `--dry-run` list show only runtime dependencies, and the `--dry-run` file list matches the files that are written. +- `doctor [PATH]` checks for a committed or unignored `.env`, a missing `.env.example`, example secrets, an MCP server without authentication, CORS `*` with credentials, plain `sqlalchemy` without `greenlet`, CRLF scripts and more, and never prints secret values. `--fix` shows the diff of the safe fixes and asks once (`--yes` without a terminal), `--dry-run` / `--diff` only previews, `--format json` is for CI and `--force` checks projects generated before 1.4.0; it exits with 0 when no problem is left, 1 when problems remain and 2 when it could not run. +- `addroute` generates a typed CRUD resource with tests in both layouts (schemas, 201 with `Location`, 204, 404, paginated list) that follows the example `items` routes; in layered projects it adds the dependency to `src/api/deps.py`. New options: `--entity`, `--dry-run` and `--diff`; in a project from an older fastkit it also adds the `core/pagination.py` and `core/responses.py` the routes import. It refuses a route whose files exist, explains how to extend a single-file project such as `fastapi-hello` by hand, and sorts the imports it writes the way isort (black profile) does. +- `addroute` no longer counts a router registration under `if TYPE_CHECKING:` or `if False:` as present, and inserts imports below `from __future__` imports. +- `runserver` without `.venv` prints the commands that create it for the project's package manager before offering to continue. It exits with the server's exit status, and error tracebacks no longer show local variables, which could print secrets from the environment. +- `startdemo` and `init` refuse to write through a symbolic link in the target directory. When they fail or are interrupted after overwriting files in an existing directory, those files get their original content back; a file that cannot be restored keeps a backup whose path is printed. An existing `.env` is kept even when a custom template ships one. +- Poetry projects install with `poetry install` (`package-mode = false`); Poetry 2 or later is required, and fastkit stops before creating anything with an older one. PDM projects get their `.venv` inside the project even with `venv.in_project = false`. +- With `--no-venv` the output no longer depends on which package managers are installed. When an environment is being created and the requested package manager is missing, fastkit warns and sets the project up for an available one. +- `list-templates` lists templates from the simplest to the most involved, `list-features` shows every option `init` offers with package extras, and `fastkit --help` has a "Start here" section. A prompt that gets 10 invalid answers, or whose input ends, exits with status 1. `startdemo -y` asks only for the project name, and `runserver` rejects an invalid `app_module` in `[tool.fastapi-fastkit]`. +- fastkit requires click 8.2.0 or later. The minimum it declared before was too low: with click 8.1 the CLI did not start. + +### Generated projects + +- The levels after `hello` wire every selected feature into the template's own `main.py`. In `single-file`, the settings move to `src/core/config.py` only when a generated module reads them, and the summary says so. +- At the `layered`, `domain` and `production` levels with PostgreSQL, MySQL or SQLite, the example `/items` API uses that database and its tests run on in-memory SQLite. With MongoDB or Redis the items keep their own store and the README says so; `addroute` still adds an in-memory resource. +- JWT generates an OAuth2 password flow (`POST /api/v1/auth/register`, `POST /api/v1/auth/token`, `GET /api/v1/users/me`) with users in the selected SQL database or MongoDB (in memory otherwise). FastAPI-Users generates working routes with tests. +- Session-based logout invalidates the session, sessions have an absolute lifetime (`SESSION_ABSOLUTE_MAX_AGE`), and the demo account needs `ENABLE_DEMO_USERS=true`. OAuth2 requires `OAUTH_REDIRECT_BASE_URL` outside development. +- Rate-Limiting applies `RATE_LIMIT_DEFAULT` to every route and `RATE_LIMIT_AUTH` to the auth endpoints, using `limits` instead of slowapi. MongoDB uses PyMongo's async client instead of Motor, and the SQL session dependency no longer commits. +- Docker images run as a non-root user with a healthcheck and a `.dockerignore`, and get `.env` at run time. Docker Compose runs Alembic migrations in a one-shot `migrate` step before the app starts, keeps a SQLite file in a volume, always points the containers at the compose services (a `DATABASE_URL` in `.env` or the shell no longer redirects them), builds one image for the app, `migrate` and worker, and explains in its comments that `.env` runs the app in development mode. +- Test and lint tools stay out of runtime dependencies: they go to the dev group and to `requirements-dev.txt`, and Dockerfiles install runtime dependencies only. pytest and coverage settings live in `pyproject.toml`; projects with the ruff option pass their own `ruff check`. +- Structured logging writes one JSON access line per request with the request id, and Loguru is configured at startup. MySQL projects install `aiomysql[rsa]`, which MySQL 8's default authentication needs. +- A project generated from a feature selection keeps the minimum versions its template sets; a version you pin for the same package wins. + +### Templates + +- `fastapi-sqlmodel` runs on SQLite, PostgreSQL or MySQL, selected by `DATABASE_URL`, with driver extras, a docker compose file for a local server and migrations that work on all three. Its timestamps are timezone-aware and PUT is added. +- `fastapi-auth-jwt`: login, register and refresh are rate limited (`AUTH_RATE_LIMIT_*`), timestamps are timezone-aware, and `GET /api/v1/users/{user_id}` (superusers only) is added. +- `fastapi-mcp`: item reads are public, and PUT and PATCH work as specified. `fastapi-llm-agent`: the SSE stream is declared in OpenAPI, the conversation store is bounded (`MAX_CONVERSATIONS`, `MAX_MESSAGES_PER_CONVERSATION`), and there are hook points for authentication and rate limiting. +- Templates that store items in a JSON file no longer reuse ids and write atomically. Unused dependencies and `setup.cfg` files are removed, and Dockerfiles run as a non-root user. +- Every template ships a `requirements-dev.txt`, and every template except `fastapi-hello` ships a ruff configuration. `fastapi-single-module`, `fastapi-default` and `fastapi-domain-starter` include pytest-cov with coverage settings. + +### Documentation + +- Start, Learn, How-to, Reference and Contributing sections, with the same pages, menus and generated tables in all seven languages. Old page addresses redirect to their new pages. +- The CLI reference is generated from the CLI itself, and sections that described configuration files and environment variables fastkit never read are removed. + +### For contributors + +- `init` options, levels, templates and their translated texts are registered in `src/fastapi_fastkit/catalog/catalog.toml` and its `i18n/.toml` overlays; a new template needs an entry there (see the template creation guide). +- CI builds the web generator from the wheel and compares its output with the CLI for every case; the docs deploy does the same before publishing. Reference tables in the docs are generated with `scripts/docs_blocks.py`. +- Install the `test-runtime` dependency group (`pdm install -G dev -G test-runtime`) so the tests that start generated applications run. ruff joins the dev dependencies. +- The translation script leaves code and generated blocks untouched and supports OpenAI only; `scripts/update_nav_translations.py`, `scripts/setup-i18n-structure.sh` and the termynal assets are removed. + ## v1.5.2 (2026-12-01) ### Security diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b7933cd6..87967d93 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -21,17 +21,29 @@ This document will also be a good indicator for you to gain insight into the dir FastAPI-fastkit uses following stacks: - Python 3.12+ -- click 8.1.7+ +- click 8.2.0+ - rich 13.9.2+ +- Jinja2 3.1+ - pre-commit - pytest for testing - black for code formatting - isort for import sorting - mypy for static type checking -### Current Source Structure (Version 1.X.X+) +### Current Source Structure (Version 2.X.X+) -![fastkit diagram](docs/img/fastkit_diagram.png) +``` +src/fastapi_fastkit/ +├── cli.py # `fastkit` command group and the smaller commands +├── commands/ # init and startdemo +├── backend/ # interactive prompts, package managers, addroute, doctor, inspection +├── catalog/ # catalog.toml (levels, features, templates) and i18n overlays +├── generation/ # prompt-free generate() used by the CLI and the web generator +├── core/ # settings and exceptions +├── utils/ # file I/O, platform and output helpers +├── fragments/ # Jinja2 fragments for init features +└── fastapi_project_template/ # bundled templates; modules/ holds the files addroute writes +``` ### Quick Setup with Makefile @@ -55,7 +67,8 @@ This single command will: - Install the package in development mode with all dev dependencies - Install documentation dependencies - Set up pre-commit hooks -- Create a ready-to-use development environment + +The tests that start generated applications also need the `test-runtime` dependency group; without it they are skipped. Install it with `pip install --group test-runtime` (pip 25.1 or later). [Development setup](docs/en/contributing/development-setup.md) shows the same setup with pdm or uv. ### Manual Setup (Alternative) @@ -111,7 +124,7 @@ Key commands for contributors: - `make serve-docs` - Serve documentation locally #### Translation -- `make translate` - Translate documentation (supports LANG, PROVIDER, MODEL parameters) +- `make translate` - Translate documentation (supports LANG and MODEL parameters) ### Development Workflow @@ -234,14 +247,16 @@ When adding a new FastAPI template project, follow these guidelines: 1. Directory Structure: +A template needs at least `README.md-tpl`, `pyproject.toml-tpl` (with `fastapi` in `[project].dependencies`), a `main.py-tpl` that creates the `FastAPI` application (at the template root, in `src/` or in `src/app/`) and a `tests/` folder with a `test_*.py-tpl` module. Most templates also ship the files below (`fastapi-hello` deliberately ships only `main.py-tpl`, its tests, the requirements files, `README.md-tpl` and `.gitignore-tpl`): + ``` template-name/ ├── src/ │ ├── main.py-tpl -│ ├── config/ -│ ├── models/ -│ ├── routes/ -│ └── utils/ +│ ├── api/ +│ ├── core/ # config.py-tpl, pagination.py-tpl, responses.py-tpl +│ ├── crud/ +│ └── schemas/ ├── tests/ ├── scripts/ ├── pyproject.toml-tpl @@ -249,31 +264,41 @@ template-name/ ├── README.md-tpl ├── .env.example-tpl ├── .gitattributes-tpl -└── .gitignore-tpl +├── .gitignore-tpl +├── Dockerfile-tpl # optional +└── .dockerignore-tpl # required with a Dockerfile ``` 2. File Extensions: - All Python source files must use `.py-tpl` extension - - Template files must include proper configuration files (`.env.example-tpl`, `.gitignore-tpl`, `.gitattributes-tpl`, etc.), never `.env-tpl` (fastkit generates `.env`) + - A template that reads settings ships `.env.example-tpl` (and `.gitattributes-tpl`), never `.env-tpl` (fastkit generates `.env`) - `.gitignore-tpl` must ignore `.env` and `.env.*` and keep `!.env.example` 3. Dependencies: - - Declare dependencies in `pyproject.toml-tpl` (`requires-python = ">=3.12"`); no `setup.py-tpl`, no `FastAPI-fastkit` dependency + - Declare dependencies and tool settings in `pyproject.toml-tpl` (`requires-python = ">=3.12"`); no `setup.py-tpl` or `setup.cfg-tpl`, no `FastAPI-fastkit` dependency - Specify version numbers in requirements.txt - Use latest stable versions of dependencies -See [Template Creation Guide](docs/en/contributing/template-creation-guide.md) for the full rules. +4. API conventions: + - Business routes under `API_V1_PREFIX` (`/api/v1`), `GET /health` returning `{"status": "ok"}` at the root, paginated lists (`limit` / `offset`, `{"items", "total", "limit", "offset"}`), 201 with `Location`, 204 on delete, `XCreate` / `XUpdate` / `XRead` schemas + - `core/pagination.py-tpl` and `core/responses.py-tpl` identical to `fastapi_project_template/modules/core/` + - Every `ENVIRONMENT` except `development` (`staging`, `production`) refuses a missing, example, or shorter than 32-byte `SECRET_KEY` + +5. Catalog registration: + - Add a `[[templates]]` entry to `src/fastapi_fastkit/catalog/catalog.toml` and its translations to every `catalog/i18n/.toml` overlay (see the Template Creation Guide) + +See [Template Creation Guide](docs/en/contributing/template-creation-guide.md) for the full rules and the conventions checklist. ### Security Requirements -1. Implementation Requirements: +1. Implementation Requirements (for templates with settings, that is every template except `fastapi-hello`): - Environment variables management (`.env.example` committed, `.env` git-ignored) - - Basic authentication system - - CORS configuration + - Authentication where the template's purpose needs it + - CORS origins only from `BACKEND_CORS_ORIGINS`, with credentials off for `*` - Exception handling and logging 2. Security Checks: - - All template code must pass `inspector.py` validation + - The template must pass the template inspection: `make inspect-template TEMPLATES="your-template-name"` - Include security middleware configurations - Follow security guidelines in SECURITY.md @@ -313,12 +338,12 @@ Additionally, a **Weekly Template Inspection** runs every Wednesday to validate - ⚡ No manual test file creation needed - 🛡️ Consistent quality standards applied -**Comprehensive Test Coverage:** -- ✅ **Project Creation**: Template copying and metadata injection -- ✅ **Package Manager Support**: UV, PDM, Poetry, and PIP compatibility -- ✅ **Virtual Environment**: Creation and dependency installation -- ✅ **Project Structure**: File and directory validation -- ✅ **FastAPI Integration**: Project identification and functionality +**What the tests check:** +- ✅ **Project Creation**: Every template is generated with `--no-venv`; metadata is injected and no placeholder is left +- ✅ **Project Structure**: `README.md-tpl` and `pyproject.toml-tpl` exist, no `setup.py-tpl`, and the expected files and folders are generated +- ✅ **Project Identification**: The generated project is recognised as a fastkit project + +These tests do not create a virtual environment or install anything. The template inspection (`make inspect-template`) installs the dependencies and runs the template's own tests. **Test Execution:** ```bash @@ -385,11 +410,12 @@ $ fastkit startdemo your-template-name --package-manager pip ```bash make dev-check # Must pass all checks ``` - - [ ] All files use .py-tpl extension - - [ ] FastAPI-fastkit dependency included + - [ ] All Python files use the `.py-tpl` extension + - [ ] No FastAPI-fastkit dependency + - [ ] Template registered in `catalog.toml` and the `i18n/.toml` overlays - [ ] Security requirements met - [ ] Documentation complete - - [ ] inspector.py validation passes + - [ ] `make inspect-template TEMPLATES="your-template-name"` passes - [ ] All make dev-check tests pass - [ ] **Automatic template tests pass** (new templates tested automatically) - [ ] **Package manager compatibility verified** (tested with UV, PDM, Poetry, PIP) @@ -409,219 +435,18 @@ For more detailed information about security requirements and project guidelines ## Contributing Translations -FastAPI-fastkit documentation supports multiple languages. Contributing translations helps users worldwide. - -### Supported Languages - -- 🇬🇧 English (en) - Default -- 🇰🇷 Korean (ko) -- 🇯🇵 Japanese (ja) -- 🇨🇳 Chinese (zh) -- 🇪🇸 Spanish (es) -- 🇫🇷 French (fr) -- 🇩🇪 German (de) - -### Translation Setup - -#### 1. Install Dependencies +The documentation is published in seven languages: English (`en`), Korean (`ko`), Japanese (`ja`), Chinese (`zh`), Spanish (`es`), French (`fr`) and German (`de`). English in `docs/en/` is the source, and every page exists at the same path under `docs//` in each language. -```bash -pdm install -G docs -G translation -# Or: pip install mkdocs mkdocs-material mkdocs-static-i18n openai anthropic -``` - -#### 2. Set Up API Key +The [Translation Guide](docs/en/contributing/translation-guide.md) describes the whole process: what stays in English, the generated tables, the catalog overlays, the web generator page, the menu labels in `mkdocs.yml`, machine translation with `scripts/translate.py` (`make translate`), and the checks a translation must pass. Follow it rather than this file. -Get an API key from OpenAI or Anthropic and set it as an environment variable: +Before opening a translation PR (with the `[DOCS]` tag), run the checks from the guide: ```bash -export TRANSLATION_API_KEY="your-api-key-here" +python scripts/docs_blocks.py --check +python -m pytest tests/test_docs tests/test_catalog -q +mkdocs build --strict -d site ``` -#### 3. First-Time Setup (Maintainers Only) - -If this is the first time setting up the i18n structure: - -```bash -./scripts/setup-i18n-structure.sh -``` - -This migrates existing English docs to `docs/en/` and creates language directories. - -### Translating Documentation - -#### Using Make Commands (Recommended) - -```bash -# Translate all docs to all configured languages -make translate - -# Translate to specific language -make translate LANG=ko - -# Specify API provider and model -make translate LANG=ko PROVIDER=github MODEL=gpt-4o-mini -make translate LANG=ko PROVIDER=openai MODEL=gpt-4 -``` - -#### Using Script Directly - -```bash -# Translate all docs to Korean -python scripts/translate.py --target-lang ko --api-provider openai - -# Translate specific files (paths relative to docs/en/) -python scripts/translate.py --target-lang ko --files index.md user-guide/installation.md --api-provider openai - -# Translate without creating PR (for local testing) -python scripts/translate.py --target-lang ko --no-pr --api-provider openai -``` - -#### Using GitHub Actions - -1. Go to repository → Actions → "Translate Documentation" -2. Click "Run workflow" -3. Select target language and options -4. Wait for automated PR to be created -5. Review and merge the translation - -### Translation Workflow - -1. **Write English documentation** in `docs/en/` -2. **Test locally**: `mkdocs serve` -3. **Commit English version** to main branch -4. **Run translation script** or trigger GitHub Actions -5. **Review PR**: Check formatting, technical terms, links -6. **Merge** and deploy - -### Translation Quality Guidelines - -When reviewing translations: - -- ✅ Markdown formatting is preserved -- ✅ Code blocks are unchanged -- ✅ Technical terms are appropriate -- ✅ Links work correctly -- ✅ Grammar and spelling are correct - -### Manual Translation - -You can also translate manually: - -1. Copy file from `docs/en/` to `docs/{lang}/` -2. Translate the content -3. Create PR with `[DOCS]` tag - -### Adding New Languages - -To add support for a new language: - -1. **Update `scripts/translation_config.json`**: -```json -{ - "code": "pt", - "name": "Portuguese", - "native_name": "Português", - "enabled": true -} -``` - -2. **Update `mkdocs.yml`**: -```yaml -- locale: pt - name: Português - build: true -``` - -3. **Run translation**: -```bash -python scripts/translate.py --target-lang pt -``` - -### Translation System Architecture - -**Core Components:** - -- **`scripts/translate.py`**: AI-powered translation script - - Supports OpenAI GPT-4 and Anthropic Claude - - Preserves markdown formatting and code blocks - - Creates GitHub PRs automatically - -- **`scripts/setup-i18n-structure.sh`**: Migration tool - - Moves docs to language-specific directories - - Creates symbolic links for shared assets - -- **`scripts/translation_config.json`**: Configuration - - Language settings - - Translation options - - Quality check parameters - -- **`.github/workflows/translate-docs.yml`**: GitHub Actions workflow - - Automated translation on trigger - - Manual workflow dispatch - -**Directory Structure:** - -``` -docs/ -├── en/ # English (source) -├── ko/ # Korean -├── ja/ # Japanese -├── zh/ # Chinese -├── es/ # Spanish -├── fr/ # French -├── de/ # German -├── css/ # Shared assets -├── js/ -└── img/ -``` - -### Troubleshooting - -**Import Error:** -```bash -pip install openai anthropic -``` - -**API Key Error:** -```bash -export TRANSLATION_API_KEY="your-key" -``` - -**Build Fails:** -```bash -# Ensure docs are in language directories -ls -la docs/en/index.md -``` - -For detailed translation guidelines, see [Translation Guide](docs/en/contributing/translation-guide.md). - -### Updating Navigation Translations - -When you add new documentation pages, update navigation translations: - -**Option 1: Automatic Update (Recommended)** - -```bash -# Update all language nav translations automatically -python scripts/update_nav_translations.py - -# With AI translation for missing items -python scripts/update_nav_translations.py --api-key "your-key" -``` - -**Option 2: Manual Update** - -Edit `mkdocs.yml` and add translations for each language under `nav_translations`: - -```yaml -- locale: ko - nav_translations: - New Page Title: 새로운 페이지 제목 -``` - -**Note:** Korean translations should be kept complete. Other languages use basic translations (Home, User Guide, Tutorial, etc.). Native speakers can contribute more detailed translations via PR. - ## Additional note If you look at source codes, you will see a commentary at the top of the module that describes about the module. diff --git a/MANIFEST.in b/MANIFEST.in index 502804e8..b1fa7b8c 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -4,3 +4,6 @@ recursive-exclude src/fastapi_fastkit/fastapi_project_template *.pyo recursive-exclude src/fastapi_fastkit/fastapi_project_template __pycache__ recursive-include src/fastapi_fastkit/fragments * recursive-exclude src/fastapi_fastkit/fragments __pycache__ +recursive-include src/fastapi_fastkit/catalog *.toml +recursive-include src/fastapi_fastkit/catalog/i18n * +recursive-exclude src/fastapi_fastkit/catalog __pycache__ diff --git a/Makefile b/Makefile index 3970ebc6..79bd78f8 100644 --- a/Makefile +++ b/Makefile @@ -45,7 +45,7 @@ inspect-templates-verbose: ## Run template inspection with verbose output inspect-template: ## Inspect specific template(s) - Usage: make inspect-template TEMPLATES="template-name" @if [ -z "$(TEMPLATES)" ]; then \ echo "Usage: make inspect-template TEMPLATES=\"template-name1,template-name2\""; \ - echo "Example: make inspect-template TEMPLATES=\"fastapi-default,fastapi-async-crud\""; \ + echo "Example: make inspect-template TEMPLATES=\"fastapi-default,fastapi-hello\""; \ exit 1; \ fi python scripts/inspect-templates.py --templates "$(TEMPLATES)" @@ -102,11 +102,13 @@ serve-docs: ## Serve documentation locally mkdocs serve # Development workflow commands +# docs is a dependency group, not an extra: install its export, +# requirements-docs.txt, as the docs workflow does. dev-setup: ## Set up development environment from scratch @echo "Setting up development environment..." pip install --upgrade pip pip install -e ".[dev]" - pip install -e ".[docs]" || pip install -r requirements-docs.txt + pip install -r requirements-docs.txt pre-commit install @echo "Development environment setup complete!" @@ -139,11 +141,10 @@ all: ## Run complete development workflow $(MAKE) build # Translation commands -translate: ## Translate documentation - Usage: make translate LANG=ko PROVIDER=github MODEL=gpt-4o-mini +translate: ## Translate documentation - Usage: make translate LANG=ko MODEL=gpt-4o-mini @echo "Starting translation..." @CMD="python scripts/translate.py"; \ if [ -n "$(LANG)" ]; then CMD="$$CMD --target-lang $(LANG)"; fi; \ - if [ -n "$(PROVIDER)" ]; then CMD="$$CMD --api-provider $(PROVIDER)"; fi; \ if [ -n "$(MODEL)" ]; then CMD="$$CMD --model $(MODEL)"; fi; \ echo "Running: $$CMD"; \ $$CMD diff --git a/README.md b/README.md index e608e813..952a8d0a 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@

- FastAPI-fastkit + FastAPI-fastkit

FastAPI-fastkit: Fast, easy-to-use starter kit for new users of Python and FastAPI @@ -12,7 +12,7 @@ GitHub Release - + Code coverage PyPI Downloads @@ -21,197 +21,121 @@ --- -This project was created to speed up the configuration of the development environment needed to develop Python-based web apps for new users of Python and [FastAPI](https://github.com/fastapi/fastapi). +FastAPI-fastkit creates [FastAPI](https://github.com/fastapi/fastapi) projects with working code and tests. Five levels lead from a single `main.py` of three endpoints to a production layout with a database, authentication, CI and Docker, each building on the one before. The code of every level explains itself: comments link the FastAPI documentation page behind each concept, and every project ends with a list of next steps. -This project was inspired by the `SpringBoot initializer` & Python Django's `django-admin` CLI operation. +**Documentation:** (English, 한국어, 日本語, 中文, Español, Français, Deutsch) -## Key Features +## Try it in your browser -- **⚡ Immediate FastAPI project creation** : Super-fast FastAPI workspace & project creation via CLI, inspired by `django-admin` feature of [Python Django](https://github.com/django/django) -- **✨ Interactive project builder**: Guided step-by-step feature selection for databases, authentication, caching, monitoring, and more with auto-generated code -- **🎨 Prettier CLI output** : Beautiful CLI experience powered by [rich library](https://github.com/Textualize/rich) -- **📋 Standards-based FastAPI project templates** : Templates follow Python standards and common FastAPI patterns. -- **🔍 Automated template quality assurance** : Weekly automated testing ensures all templates remain functional and up-to-date -- **🚀 Multiple project templates** : Choose from various pre-configured templates for different use cases (async CRUD, Docker, PostgreSQL, etc.) -- **📦 Multiple package manager support** : Choose your preferred Python package manager (pip, uv, pdm, poetry) for dependency management -- **🧾 Reproducible project configs** : Save an interactive session to a `.json` / `.toml` / `.yaml` file and replay it with `fastkit init --config` -- **🏷️ Self-describing projects** : Every generated project records its template, preset, package manager, entrypoint and selected features in a `[tool.fastapi-fastkit]` block that `runserver` and `addroute` read back +The [web generator](https://bnbong.github.io/FastAPI-fastkit/start/web-generator/) works like Spring Initializr: choose a level, a database and features, watch the file list change, and download the project as a zip file. It runs the fastkit generator itself in your browser through [Pyodide](https://pyodide.org/), so nothing you enter is sent anywhere. The zip holds the same files as the `fastkit init ... --no-venv` command that the page shows next to the form. -## Installation +![The web generator with the domain level, SQLite and JWT authentication chosen: the customise form on the left; on the right the file list of 52 files with the auth package open, the matching fastkit init command and the Generate and download button](https://raw.githubusercontent.com/bnbong/FastAPI-fastkit/main/docs/img/2.0/web-generator-customise.png) -Install `FastAPI-fastkit` in your Python environment. +After the download, the page lists the next steps for this project and what each selected feature added: its files, its settings and a link to the documentation. -```console -$ pip install FastAPI-fastkit -``` +![The web generator after the download: shop.zip downloaded with 52 files, the numbered Next steps from cd shop to fastkit init --level production, and the Selected features section for the SQLite database](https://raw.githubusercontent.com/bnbong/FastAPI-fastkit/main/docs/img/2.0/web-generator-result.png) +You still need Python on your machine to run the project. [Web generator](https://bnbong.github.io/FastAPI-fastkit/start/web-generator/) in the documentation describes every choice on the page. -## Usage +## Install -- Global options - - `--help`: Show help - - `--version`: Show version - - `--debug/--no-debug`: Toggle debug mode +fastkit needs Python 3.12 or later. Install it with pip into a virtual environment, or with uv as a tool of its own: -### Create a new FastAPI project -```console -fastkit init [OPTIONS] -``` -> [!TIP] -> Scaffolds an empty FastAPI project, creates a virtual environment, installs dependencies - -- Key options: - - `--project-name`, `--author`, `--author-email`, `--description` - - `--package-manager` [pip|uv|pdm|poetry] - - `--config `: create the project from a saved config file (`.json` / `.toml`, and `.yaml` when PyYAML is installed) with no prompts - - `--save-config `: with `--interactive`, record the answers for later reuse - - `--dry-run`: print the files and packages that would be created, write nothing - - `--no-venv`: skip virtual environment creation (implies `--no-install`) - - `--no-install`: skip dependency installation - - `--yes` / `-y`: skip the "Overwrite these files?" confirmation when deploying in place - - Stack selection: `minimal` | `standard` | `full` (interactive) - -### Create a project with interactive mode ```console -fastkit init --interactive +$ pip install fastapi-fastkit +$ uv tool install fastapi-fastkit ``` -> [!TIP] -> Guided step-by-step project setup with intelligent feature selection - -- Features: - - **Architecture preset**: `minimal` | `single-module` | `classic-layered` | `domain-starter` (default) - - **Database selection**: PostgreSQL, MySQL, MongoDB, Redis, SQLite - - **Authentication**: JWT, OAuth2, FastAPI-Users, Session-based - - **Background tasks**: Celery, Dramatiq - - **Caching**: Redis, fastapi-cache2 - - **Monitoring**: Loguru, OpenTelemetry, Prometheus - - **Testing**: Basic (pytest), Coverage, Advanced (with faker, factory-boy) - - **Utilities**: CORS, Rate-Limiting, Pagination, WebSocket - - **Logging**: structured JSON logging with a request-id middleware - - **Migrations**: Alembic (async env, baseline revision) - - **Tooling**: ruff, pre-commit, GitHub Actions, devcontainer, Makefile (multi-select) - - **Deployment**: Docker, docker-compose with auto-generated configs - - **Package manager**: pip, uv, pdm, poetry - - **Custom packages**: Add your own dependencies -- Auto-generates (varies by preset - see [the matrix](https://bnbong.github.io/FastAPI-fastkit/reference/preset-feature-matrix/) for details): - - `main.py` regenerated from selected features for `minimal` / `single-module`; preserved as-shipped for `classic-layered` / `domain-starter` - - Database and authentication configuration files at preset-specific paths - - Docker deployment files (`Dockerfile`, `docker-compose.yml`) with the preset's correct uvicorn entrypoint - - Test configuration (pytest with coverage) - - `/health` and `/ready` endpoints on every generated project - - Real working code — not just installed packages — for background tasks, caching, WebSocket, pagination, OpenTelemetry, OAuth2 and session-based auth - - `--dry-run` previews the exact file tree a run would create, including logging/migrations/tooling artifacts - -### Create a project from a template -```console -fastkit startdemo [TEMPLATE] [OPTIONS] -``` -> [!TIP] -> Creates a project from a template (e.g., `fastapi-default`) and installs dependencies -- Key options: - - `--project-name`, `--author`, `--author-email`, `--description` - - `--package-manager` [pip|uv|pdm|poetry] - - `--dry-run`, `--no-venv`, `--no-install`, `--yes`/`-y` — same meaning as on `init` - - Refuses to run if the target project directory already exists (`--dry-run` excepted) -- Tip: List available templates with `fastkit list-templates` +When uv is installed, fastkit uses it for the projects it creates; otherwise it uses pip. pdm and Poetry are also supported. [Installation](https://bnbong.github.io/FastAPI-fastkit/start/installation/) covers each option. -### Add a new route -```console -fastkit addroute -``` -- What it does: Adds a new API route to the specified project +## Create a project -### Run the development server -```console -fastkit runserver [OPTIONS] -``` -- What it does: Starts the uvicorn development server -- Key options: - - `--host`, `--port`, `--reload/--no-reload`, `--workers` +`fastkit init` asks for a project name and a level, shows a summary, creates the project and installs its dependencies. Type a project name and press Enter at every other question to get the `hello` level: one `main.py` with three endpoints and a test for each. The run ends with a Next steps panel, and the project's `README.md` lists the steps for a fresh checkout. + +![Terminal running fastkit init: the project name shop, the Levels table, the Project summary and the Next steps panel](https://raw.githubusercontent.com/bnbong/FastAPI-fastkit/main/docs/img/2.0/generate-init-dialogue.svg) + +In scripts and CI, pass every choice as an option and nothing is asked: -### List templates ```console -fastkit list-templates +$ fastkit init --project-name shop --level domain --database SQLite --feature authentication=JWT -y ``` -Available templates: - -| Template | Description | Notes | -|---|---|---| -| [`fastapi-default`](src/fastapi_fastkit/fastapi_project_template/fastapi-default/README.md-tpl) | Simple FastAPI project with a classic layered layout | Good first choice | -| [`fastapi-empty`](src/fastapi_fastkit/fastapi_project_template/fastapi-empty/README.md-tpl) | Minimal FastAPI template | Base for `minimal` preset | -| [`fastapi-single-module`](src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/README.md-tpl) | Single-file FastAPI app | Base for `single-module` preset | -| [`fastapi-domain-starter`](src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/README.md-tpl) | Domain-oriented, pyproject-first starter for medium-sized APIs | Base for `domain-starter` preset | -| [`fastapi-auth-jwt`](src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/README.md-tpl) | JWT authentication with refresh-token rotation, argon2 hashing and scopes | New in v1.4.0 | -| [`fastapi-sqlmodel`](src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/README.md-tpl) | Async SQLModel + Alembic migrations + generic CRUD with pagination | New in v1.4.0 | -| [`fastapi-llm-agent`](src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/README.md-tpl) | Streaming Claude chat agent (SSE) with a tool-call loop | New in v1.4.0 | -| [`fastapi-mcp`](src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/README.md-tpl) | FastAPI app exposed as an MCP server | | -| [`fastapi-psql-orm`](src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/README.md-tpl) | Item management API with PostgreSQL, SQLModel, Alembic and docker-compose | Requires Docker | -| [`fastapi-custom-response`](src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/README.md-tpl) | Item management API with a custom response envelope, error handling and pagination | | -| [`fastapi-async-crud`](src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/README.md-tpl) | Async item management API | **Deprecated** — use `fastapi-sqlmodel` | -| [`fastapi-dockerized`](src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/README.md-tpl) | Dockerized item management API | **Deprecated** — use `fastapi-default` with the Docker option in `init --interactive` | - -Deprecated templates still work but are no longer recommended starting points. See [Which starter should I choose?](https://bnbong.github.io/FastAPI-fastkit/user-guide/choosing-a-starter/) for a decision guide. - -### Delete a project -```console -fastkit deleteproject +In the project folder, `fastkit runserver` starts the app, and FastAPI's interactive documentation opens at . For the `hello` project from the guided run above: + +![Swagger UI at /docs of the shop app listing GET /, POST /items and GET /items/{item_id}, with the Schemas section below](https://raw.githubusercontent.com/bnbong/FastAPI-fastkit/main/docs/img/2.0/generate-swagger-ui.png) + +## Learn FastAPI from the generated code + +At every level, each FastAPI concept is explained where it first appears in the project, in a comment of at most two lines that ends with the link to the official tutorial page. The start of `main.py` at the `hello` level: + +```python +# `app` is the application object that uvicorn serves. +# https://fastapi.tiangolo.com/tutorial/first-steps/ +app = FastAPI(title="shop") + + +# An argument typed with a pydantic model (`item: Item`) is the validated JSON body. +# https://fastapi.tiangolo.com/tutorial/body/ +class Item(BaseModel): + name: str = Field(min_length=1, max_length=100) + price: float = Field(gt=0) + description: str | None = None ``` -## Documentation +The [Learn track](https://bnbong.github.io/FastAPI-fastkit/learn/generate/) follows one project, `shop`, through six pages: generate it, understand the code, extend it with routers and dependencies, test it, move it to a domain layout with a SQL database, and deploy it at the production level with Docker. -For comprehensive guides and detailed usage instructions, visit our documentation: +## Levels -- 🧭 **[Which starter should I choose?](https://bnbong.github.io/FastAPI-fastkit/user-guide/choosing-a-starter/)** - Beginner decision guide for `startdemo` templates and interactive presets -- 📚 **[User Guide](https://bnbong.github.io/FastAPI-fastkit/user-guide/quick-start/)** - Detailed installation and usage guides -- 🎯 **[Tutorial](https://bnbong.github.io/FastAPI-fastkit/tutorial/getting-started/)** - Step-by-step tutorials for beginners -- 📖 **[CLI Reference](https://bnbong.github.io/FastAPI-fastkit/user-guide/cli-reference/)** - Complete command reference -- 🧱 **[Architecture Preset Matrix](https://bnbong.github.io/FastAPI-fastkit/reference/preset-feature-matrix/)** - Per-preset / per-feature contract for interactive generation -- 🔍 **[Template Quality Assurance](https://bnbong.github.io/FastAPI-fastkit/reference/template-quality-assurance/)** - Automated testing and quality standards +Each level adds structure to the one above it. fastkit does not convert a project to another level; the Learn track shows how to move your code to the next one: -## Contributing +| Level | What you get | +|---|---| +| `hello` | One `main.py`: three endpoints, data in memory, tests. | +| `single-file` | The whole app in one module, with settings and tests. | +| `layered` | Separate layers: routes, CRUD, schemas, core config. | +| `domain` | One package per domain: router, service, repository. | +| `production` | `domain` plus PostgreSQL, Alembic migrations, JWT authentication, coverage, structured logging, ruff, GitHub Actions, Docker and Docker Compose. | + +At every level after `hello` you can choose a database (PostgreSQL, MySQL or SQLite through async SQLAlchemy, MongoDB or Redis) and features: authentication, background tasks, caching, monitoring, rate limiting, WebSocket, migrations, logging, developer tooling and container deployment. fastkit writes the code and configuration for each choice, with tests where they apply, and the generated README gets one section per selected feature. [Choose a level or an example](https://bnbong.github.io/FastAPI-fastkit/how-to/choose-a-level/) compares the levels, and [Levels and features](https://bnbong.github.io/FastAPI-fastkit/reference/levels-and-features/) lists every option with its packages. + +## Example projects -We welcome contributions from the community! FastAPI-fastkit is designed to help newcomers to Python and FastAPI, and your contributions can make a significant impact. +`fastkit init --template ` copies a complete example project as it is: -

-Contributing Guide +| Template | Shows | +|---|---| +| `fastapi-custom-response` | One response envelope for every answer, errors included | +| `fastapi-auth-jwt` | Accounts with access and refresh tokens | +| `fastapi-sqlmodel` | SQLModel and Alembic, with SQLite, PostgreSQL or MySQL | +| `fastapi-mcp` | Your API exposed to AI clients as MCP tools | +| `fastapi-llm-agent` | A streamed Claude chat reply with a tool-call loop | -### Quick Start for Contributors +[Start from an example project](https://bnbong.github.io/FastAPI-fastkit/how-to/example-projects/) describes what each one needs. -1. **Fork and clone the repository:** - ```bash - git clone https://github.com/bnbong/FastAPI-fastkit.git - cd FastAPI-fastkit - ``` +## Keep working on the project -2. **Set up development environment:** - ```bash - make dev-setup # Sets up everything you need - ``` +- `fastkit addroute orders` adds a resource to a generated project at any level except `hello`: its routes, schemas, data layer and tests, in the project's own layout, with the router registered. `--diff` previews the change. +- `fastkit runserver` starts the development server. +- `fastkit doctor` checks a project for problems that newer templates fix, such as a committed `.env`, an example secret still in use or shell scripts with CRLF line endings, and `fastkit doctor --fix` repairs the safe ones. [Check and fix a project](https://bnbong.github.io/FastAPI-fastkit/how-to/doctor/) explains the checks. -3. **Run development checks:** - ```bash - make dev-check # Format, lint, and test - ``` +[CLI reference](https://bnbong.github.io/FastAPI-fastkit/reference/cli/) describes every command and option. -### What You Can Contribute +## Upgrading from fastkit 1.x -- 🚀 **New FastAPI templates** - Add templates for different use cases -- 🐛 **Bug fixes** - Help us improve stability and reliability -- 📚 **Documentation** - Improve guides, examples, and translations -- 🧪 **Tests** - Increase test coverage and add integration tests -- 💡 **Features** - Suggest and implement new CLI features +Projects you already have keep working. `fastkit startdemo` is now `fastkit init --template` (the old command still works), the stack question is gone, and the templates `fastapi-async-crud`, `fastapi-dockerized`, `fastapi-psql-orm` and `fastapi-empty` were removed. [Upgrade from fastkit 1.x](https://bnbong.github.io/FastAPI-fastkit/how-to/upgrade-from-1x/) lists what to change in your commands and scripts. -### Contribution Guidelines +## Contributing -For detailed contribution guidelines, development setup, and project standards, please refer to: +Contributions are welcome: templates, bug fixes, documentation, translations and tests. -- **[CONTRIBUTING.md](CONTRIBUTING.md)** - Comprehensive contribution guide -- **[CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md)** - Project principles and community standards -- **[SECURITY.md](SECURITY.md)** - Security guidelines and reporting +```console +$ git clone https://github.com/bnbong/FastAPI-fastkit.git +$ cd FastAPI-fastkit +$ make dev-setup +$ make dev-check +``` -
+Read [CONTRIBUTING.md](https://github.com/bnbong/FastAPI-fastkit/blob/main/CONTRIBUTING.md), the [Code of Conduct](https://github.com/bnbong/FastAPI-fastkit/blob/main/CODE_OF_CONDUCT.md) and the [security policy](https://github.com/bnbong/FastAPI-fastkit/blob/main/SECURITY.md) before you open a pull request. [Development setup](https://bnbong.github.io/FastAPI-fastkit/contributing/development-setup/) explains the tests and checks. ## Significance of FastAPI-fastkit diff --git a/docs/css/custom.css b/docs/css/custom.css index 200ac45c..0d8a1d9f 100644 --- a/docs/css/custom.css +++ b/docs/css/custom.css @@ -1,17 +1,3 @@ -.termynal-comment { - color: #4a968f; - font-style: italic; - display: block; -} - -.termy [data-termynal] { - white-space: pre-wrap; -} - -.termy .linenos { - display: none; -} - a.external-link::after { /* \00A0 is a non-breaking space to make the mark be on the same line as the link @@ -69,3 +55,17 @@ a.internal-link::after { font-size: 80%; text-align: center; } + +/* Copy button of code blocks: copy the commands of a console block, not + its "$ " prompts or its output. Material sets data-md-copying on the + code element while it reads innerText, which skips hidden elements. */ +.highlight code[data-md-copying] .gp, +.highlight code[data-md-copying] .go { + display: none; +} + +/* An output line also drops its line break (pymdownx line spans); kept as + a rule of its own so browsers without :has() still apply the one above. */ +.highlight code[data-md-copying] span[id^="__span-"]:has(> .go) { + display: none; +} diff --git a/docs/css/termynal.css b/docs/css/termynal.css deleted file mode 100644 index 998b42b8..00000000 --- a/docs/css/termynal.css +++ /dev/null @@ -1,101 +0,0 @@ -/** - * termynal.js - * - * @author Ines Montani - * @version 0.0.1 - * @license MIT - */ - - :root { - --color-bg: #252a33; - --color-text: #eee; - --color-text-subtle: #a2a2a2; -} - -[data-termynal] { - width: 750px; - max-width: 100%; - background: var(--color-bg); - color: var(--color-text); - font-size: 14px; - font-family: 'Fira Mono', Consolas, Menlo, Monaco, 'Courier New', Courier, monospace; - border-radius: 4px; - padding: 75px 45px 35px; - position: relative; - -webkit-box-sizing: border-box; - box-sizing: border-box; -} - -[data-termynal]:before { - content: ''; - position: absolute; - top: 15px; - left: 15px; - display: inline-block; - width: 15px; - height: 15px; - border-radius: 50%; - /* A little hack to display the window buttons in one pseudo element. */ - background: #d9515d; - -webkit-box-shadow: 25px 0 0 #f4c025, 50px 0 0 #3ec930; - box-shadow: 25px 0 0 #f4c025, 50px 0 0 #3ec930; -} - -[data-termynal]:after { - content: 'bash'; - position: absolute; - color: var(--color-text-subtle); - top: 5px; - left: 0; - width: 100%; - text-align: center; -} - -[data-ty] { - display: block; - line-height: 1.6; -} - -[data-ty]:before { - /* Set up defaults and ensure empty lines are displayed. */ - content: ''; - display: inline-block; - vertical-align: middle; -} - -[data-ty="input"]:before, -[data-ty-prompt]:before { - margin-right: 0.75em; - color: var(--color-text-subtle); -} - -[data-ty="input"]:before { - content: '$'; -} - -[data-ty][data-ty-prompt]:before { - content: attr(data-ty-prompt); -} - -[data-ty-cursor]:after { - content: attr(data-ty-cursor); - font-family: monospace; - margin-left: 0.5em; - -webkit-animation: blink 1s infinite; - animation: blink 1s infinite; -} - - -/* Cursor animation */ - -@-webkit-keyframes blink { - 50% { - opacity: 0; - } -} - -@keyframes blink { - 50% { - opacity: 0; - } -} diff --git a/docs/css/web-generator.css b/docs/css/web-generator.css new file mode 100644 index 00000000..16cab5a5 --- /dev/null +++ b/docs/css/web-generator.css @@ -0,0 +1,698 @@ +/* Web generator page (docs//start/web-generator.md). Every selector is + scoped under .fkg; colours come from Material's theme variables so the + page follows the light/dark palette toggle without a reload. */ + +.fkg { + --fkg-error: #b3261e; + --fkg-border: var(--md-default-fg-color--lightest); + --fkg-muted: var(--md-default-fg-color--light); + --fkg-radius: 0.3rem; + margin: 1.2em 0 2em; + overflow-wrap: break-word; +} + +/* Korean breaks between words, not inside them. */ +.fkg:lang(ko) { + word-break: keep-all; +} + +/* Long German compounds: hyphenate (the page sets lang="de"). */ +.fkg:lang(de) { + hyphens: auto; +} + +[data-md-color-scheme="slate"] .fkg { + --fkg-error: #f2b8b5; +} + +.fkg *, +.fkg *::before, +.fkg *::after { + box-sizing: border-box; +} + +.fkg [hidden] { + display: none !important; +} + +.fkg .fkg-static { + color: var(--fkg-muted); +} + +/* ---------- layout ---------- */ + +.fkg .fkg-layout { + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: 1.5rem; +} + +@media screen and (min-width: 60em) { + .fkg .fkg-layout { + grid-template-columns: minmax(0, 3fr) minmax(0, 2fr); + align-items: start; + } +} + +.fkg .fkg-main > * + *, +.fkg .fkg-side > * + * { + margin-top: 1.25rem; +} + +.fkg .fkg-row { + display: flex; + flex-wrap: wrap; + gap: 0.5rem 0.75rem; + align-items: center; + margin: 0.6em 0 0; +} + +/* ---------- disclosure widgets: undo Material's admonition look ---------- */ + +.md-typeset .fkg details { + display: block; + margin: 0; + padding: 0; + overflow: visible; + font-size: inherit; + background: none; + border: 0; + border-radius: 0; + box-shadow: none; +} + +.md-typeset .fkg details > summary { + display: block; + position: static; + margin: 0; + padding: 0; + font-weight: inherit; + background: none; + border: 0; + border-radius: 0; + cursor: pointer; +} + +.md-typeset .fkg details > summary::after { + display: none; +} + +.md-typeset .fkg details > summary::before { + content: "\25B8"; + position: static; + display: inline-block; + width: 1em; + height: auto; + margin: 0; + background: none; + -webkit-mask-image: none; + mask-image: none; + transform: none; + color: var(--fkg-muted); +} + +.md-typeset .fkg details[open] > summary::before { + content: "\25BE"; +} + +/* ---------- fields ---------- */ + +.fkg fieldset { + margin: 0; + padding: 0; + border: 0; + min-width: 0; +} + +.fkg legend, +.fkg .fkg-field > label { + display: block; + padding: 0; + margin: 0 0 0.35em; + font-weight: 700; + color: var(--md-default-fg-color); +} + +.fkg .fkg-field + .fkg-field, +.fkg .fkg-group + .fkg-group, +.fkg .fkg-group .fkg-field + .fkg-multi, +.fkg .fkg-group .fkg-multi + .fkg-field, +.fkg .fkg-group .fkg-multi + .fkg-multi { + margin-top: 1rem; +} + +.fkg input[type="text"], +.fkg input[type="email"], +.fkg select, +.fkg textarea { + display: block; + width: 100%; + max-width: 32rem; + min-height: 2.25rem; + padding: 0.4em 0.6em; + font: inherit; + font-size: 0.8rem; + color: var(--md-default-fg-color); + background-color: var(--md-default-bg-color); + border: 1px solid var(--md-default-fg-color--lighter); + border-radius: var(--fkg-radius); +} + +.fkg textarea { + resize: vertical; +} + +.fkg input:focus-visible, +.fkg select:focus-visible, +.fkg textarea:focus-visible, +.fkg button:focus-visible, +.fkg summary:focus-visible, +.fkg a:focus-visible, +.fkg [tabindex="-1"]:focus-visible { + outline: 2px solid var(--md-accent-fg-color); + outline-offset: 2px; +} + +.fkg [aria-invalid="true"]:not(fieldset) { + border-color: var(--fkg-error); + border-width: 2px; +} + +.fkg .fkg-help { + margin: 0.35em 0 0; + font-size: 0.7rem; + line-height: 1.6; + color: var(--fkg-muted); +} + +.fkg .fkg-help-line { + display: block; +} + +.fkg .fkg-summary:empty { + display: none; +} + +.fkg .fkg-summary { + color: var(--md-default-fg-color); +} + +.fkg .fkg-error { + margin: 0.35em 0 0; + font-size: 0.75rem; + font-weight: 700; + line-height: 1.5; + color: var(--fkg-error); +} + +.fkg .fkg-error::before { + content: "\2715\00A0"; +} + +.fkg .fkg-hint { + display: block; + margin-top: 0.25em; + font-weight: 700; + color: var(--md-default-fg-color); +} + +/* ---------- level cards ---------- */ + +.fkg .fkg-cards { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(min(100%, 13rem), 1fr)); + gap: 0.6rem; + margin-top: 0.6rem; +} + +.fkg .fkg-card { + position: relative; + display: flex; + gap: 0.6rem; + align-items: flex-start; + min-height: 100%; + padding: 0.7rem 0.8rem; + cursor: pointer; + border: 1px solid var(--md-default-fg-color--lighter); + border-radius: var(--fkg-radius); + background-color: var(--md-default-bg-color); +} + +.fkg .fkg-card:hover { + border-color: var(--md-accent-fg-color); +} + +.fkg .fkg-card input { + flex: none; + width: 1.1rem; + height: 1.1rem; + margin: 0.15rem 0 0; + accent-color: var(--md-primary-fg-color); +} + +.fkg .fkg-card:has(input:checked) { + border-color: var(--md-primary-fg-color); + box-shadow: inset 0 0 0 1px var(--md-primary-fg-color); +} + +.fkg .fkg-card:has(input:focus-visible) { + outline: 2px solid var(--md-accent-fg-color); + outline-offset: 2px; +} + +.fkg .fkg-card-step { + flex: none; + display: inline-grid; + place-items: center; + width: 1.4rem; + height: 1.4rem; + font-size: 0.65rem; + font-weight: 700; + border-radius: 50%; + color: var(--md-default-bg-color); + background-color: var(--md-default-fg-color--light); +} + +.fkg .fkg-card:has(input:checked) .fkg-card-step { + background-color: var(--md-primary-fg-color); + color: var(--md-primary-bg-color); +} + +.fkg .fkg-card-body { + display: flex; + flex-direction: column; + gap: 0.2rem; + min-width: 0; +} + +.fkg .fkg-card-title { + font-weight: 700; +} + +.fkg .fkg-card-desc { + font-size: 0.7rem; + line-height: 1.5; + color: var(--fkg-muted); +} + +/* ---------- customise ---------- */ + +.md-typeset .fkg .fkg-customise { + border: 1px solid var(--fkg-border); + border-radius: var(--fkg-radius); + padding: 0 0.9rem; +} + +.md-typeset .fkg .fkg-customise[open] { + padding-bottom: 1rem; +} + +.md-typeset .fkg .fkg-customise > summary { + min-height: 2.5rem; + padding: 0.6rem 0; + font-weight: 700; +} + +.fkg .fkg-group { + margin-top: 1.2rem; + padding-top: 1rem; + border-top: 1px solid var(--fkg-border); +} + +.fkg .fkg-group > legend { + float: left; + width: 100%; + margin-bottom: 0.8rem; + font-size: 0.85rem; +} + +.fkg .fkg-group > legend + * { + clear: both; +} + +.fkg .fkg-multi > legend { + font-weight: 700; +} + +.fkg .fkg-check { + display: flex; + gap: 0.5rem; + align-items: flex-start; + margin-top: 0.4rem; +} + +.fkg .fkg-check input { + flex: none; + width: 1.1rem; + height: 1.1rem; + margin: 0.2rem 0 0; + accent-color: var(--md-primary-fg-color); +} + +.fkg .fkg-check label { + display: flex; + flex-direction: column; + min-width: 0; + cursor: pointer; +} + +.fkg .fkg-check-desc { + font-size: 0.7rem; + line-height: 1.5; + color: var(--fkg-muted); +} + +/* ---------- message boxes ---------- */ + +.fkg .fkg-box, +.fkg .fkg-alert { + padding: 0.7rem 0.9rem; + border: 1px solid var(--fkg-border); + border-left-width: 0.25rem; + border-radius: var(--fkg-radius); + font-size: 0.75rem; + line-height: 1.6; +} + +.fkg .fkg-customise .fkg-rules { + margin-top: 1rem; +} + +.fkg .fkg-box + .fkg-box { + margin-top: 0.75rem; +} + +.fkg .fkg-box-error, +.fkg .fkg-alert { + border-left-color: var(--fkg-error); +} + +.fkg .fkg-box-note { + border-left-color: var(--md-typeset-a-color); +} + +.fkg .fkg-alert { + margin: 0 0 1.25rem; +} + +.fkg .fkg-alert:empty { + display: none; +} + +.fkg .fkg-alert p, +.fkg .fkg-box p { + margin: 0.3em 0; +} + +.fkg .fkg-box ul { + margin: 0.3em 0 0; +} + +.fkg .fkg-box-title { + font-weight: 700; +} + +.fkg .fkg-icon { + display: inline-grid; + place-items: center; + width: 1.2em; + height: 1.2em; + margin-right: 0.4em; + font-size: 0.85em; + font-weight: 700; + border-radius: 50%; + border: 1.5px solid currentColor; + vertical-align: -0.15em; +} + +.fkg .fkg-alert pre { + margin: 0.4em 0 0; + white-space: pre-wrap; +} + +/* ---------- side panels ---------- */ + +.fkg .fkg-panel { + padding: 0.8rem 0.9rem; + border: 1px solid var(--fkg-border); + border-radius: var(--fkg-radius); + transition: opacity 0.15s; +} + +.md-typeset .fkg .fkg-panel h2, +.md-typeset .fkg .fkg-result h2 { + margin: 0 0 0.5em; + font-size: 1rem; + font-weight: 700; + line-height: 1.4; +} + +.md-typeset .fkg .fkg-result h3 { + margin: 1.4em 0 0.5em; + font-size: 0.9rem; + font-weight: 700; +} + +.md-typeset .fkg .fkg-result h4 { + margin: 0 0 0.3em; + font-size: 0.8rem; +} + +.fkg.fkg-checking .fkg-panel, +.fkg .fkg-panel.fkg-stale { + opacity: 0.55; +} + +.fkg .fkg-count { + margin: 0 0 0.5em; + font-size: 0.75rem; + color: var(--fkg-muted); +} + +.fkg .fkg-tree { + font-family: var(--md-code-font-family); + font-size: 0.7rem; + line-height: 1.7; + max-height: 22rem; + overflow: auto; +} + +.md-typeset .fkg .fkg-tree ul { + list-style: none; + margin: 0 0 0 1.1em; + padding: 0; +} + +.md-typeset .fkg .fkg-tree ul.fkg-tree-root { + margin-left: 0; +} + +.md-typeset .fkg .fkg-tree li { + margin: 0; +} + +.fkg .fkg-tree summary { + cursor: pointer; + min-height: 1.5rem; +} + +.fkg .fkg-dir { + font-weight: 700; +} + +.fkg .fkg-badge { + display: inline-block; + padding: 0 0.4em; + font-family: var(--md-text-font-family); + font-size: 0.6rem; + border: 1px solid var(--md-default-fg-color--lighter); + border-radius: 0.2rem; + color: var(--fkg-muted); +} + +.md-typeset .fkg pre.fkg-command, +.md-typeset .fkg pre.fkg-step-code { + margin: 0.3em 0 0; +} + +.md-typeset .fkg pre.fkg-command > code, +.md-typeset .fkg pre.fkg-step-code > code { + white-space: pre-wrap; + overflow-wrap: anywhere; + padding: 0.6em 0.8em; +} + +.fkg .fkg-copy-status { + font-size: 0.7rem; + color: var(--fkg-muted); +} + +/* ---------- buttons ---------- */ + +.md-typeset .fkg .md-button { + min-height: 2.25rem; + margin: 0; + padding: 0.45em 1.1em; + font-size: 0.75rem; + cursor: pointer; +} + +.md-typeset .fkg .fkg-generate { + display: inline-flex; + align-items: center; + gap: 0.5em; + font-size: 0.85rem; +} + +.md-typeset .fkg .fkg-generate[aria-disabled="true"] { + opacity: 0.6; + cursor: not-allowed; +} + +.fkg .fkg-privacy { + margin-top: 0.75rem; +} + +/* ---------- status line and spinner ---------- */ + +.fkg .fkg-status { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 0.2rem 0.5rem; + margin: 0 0 1rem; + font-size: 0.75rem; + color: var(--fkg-muted); +} + +.fkg .fkg-status-text { + font-weight: 700; + color: var(--md-default-fg-color); +} + +.fkg .fkg-spinner { + display: none; + flex: none; + width: 0.9em; + height: 0.9em; + border: 2px solid var(--md-default-fg-color--lighter); + border-top-color: var(--md-primary-fg-color); + border-radius: 50%; + animation: fkg-spin 0.8s linear infinite; + align-self: center; +} + +.fkg[data-fkg-state="starting"] .fkg-status .fkg-spinner, +.fkg .fkg-generate.fkg-busy .fkg-button-spinner { + display: inline-block; +} + +.fkg .fkg-generate .fkg-button-spinner { + border-color: currentColor; + border-top-color: transparent; +} + +@keyframes fkg-spin { + to { + transform: rotate(360deg); + } +} + +@media (prefers-reduced-motion: reduce) { + .fkg .fkg-spinner { + animation: none; + border-top-color: var(--md-default-fg-color--lighter); + } + + .fkg .fkg-panel { + transition: none; + } +} + +/* ---------- result ---------- */ + +.fkg .fkg-result { + margin-top: 2rem; + padding: 1rem 1.1rem; + border: 1px solid var(--md-primary-fg-color); + border-radius: var(--fkg-radius); +} + +.fkg .fkg-done { + margin: 0; + font-weight: 700; +} + +.fkg .fkg-os { + display: flex; + flex-wrap: wrap; + gap: 0.25rem 1rem; + align-items: center; + margin: 0.4rem 0 0.6rem; + font-size: 0.75rem; +} + +.fkg .fkg-os > legend { + float: left; + margin: 0 0.5rem 0 0; +} + +.fkg .fkg-os-option { + display: inline-flex; + gap: 0.35rem; + align-items: center; + min-height: 1.5rem; +} + +.fkg .fkg-os-option input { + width: 1rem; + height: 1rem; + margin: 0; + accent-color: var(--md-primary-fg-color); +} + +.md-typeset .fkg .fkg-step-list > li { + margin-bottom: 0.8em; +} + +.md-typeset .fkg .fkg-step-list p { + margin: 0 0 0.3em; +} + +.fkg .fkg-feature { + padding: 0.7rem 0; + border-top: 1px solid var(--fkg-border); +} + +.md-typeset .fkg .fkg-feature dl { + display: grid; + grid-template-columns: max-content minmax(0, 1fr); + gap: 0.2em 0.8em; + margin: 0.4em 0; + font-size: 0.75rem; +} + +.md-typeset .fkg .fkg-feature dd { + margin: 0; +} + +.fkg .fkg-messages { + margin-top: 1rem; + font-size: 0.75rem; +} + +.fkg .fkg-footer { + margin-top: 1.5rem; + font-size: 0.65rem; + color: var(--fkg-muted); +} + +@media screen and (max-width: 30em) { + .fkg .fkg-customise { + padding: 0 0.6rem; + } + + .md-typeset .fkg .fkg-feature dl { + grid-template-columns: minmax(0, 1fr); + } +} diff --git a/docs/de/contributing/code-guidelines.md b/docs/de/contributing/code-guidelines.md deleted file mode 100644 index 3473bf1c..00000000 --- a/docs/de/contributing/code-guidelines.md +++ /dev/null @@ -1,748 +0,0 @@ -# Code-Richtlinien - -Umfassende Coding-Standards und Best Practices für Beiträge zu FastAPI-fastkit. - -## Überblick - -Diese Richtlinien sorgen für Code-Qualität, Konsistenz und Wartbarkeit im gesamten FastAPI-fastkit-Projekt. Wenn Sie ihnen folgen, entsteht eine Codebasis, die leicht zu lesen, zu pflegen und zu erweitern ist. - -## Python-Codestil - -### PEP-8-Konformität - -Folgen Sie [PEP 8](https://www.python.org/dev/peps/pep-0008/) mit diesen spezifischen Einstellungen: - -- **Zeilenlänge**: 88 Zeichen (Black-Standard) -- **Einrückung**: 4 Leerzeichen (keine Tabs) -- **Nachgestellte Kommas**: in mehrzeiligen Strukturen erforderlich -- **Anführungszeichen**: doppelte Anführungszeichen bevorzugt - -### Code-Formatierung - -Wir verwenden **Black** für automatische Code-Formatierung: - -```python -# Gut ✅ -def create_project( - name: str, - template: str, - options: Dict[str, Any], -) -> ProjectResult: - """Create a new FastAPI project.""" - return ProjectResult(name=name, template=template) - -# Nicht gut ❌ -def create_project(name: str, template: str, options: Dict[str,Any])->ProjectResult: - """Create a new FastAPI project.""" - return ProjectResult(name=name,template=template) -``` - -### Import-Organisation - -Verwenden Sie **isort**, um Imports zu organisieren: - -```python -# Standard library imports -import os -import sys -from pathlib import Path -from typing import Dict, List, Optional, Union - -# Third-party imports -import click -import pydantic -from fastapi import FastAPI - -# Local imports -from fastapi_fastkit.commands import BaseCommand -from fastapi_fastkit.utils import validation -from fastapi_fastkit.templates.manager import TemplateManager -``` - -## Type Hints - -### Erforderliche Type Hints - -Alle öffentlichen Funktionen und Methoden müssen Type Hints enthalten: - -```python -# Gut ✅ -def validate_project_name(name: str) -> bool: - """Validate project name format.""" - return name.isidentifier() and not name.startswith('_') - -def create_files( - files: List[Path], - template_data: Dict[str, Any] -) -> List[Path]: - """Create files from template data.""" - created_files = [] - for file_path in files: - # Implementation... - created_files.append(file_path) - return created_files - -# Nicht gut ❌ -def validate_project_name(name): - return name.isidentifier() and not name.startswith('_') -``` - -### Komplexe Type-Annotationen - -Verwenden Sie passende Annotationen für komplexe Strukturen: - -```python -from typing import Dict, List, Optional, Union, Tuple, Any -from pathlib import Path - -# Type aliases for complex types -ProjectConfig = Dict[str, Union[str, bool, List[str]]] -FileMapping = Dict[Path, str] -ValidationResult = Tuple[bool, Optional[str]] - -def process_template( - template_path: Path, - config: ProjectConfig, - output_dir: Optional[Path] = None, -) -> ValidationResult: - """Process template with configuration.""" - # Implementation... - return True, None -``` - -## Namenskonventionen - -### Variablen und Funktionen - -- **snake_case** für Variablen und Funktionen -- **Aussagekräftige Namen**, die den Zweck erklären -- **Abkürzungen vermeiden**, sofern nicht gängig - -```python -# Gut ✅ -project_name = "my-api" -template_directory = Path("templates") -user_input_data = get_user_input() - -def validate_email_address(email: str) -> bool: - """Validate email address format.""" - return "@" in email and "." in email - -# Nicht gut ❌ -proj_nm = "my-api" -temp_dir = Path("templates") -usr_data = get_input() - -def validate_email(e): - return "@" in e and "." in e -``` - -### Klassen - -- **PascalCase** für Klassennamen -- **Beschreibende und spezifische** Namen - -```python -# Gut ✅ -class SomeClass: - """Represents example class of FastAPI-fastkit.""" - pass - -class SomeClassValidationError(Exception): - """Raised when example class validation fails.""" - pass - -class UserInputHandler: - """Handles user input validation and processing.""" - pass - -# Nicht gut ❌ -class Class: - pass - -class Error(Exception): - pass - -class Handler: - pass -``` - -### Konstanten - -- **UPPER_CASE** mit Unterstrichen -- Konstanten **nur auf Modul-Ebene** - -```python -# Gut ✅ -DEFAULT_TEMPLATE_NAME = "fastapi-default" -MAX_PROJECT_NAME_LENGTH = 50 -SUPPORTED_PYTHON_VERSIONS = ["3.8", "3.9", "3.10", "3.11", "3.12"] - -# Nicht gut ❌ -default_template = "fastapi-default" -maxLength = 50 -versions = ["3.8", "3.9", "3.10", "3.11", "3.12"] -``` - -## Dokumentations-Standards - -### Docstrings - -Verwenden Sie **Google-Style-Docstrings** für alle öffentlichen APIs: - -```python -def create_project_structure( - project_name: str, - template_path: Path, - output_directory: Optional[Path] = None, - overwrite: bool = False, -) -> List[Path]: - """Create project structure from template. - - Creates a new FastAPI project structure by copying and processing - template files. Supports variable substitution and file customization. - - Args: - project_name: Name of the project to create. Must be a valid - Python identifier. - template_path: Path to the template directory containing - source files and configuration. - output_directory: Directory where project will be created. - Defaults to current working directory. - overwrite: Whether to overwrite existing files. If False, - raises error when files exist. - - Returns: - List of created file paths in order of creation. - - Raises: - ValueError: If project_name is invalid or empty. - FileExistsError: If output directory exists and overwrite is False. - TemplateNotFoundError: If template_path doesn't exist. - PermissionError: If insufficient permissions to create files. - - Example: - ```python - template_path = Path("templates/fastapi-default") - created_files = create_project_structure( - project_name="my-api", - template_path=template_path, - output_directory=Path("./projects"), - overwrite=False - ) - print(f"Created {len(created_files)} files") - ``` - """ - # Implementation here... - pass -``` - -### Kommentare - -- **WARUM erklären, nicht WAS** -- **Sparsam einsetzen** — Code sollte selbsterklärend sein -- **Kommentare aktualisieren**, wenn sich Code ändert - -```python -# Gut ✅ -def validate_dependencies(requirements: List[str]) -> bool: - """Validate project dependencies.""" - # Skip validation in development mode to allow experimental packages - if os.getenv("FASTKIT_DEV_MODE"): - return True - - # Check each requirement against known security vulnerabilities - for requirement in requirements: - if is_vulnerable_package(requirement): - return False - - return True - -# Nicht gut ❌ -def validate_dependencies(requirements: List[str]) -> bool: - """Validate project dependencies.""" - # Check if dev mode - if os.getenv("FASTKIT_DEV_MODE"): - return True - - # Loop through requirements - for requirement in requirements: - # Check if vulnerable - if is_vulnerable_package(requirement): - return False - - # Return true - return True -``` - -## Fehlerbehandlung - -### Behandlung von Exceptions - -- **Spezifische Exceptions** soweit möglich abfangen -- **Aussagekräftige Fehlermeldungen** liefern -- **Fehler angemessen loggen** - -```python -# Gut ✅ -def load_template_config(template_path: Path) -> Dict[str, Any]: - """Load template configuration from file.""" - config_file = template_path / "template.yaml" - - try: - with open(config_file, 'r') as f: - return yaml.safe_load(f) - except FileNotFoundError: - raise TemplateNotFoundError( - f"Template configuration not found: {config_file}" - ) - except yaml.YAMLError as e: - raise TemplateConfigError( - f"Invalid YAML syntax in {config_file}: {e}" - ) - except PermissionError: - raise TemplateAccessError( - f"Permission denied reading {config_file}" - ) - -# Nicht gut ❌ -def load_template_config(template_path: Path) -> Dict[str, Any]: - """Load template configuration from file.""" - config_file = template_path / "template.yaml" - - try: - with open(config_file, 'r') as f: - return yaml.safe_load(f) - except Exception as e: - raise Exception(f"Error loading config: {e}") -``` - -### Benutzerdefinierte Exceptions - -Definieren Sie spezifische Exceptions für unterschiedliche Fehlerbedingungen: - -```python -class FastKitError(Exception): - """Base exception for FastAPI-fastkit errors.""" - pass - -class ProjectCreationError(FastKitError): - """Raised when project creation fails.""" - pass - -class TemplateNotFoundError(FastKitError): - """Raised when template is not found.""" - pass - -class ValidationError(FastKitError): - """Raised when input validation fails.""" - - def __init__(self, message: str, field: str = None): - super().__init__(message) - self.field = field -``` - -## Test-Standards - -### Teststruktur - -Organisieren Sie Tests mit klarer Struktur und klarer Benennung: - -```python -class TestProjectCreation: - """Test project creation functionality.""" - - def test_create_project_with_valid_name(self, tmp_path): - """Test project creation with valid project name.""" - project_name = "test-project" - result = create_project(project_name, template="minimal", output=tmp_path) - - assert result.success is True - assert (tmp_path / project_name).exists() - assert (tmp_path / project_name / "src" / "main.py").exists() - - def test_create_project_with_invalid_name(self): - """Test project creation fails with invalid name.""" - with pytest.raises(ValueError, match="Invalid project name"): - create_project("invalid-project-name!", template="minimal") - - def test_create_project_overwrites_existing(self, tmp_path): - """Test project creation overwrites existing directory when forced.""" - project_name = "existing-project" - project_dir = tmp_path / project_name - project_dir.mkdir() - - result = create_project( - project_name, - template="minimal", - output=tmp_path, - overwrite=True - ) - - assert result.success is True - assert project_dir.exists() -``` - -### Testabdeckung - -- **Streben Sie 90 %+ Abdeckung** bei neuem Code an -- **Grenzfälle und Fehlerbedingungen** testen -- **Externe Abhängigkeiten mocken** - -```python -def test_template_download_with_network_error(mock_requests): - """Test template download handles network errors gracefully.""" - mock_requests.get.side_effect = requests.ConnectionError("Network unreachable") - - with pytest.raises(TemplateDownloadError, match="Network error"): - download_template("https://example.com/template.zip") - -def test_file_creation_with_permission_error(mock_open): - """Test file creation handles permission errors.""" - mock_open.side_effect = PermissionError("Permission denied") - - with pytest.raises(FileCreationError, match="Permission denied"): - create_file(Path("/restricted/file.py"), content="test") -``` - -## Import-Richtlinien - -### Import-Organisation - -!!! note - - `isort` ordnet Imports automatisch — Sie können Imports einfach mit `bash scripts/format.sh` ordnen. - -1. **Standardbibliothek** zuerst -2. **Drittanbieter** als Zweites -3. **Lokale Anwendung** zuletzt -4. **Leerzeile** zwischen jeder Gruppe - -```python -# Standard library -import os -import sys -from pathlib import Path -from typing import Dict, List, Optional - -# Third-party -import click -import pydantic -import yaml -from fastapi import FastAPI - -# Local application -from fastapi_fastkit.commands.base import BaseCommand -from fastapi_fastkit.utils.validation import validate_project_name -from fastapi_fastkit.templates import TemplateManager -``` - -### Best Practices für Imports - -- **Wildcard-Imports vermeiden** (`from module import *`) -- **Absolute Imports** für Klarheit verwenden -- **Module importieren, nicht einzelne Symbole**, wenn Sie viele Symbole brauchen - -```python -# Gut ✅ -from fastapi_fastkit.utils import validation, files, formatting - -# Gut ✅ (wenn nur wenige Elemente importiert werden) -from fastapi_fastkit.utils.validation import validate_email, validate_project_name - -# Nicht gut ❌ -from fastapi_fastkit.utils.validation import * - -# Nicht gut ❌ (wenn viele Elemente importiert werden) -from fastapi_fastkit.utils.validation import ( - validate_email, validate_project_name, validate_template_name, - validate_dependencies, validate_python_version, validate_directory -) -``` - -## Sicherheitsrichtlinien - -### Eingabevalidierung - -Nutzereingaben immer validieren und säubern: - -```python -def validate_project_name(name: str) -> str: - """Projektname validieren und bereinigen.""" - if not name: - raise ValueError("Project name cannot be empty") - - if not name.isidentifier(): - raise ValueError("Project name must be a valid Python identifier") - - if name.startswith('_'): - raise ValueError("Project name cannot start with underscore") - - if len(name) > 50: - raise ValueError("Project name too long (max 50 characters)") - - # Potenziell problematische Zeichen entfernen - sanitized = re.sub(r'[^a-zA-Z0-9_-]', '', name) - - return sanitized -``` - -### Dateioperationen - -Seien Sie vorsichtig mit Dateipfaden und -operationen: - -```python -def create_file_safely(file_path: Path, content: str, base_dir: Path) -> None: - """Datei sicher innerhalb des Basisverzeichnisses anlegen.""" - # Pfad auflösen, um Directory-Traversal-Angriffe zu verhindern - resolved_path = file_path.resolve() - resolved_base = base_dir.resolve() - - # Sicherstellen, dass die Datei innerhalb des Basisverzeichnisses liegt - try: - resolved_path.relative_to(resolved_base) - except ValueError: - raise SecurityError(f"File path outside base directory: {file_path}") - - # Übergeordnete Verzeichnisse sicher anlegen - resolved_path.parent.mkdir(parents=True, exist_ok=True) - - # Datei mit passenden Berechtigungen schreiben - resolved_path.write_text(content, encoding='utf-8') - resolved_path.chmod(0o644) # Besitzer: lesen/schreiben, andere: nur lesen -``` - -## Performance-Richtlinien - -### Effiziente Code-Praktiken - -- **Generatoren** für große Datenmengen verwenden -- **Vorzeitige Optimierung vermeiden** -- **Vor dem Optimieren profilen** - -```python -# Gut ✅ - Generator spart Arbeitsspeicher -def process_large_template(template_files: List[Path]) -> Iterator[ProcessedFile]: - """Vorlagendateien effizient verarbeiten.""" - for file_path in template_files: - content = file_path.read_text() - processed_content = process_template_content(content) - yield ProcessedFile(path=file_path, content=processed_content) - -# Nicht gut ❌ - lädt alles in den Arbeitsspeicher -def process_large_template(template_files: List[Path]) -> List[ProcessedFile]: - """Vorlagendateien verarbeiten.""" - results = [] - for file_path in template_files: - content = file_path.read_text() - processed_content = process_template_content(content) - results.append(ProcessedFile(path=file_path, content=processed_content)) - return results -``` - -### Caching - -Cache für teure Operationen nutzen: - -```python -from functools import lru_cache - -@lru_cache(maxsize=128) -def get_template_metadata(template_path: Path) -> TemplateMetadata: - """Get template metadata with caching.""" - config_file = template_path / "template.yaml" - - if not config_file.exists(): - return TemplateMetadata(name=template_path.name) - - config = yaml.safe_load(config_file.read_text()) - return TemplateMetadata.from_config(config) -``` - -## Git-Commit-Richtlinien - -### Format der Commit-Nachricht - -Verwenden Sie das Conventional-Commit-Format: - -``` -type(scope): description - -[optional body] - -[optional footer] -``` - -### Commit-Typen - -- **feat**: neue Funktion -- **fix**: Fehlerbehebung -- **docs**: Dokumentationsänderungen -- **style**: Code-Stil-Änderungen (Formatierung usw.) -- **refactor**: Refactoring -- **test**: Tests hinzufügen oder aktualisieren -- **chore**: Wartungsarbeiten - -### Beispiele - -```bash -# Gut ✅ -feat(cli): add template validation command - -Add new command to validate template structure and configuration. -The command checks for required files, validates YAML syntax, -and ensures template follows conventions. - -Closes #123 - -# Gut ✅ -fix(templates): handle missing dependency files gracefully - -When a template references a requirements file that doesn't exist, -show a clear error message instead of crashing. - -# Nicht gut ❌ -update stuff - -# Nicht gut ❌ -Fixed bug -``` - -## Code-Review-Richtlinien - -### Für Autoren - -Vor dem Einreichen zur Review: - -1. **Alle Tests ausführen** und sicherstellen, dass sie bestehen -2. **Code-Abdeckung prüfen**, damit sie erhalten bleibt -3. **Dokumentation aktualisieren**, falls nötig -4. **Commit-Konventionen befolgen** -5. **Pull-Requests** fokussiert und klein halten - -### Für Reviewer - -Beim Review: - -1. **Funktionsfähigkeit prüfen** — funktioniert es wie beabsichtigt? -2. **Tests überprüfen** — sind Grenzfälle abgedeckt? -3. **Dokumentation verifizieren** — klar und aktuell? -4. **Codestil prüfen** — folgt er den Projekt-Konventionen? -5. **Sicherheit beachten** — potenzielle Schwachstellen? - -### Review-Checkliste - -- [ ] Code folgt den Style-Richtlinien -- [ ] Tests sind umfassend und bestehen -- [ ] Dokumentation ist aktuell -- [ ] Keine Sicherheitslücken -- [ ] Performance-Überlegungen berücksichtigt -- [ ] Fehlerbehandlung ist angemessen -- [ ] Commit-Nachrichten folgen den Konventionen - -## Werkzeuge und Automatisierung - -### Pre-Commit-Hooks - -Wir nutzen Pre-Commit-Hooks zur Durchsetzung der Standards: - -```yaml -# .pre-commit-config.yaml -repos: -- repo: https://github.com/pre-commit/pre-commit-hooks - rev: v6.0.0 - hooks: - - id: trailing-whitespace - - id: end-of-file-fixer - - id: check-yaml - - id: check-toml - -- repo: local - hooks: - - id: format - name: format - entry: black --config pyproject.toml --check . - language: python - types: [python] - additional_dependencies: ['black>=24.10.0'] - pass_filenames: false - - - id: isort-check - name: isort check - entry: isort --sp pyproject.toml --check-only --diff . - language: python - types: [python] - additional_dependencies: ['isort>=5.13.2'] - pass_filenames: false - - - id: isort-fix - name: isort fix - entry: isort --sp pyproject.toml . - language: python - types: [python] - additional_dependencies: ['isort>=5.13.2'] - pass_filenames: false - - - id: black-fix - name: black fix - entry: black --config pyproject.toml . - language: python - types: [python] - additional_dependencies: ['black>=24.10.0'] - pass_filenames: false - - - id: mypy - name: mypy - entry: mypy --config-file pyproject.toml src - language: python - types: [python] - additional_dependencies: - - mypy>=1.12.0 - - rich>=13.9.2 - - click>=8.1.7 - - pyyaml>=6.0.0 - - types-PyYAML>=6.0.12 - pass_filenames: false - -ci: - autofix_commit_msg: 🎨 [pre-commit.ci] Auto format from pre-commit.com hooks - autoupdate_commit_msg: ⬆ [pre-commit.ci] pre-commit autoupdate -``` - -!!! note - - Pre-Commit-Hooks verwenden isolierte Python-Umgebungen (`language: python`). - -### IDE-Konfiguration - -Empfohlene VS-Code-Einstellungen: - -```json -{ - "python.linting.enabled": true, - "python.linting.mypyEnabled": true, - "python.formatting.provider": "black", - "python.sortImports.path": "isort", - "editor.formatOnSave": true, - "editor.codeActionsOnSave": { - "source.organizeImports": true - } -} -``` - -## Nächste Schritte - -Nachdem Sie diese Richtlinien gelesen haben: - -1. **Entwicklungsumgebung einrichten** gemäß [Entwicklungsumgebung einrichten](development-setup.md) -2. **Mit kleinen Beiträgen üben**, um sich vertraut zu machen -3. **Fragen stellen** in GitHub Discussions, falls etwas unklar ist -4. **Vorhandenen Code lesen**, um diese Richtlinien in der Praxis zu sehen - -!!! tip "Schnelle Referenz" - - Verwenden Sie `make check-all`, um zu prüfen, ob Ihr Code allen Richtlinien folgt - - Richten Sie Pre-Commit-Hooks ein, um Probleme früh zu erkennen - - Im Zweifel: Beispiele im bestehenden Code anschauen - - Zögern Sie nicht, in Code-Reviews um Hilfe zu bitten - -Diese Richtlinien zu befolgen hilft, die hohe Code-Qualität von FastAPI-fastkit zu erhalten und macht die Zusammenarbeit für alle einfacher! 🚀 diff --git a/docs/de/contributing/development-setup.md b/docs/de/contributing/development-setup.md index 9f63f89d..90f1e1dd 100644 --- a/docs/de/contributing/development-setup.md +++ b/docs/de/contributing/development-setup.md @@ -1,840 +1,161 @@ # Entwicklungsumgebung einrichten -Ein umfassender Leitfaden zum Einrichten einer Entwicklungsumgebung für Beiträge zu FastAPI-fastkit. +Diese Seite zeigt, wie du das Repository von FastAPI-fastkit einrichtest, seine Tests und Prüfungen ausführst, seine Coderegeln einhältst, die Dokumentation mit dem Web-Generator baust und ein Release vorbereitest. Wie Pull Requests ablaufen, beschreibt `CONTRIBUTING.md` im Repository. ## Voraussetzungen -Bevor Sie starten, stellen Sie sicher, dass Sie haben: +- Python 3.12 oder neuer (`requires-python = ">=3.12"`). +- git. +- PDM, das die CI-Workflows verwenden, oder uv. pip funktioniert ebenfalls. +- Node.js (die CI verwendet Version 22), nur um den Web-Generator mit der Kommandozeile zu vergleichen. -- **Python 3.12 oder höher** installiert -- **Git** installiert und konfiguriert -- **Grundkenntnisse** in Python und FastAPI -- **Einen Texteditor oder eine IDE** (VS Code, PyCharm usw.) +## Installieren -## Schnelles Setup mit Makefile - -FastAPI-fastkit bietet ein Makefile für einfaches Entwicklungs-Setup: - -
+Klone das Repository und installiere fastkit im Editable-Modus zusammen mit den Entwicklerwerkzeugen: ```console $ git clone https://github.com/bnbong/FastAPI-fastkit.git $ cd FastAPI-fastkit -$ make install-dev -Setting up development environment... -Creating virtual environment... -Installing dependencies... -Installing pre-commit hooks... -✅ Development environment ready! -``` - -
- -Dieser einzelne Befehl: - -- Installiert das Paket im Editable-Modus mit Dev-Abhängigkeiten -- Richtet Pre-Commit-Hooks ein -- Konfiguriert Entwicklungstools - -!!! note - - Sie sollten eine virtuelle Umgebung erstellen und aktivieren, bevor Sie diesen Befehl ausführen. - -## Manuelles Setup - -Wenn Sie ein manuelles Setup bevorzugen oder das Makefile auf Ihrem System nicht funktioniert: - -### 1. Repository klonen - -
- -```console -$ git clone https://github.com/bnbong/FastAPI-fastkit.git -$ cd FastAPI-fastkit -``` - -
- -### 2. Virtuelle Umgebung erstellen - -
- -```console -$ python -m venv .venv -$ source .venv/bin/activate # On Windows: .venv\Scripts\activate -``` - -
- -### 3. Abhängigkeiten installieren - -
- -```console -# Install package in editable mode with development dependencies -$ pip install -e ".[dev]" - -# Or install from requirements files -$ pip install -r requirements.txt -$ pip install -r requirements-dev.txt +$ pdm install -G dev -G test-runtime +$ pdm run pre-commit install ``` -
+Mit uv führst du `uv sync --extra dev --group test-runtime` aus. Mit pip erstellst und aktivierst du eine virtuelle Umgebung und führst dann `make dev-setup` aus: Das Target aktualisiert pip, installiert fastkit mit `pip install -e ".[dev]"`, installiert die Abhängigkeiten der Dokumentation aus `requirements-docs.txt` und führt `pre-commit install` aus. Für die Laufzeittests kommt `pip install --group test-runtime` hinzu (pip 25.1 oder neuer). -### 4. Pre-Commit-Hooks einrichten +Die Entwicklerwerkzeuge haben in `pyproject.toml` und in beiden Lockdateien dieselben Versionen: black 26.10.1, isort 9.0.1, mypy 2.3.1 und ruff 0.17.6. Die pre-commit-Hooks pinnen black, isort und mypy auf dieselben Versionen. Nach einem Pull bringst du deine Umgebung mit `pdm sync -G dev --clean` (oder `uv sync --extra dev`) auf diesen Stand. -
+Die Tests, die erzeugte Anwendungen starten, brauchen FastAPI und einige weitere Pakete. Diese stellt die Abhängigkeitsgruppe `test-runtime` bereit; ohne sie werden diese Tests übersprungen. Die CI installiert die Gruppe mit `pdm install -G dev -G test-runtime`, und lokal kannst du `pdm sync -G dev -G test-runtime --clean`, `uv sync --extra dev --group test-runtime` oder `pip install --group test-runtime` (pip 25.1 oder neuer) verwenden. -```console -$ pre-commit install -pre-commit installed at .git/hooks/pre-commit -``` - -
- -### 5. Installation überprüfen +## Die Tests ausführen -
+`pytest` führt vom Wurzelverzeichnis des Repositorys aus die ganze Testsuite aus (`testpaths = ["tests"]`). Mit `extended` markierte Tests sind langsamere End-to-End-Tests; lass sie weg, solange du an einer Änderung arbeitest: ```console -$ fastkit --version -fastapi-fastkit, version 1.2.1 - -$ python -m pytest tests/ -======================== test session starts ======================== -collected 45 items -tests/test_cli.py::test_init_command PASSED -tests/test_templates.py::test_template_listing PASSED -... -======================== 45 passed in 2.34s ======================== +$ pdm run pytest -m "not extended" +$ pdm run pytest tests/test_docs -q ``` -
- -## Entwicklungstools - -Die Entwicklungsumgebung enthält mehrere Tools zur Code-Qualität: - -### Einzeilen-Befehle +`make test` führt `pytest` aus, und `make test-coverage` führt es mit Messung der Testabdeckung aus (`--cov-fail-under=80`) und schreibt `htmlcov/` und `coverage.xml`. Der Workflow „Test and Coverage“ führt die Testsuite unter Ubuntu mit Python 3.12, 3.13 und 3.14 und unter Windows mit Python 3.12 und 3.14 aus. Ein zweiter Job führt sie so aus, dass implizite Textkodierungen zu Fehlern werden, und noch einmal unter einer C-Locale ohne UTF-8. -mit Makefile: +## Prüfungen ```console -$ make format lint -Running isort... -Running black... -Running mypy... -✅ All checks passed! -``` - -mit den mitgelieferten Skripten: - -```console -$ ./scripts/format.sh -$ ./scripts/lint.sh -``` - -### Code-Formatierung - -**Black** — Code-Formatter: - -
- -```console -$ black src/ tests/ -reformatted src/main.py -reformatted tests/test_cli.py +$ make lint +Running isort check... +isort --sp pyproject.toml --check . +Skipped 5 files +Running black check... +black --config pyproject.toml --check . All done! ✨ 🍰 ✨ +253 files would be left unchanged. +Running mypy check... +mypy --config-file pyproject.toml src +Success: no issues found in 98 source files ``` -
- -**isort** — Import-Sortierer: - -
- -```console -$ isort src/ tests/ -Fixing import order in src/main.py -``` - -
- -### Code-Linting - -**mypy** — Typprüfung: - -
- -```console -$ mypy src/ -Success: no issues found in 12 source files -``` - -
- -## Verfügbare Make-Befehle - -Das Projekt-Makefile bietet praktische Befehle für gängige Entwicklungsaufgaben: - -### Setup-Befehle - -| Befehl | Beschreibung | -|---------|-------------| -| `make install` | Paket im Produktionsmodus installieren | -| `make install-dev` | Paket mit Dev-Abhängigkeiten installieren | -| `make install-test` | Paket für Tests installieren (deinstallieren + neu installieren) | -| `make uninstall` | Paket deinstallieren | -| `make clean` | Build-Artefakte und Cache-Dateien löschen | - -### Befehle zur Code-Qualität - -| Befehl | Beschreibung | -|---------|-------------| -| `make format` | Code mit black und isort formatieren | -| `make format-check` | Formatierung prüfen, ohne Änderungen vorzunehmen | -| `make lint` | Alle Linting-Prüfungen ausführen (isort, black, mypy) | - -### Test-Befehle - -| Befehl | Beschreibung | -|---------|-------------| -| `make test` | Alle Tests ausführen | -| `make test-verbose` | Tests mit ausführlicher Ausgabe ausführen | -| `make test-coverage` | Tests mit Coverage-Bericht ausführen | -| `make coverage-report` | Detaillierten Coverage-Bericht erzeugen (FORMAT=html/xml/json/all) | - -### Befehle zur Vorlagen-Inspektion - -| Befehl | Beschreibung | -|---------|-------------| -| `make inspect-templates` | Alle Vorlagen inspizieren | -| `make inspect-templates-verbose` | Mit ausführlicher Ausgabe inspizieren | -| `make inspect-template` | Eine oder mehrere Vorlagen inspizieren (Parameter TEMPLATES) | - -Das zugrunde liegende Skript kennt drei Flags, die beim Iterieren nützlich sind: `--offline` (überspringt die PyPI-Aktualitätsabfragen), `--no-smoke` (überspringt das Starten des generierten Projekts mit uvicorn — der langsamste Schritt) und `--mypy` (Typprüfung des generierten Projekts; optional, weil sie langsam ist). Was jede Prüfung genau tut, beschreibt [Qualitätssicherung der Vorlagen](../reference/template-quality-assurance.md). - -```console -$ python scripts/inspect-templates.py --templates fastapi-sqlmodel --offline --no-smoke -``` - -### Generierter Code liegt in Jinja2-Fragmenten - -Alles, was `fastkit init --interactive` in ein Projekt schreibt — `main.py`, Datenbank- und Auth-Module, Docker-Dateien, die pytest-Konfiguration — wird aus Vorlagen unter `src/fastapi_fastkit/fragments/` gerendert und nicht in Python aus Strings zusammengesetzt. `main.py.j2` codiert keine Funktion fest: Es iteriert über die Listen `import_fragments`, `lifespan_fragments` und `setup_fragments`, die `DynamicConfigGenerator` liefert, und bindet jedes Fragment ein, sodass sich Funktionen frei kombinieren lassen. - -Eine Funktion hinzuzufügen, sieht ungefähr so aus: - -1. Legen Sie die Bausteine in `main/imports/`, `main/lifespan/` und/oder `main/setup/` ab (Lifespan-Fragmente sind um vier Leerzeichen eingerückt, die anderen beiden nicht). -2. Registrieren Sie sie in `DynamicConfigGenerator._main_fragments()`, abgesichert durch die passende Konfigurationsabfrage. -3. Für ein eigenständiges Modul fügen Sie `/.py.j2` hinzu und rendern es mit `self._render(...)`. -4. Erweitern Sie die Kombinationsmatrix in `tests/test_backends/test_project_builder_config_generator.py` — sie prüft, dass sich jede gerenderte Python-Datei mit `ast.parse` parsen lässt. - -Zwei Einschränkungen, über die man leicht stolpert: Jedes Fragment muss mit einem abschließenden Zeilenumbruch enden (die Umgebung wird mit `keep_trailing_newline=True` erstellt), und `main.py.j2` muss seine Anker `# fastkit:imports` / `# fastkit:routes` behalten — `fastkit addroute` fügt an ihnen ein. - -Das maßgebliche Vorgehen ist direkt neben den Fragmenten dokumentiert, in [`src/fastapi_fastkit/fragments/README.md`](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fragments/README.md). - -### Dokumentations-Befehle - -| Befehl | Beschreibung | -|---------|-------------| -| `make serve-docs` | Dokumentation lokal bereitstellen | -| `make build-docs` | Dokumentation bauen | - -### Übersetzungs-Befehle - -| Befehl | Beschreibung | -|---------|-----------| -| `make translate` | Dokumentation übersetzen (Parameter LANG, PROVIDER, MODEL) | - -### Beispiele - -
- -```console -# Format code and run all checks -$ make format lint -Running isort... -Running black... -Running mypy... -✅ All checks passed! - -# Run tests with coverage -$ make test-coverage -======================== test session starts ======================== -collected 45 items -tests/test_cli.py::test_init_command PASSED -... -======================== 45 passed in 2.34s ======================== - ----------- coverage: platform darwin, python 3.12.1-final-0 ---------- -Name Stmts Miss Cover --------------------------------------------- -src/main.py 45 2 96% -src/cli.py 89 5 94% -src/templates.py 67 3 96% --------------------------------------------- -TOTAL 201 10 95% - -# Generate HTML coverage report -$ make coverage-report FORMAT=html -🌐 Opening HTML coverage report in browser... - -# Translate documentation to Korean -$ make translate LANG=ko PROVIDER=github MODEL=gpt-4o-mini -Starting translation... -Running: python scripts/translate.py --target-lang ko --api-provider github --model gpt-4o-mini -``` - -
- -## Projektstruktur - -Die Projektstruktur zu verstehen, ist für die Entwicklung entscheidend: - -```bash -FastAPI-fastkit/ -├── src/ -│ ├── fastapi_fastkit/ -│ │ ├── __main__.py # Entry point of the application -│ │ ├── backend/ -│ │ │ ├── inspector.py # FastAPI-fastkit template inspector -│ │ │ ├── interactive/ -│ │ │ │ ├── config_builder.py # Configuration builder for interactive mode -│ │ │ │ ├── prompts.py # Prompts for interactive mode -│ │ │ │ ├── selectors.py # Selectors logic for interactive mode -│ │ │ │ └── validators.py # User input validators for interactive mode -│ │ │ ├── main.py # Backend's logic entry point -│ │ │ ├── package_managers/ -│ │ │ │ ├── base.py # Base class for package managers -│ │ │ │ ├── factory.py # Factory for package managers -│ │ │ │ ├── pdm_manager.py # PDM package manager -│ │ │ │ ├── pip_manager.py # pip package manager -│ │ │ │ ├── poetry_manager.py # Poetry package manager -│ │ │ │ └── uv_manager.py # uv package manager -│ │ │ ├── project_builder/ -│ │ │ │ ├── config_generator.py # Configuration generator for project builder -│ │ │ │ └── dependency_collector.py # Dependency collector for project builder -│ │ │ └── transducer.py # Transducer for project builder -│ │ ├── cli.py # FastAPI-fastkit main CLI entry point -│ │ ├── core/ -│ │ │ ├── exceptions.py # Exception handling -│ │ │ └── settings.py # Settings configuration -│ │ ├── fastapi_project_template/ -│ │ │ ├── PROJECT_README_TEMPLATE.md # fastkit template project base README file -│ │ │ ├── README.md # fastkit template README -│ │ │ ├── fastapi-async-crud/ -│ │ │ ├── fastapi-custom-response/ -│ │ │ ├── fastapi-default/ -│ │ │ ├── fastapi-dockerized/ -│ │ │ ├── fastapi-empty/ -│ │ │ ├── fastapi-mcp/ -│ │ │ ├── fastapi-psql-orm/ -│ │ │ ├── fastapi-single-module/ -│ │ │ └── modules/ -│ │ │ ├── api/ -│ │ │ │ └── routes/ -│ │ │ ├── crud/ -│ │ │ └── schemas/ -│ │ ├── py.typed -│ │ └── utils/ -│ │ ├── logging.py # Logging configuration -│ │ └── main.py # FastAPI-fastkit main entry point -│ └── logs -├── tests -│ ├── conftest.py # pytest configuration -│ ├── test_backends/ -│ ├── test_cli_operations/ -│ ├── test_core.py -│ ├── test_rich/ -│ ├── test_templates/ -│ └── test_utils.py -├── uv.lock -├── docs/ # Documentation -├── scripts/ # Development scripts -├── mkdocs.yml -├── overrides/ # mkdocs overrides -├── pdm.lock -├── pyproject.toml -├── requirements-docs.txt # requirements for documentation -├── requirements.txt # requirements for development -├── CHANGELOG.md -├── CITATION.cff -├── CODE_OF_CONDUCT.md -├── CONTRIBUTING.md -├── LICENSE -├── MANIFEST.in -├── Makefile -├── README.md -├── SECURITY.md -└── env.example # environment example(configures translation AI model env vars) -``` - -### Wichtige Verzeichnisse - -- **`src/fastapi_fastkit/`** — Hauptquellcode des Pakets - - **`cli.py`** — Haupteinstiegspunkt des CLI - - **`backend/`** — zentrale Backend-Logik - - **`inspection/`** — Pipeline zur Vorlagen-Inspektion (context, checks, consistency, freshness, smoke, lint, report) - - **`inspector.py`** — Fassade über `inspection/`, beibehalten für den historischen Importpfad - - **`interactive/`** — Komponenten des interaktiven Modus (Prompts, Selectors, Validators) - - **`package_managers/`** — Implementierungen der Paketmanager (pip, uv, pdm, poetry) - - **`project_builder/`** — Hilfsfunktionen zum Projektbau, einschließlich des fragmentbasierten Konfigurationsgenerators - - **`scaffolder.py`** — die Generierungspipeline, die `init` und `startdemo` gemeinsam nutzen - - **`transducer.py`** — Vorlagen-Transducer - - **`core/`** — zentrale Konfiguration und Exceptions - - **`fragments/`** — Jinja2-Fragmente, die in generierte Projekte gerendert werden (siehe oben) - - **`fastapi_project_template/`** — Projektvorlagen (fastapi-default, fastapi-domain-starter usw.) - - **`utils/`** — gemeinsame Hilfsfunktionen -- **`tests/`** — Test-Suite - - **`test_backends/`** — Backend-spezifische Tests - - **`test_cli_operations/`** — Tests der CLI-Operationen - - **`test_templates/`** — Tests des Vorlagensystems -- **`docs/`** — Dokumentation (MkDocs) - - Nutzerhandbücher, Tutorials und API-Referenz - -## Entwicklungs-Workflow - -### 1. Feature-Branch erstellen - -
- -```console -$ git checkout -b feature/add-new-template -Switched to a new branch 'feature/add-new-template' -``` - -
- -### 2. Änderungen vornehmen - -Code bearbeiten, Funktionen ergänzen, Bugs beheben… - -### 3. Tests und Prüfungen ausführen - -
- -```console -$ make dev-check -Running all quality checks... -Running all tests... -✅ All tests passed! -``` - -
- -### 4. Änderungen committen - -Pre-Commit-Hooks laufen automatisch: - -
- -```console -$ git add . -$ git commit -m "Add new FastAPI template with authentication" -format...................................................................Passed -isort-check..............................................................Passed -black-fix................................................................Passed -mypy.....................................................................Passed -[feature/add-new-template abc1234] Add new FastAPI template with authentication -``` - -
- -### 5. Pushen und Pull-Request erstellen - -
- -```console -$ git push origin feature/add-new-template -$ gh pr create --title "Add new FastAPI template with authentication" -``` - -
- -## Testen - -### Tests ausführen - -**Alle Tests:** - -
- -```console -$ make test -# or -$ python -m pytest -``` - -
- -**Bestimmte Testdatei:** - -
- -```console -$ python -m pytest tests/test_cli.py -v -``` - -
- -**Mit Coverage:** - -
- -```console -$ make test-coverage -# or -$ python -m pytest --cov=src --cov-report=html -``` - -
- -### Tests schreiben - -Bei neuen Funktionen immer Tests beifügen: - -```python -# tests/test_commands/test_new_feature.py -import pytest -from fastapi_fastkit.commands.new_feature import NewFeatureCommand - -class TestNewFeatureCommand: - def test_command_success(self): - """Test successful command execution""" - command = NewFeatureCommand() - result = command.execute(valid_args) - assert result.success is True - assert result.message == "Feature executed successfully" - - def test_command_validation_error(self): - """Test command with invalid arguments""" - command = NewFeatureCommand() - with pytest.raises(ValueError, match="Invalid argument"): - command.execute(invalid_args) - - def test_command_edge_case(self): - """Test edge case handling""" - command = NewFeatureCommand() - result = command.execute(edge_case_args) - assert result.success is True - assert "warning" in result.message.lower() -``` - -### Test-Kategorien +| Befehl | Was er tut | +| --- | --- | +| `make format` | Sortiert die Importe mit isort und formatiert mit black. | +| `make format-check` | Zeigt, was `make format` ändern würde, ohne etwas zu ändern. | +| `make lint` | isort und black im Prüfmodus, danach `mypy src` (strikt). | +| `make dev-check` | `make format-check`, `make lint` und `make test`. | +| `make dev-setup` | Installiert mit pip fastkit samt Entwicklerwerkzeugen, die Abhängigkeiten der Dokumentation und die pre-commit-Hooks. | +| `make help` | Listet alle Targets auf. | -**Unit-Tests** — einzelne Funktionen und Klassen testen: +Die pre-commit-Hooks führen dieselben Befehle für isort, black und mypy aus, dazu Prüfungen auf Leerraum, Dateiende, YAML und TOML. -```python -def test_validate_project_name(): - assert validate_project_name("valid-name") is True - assert validate_project_name("invalid name!") is False -``` - -**Integrationstests** — Interaktionen zwischen Befehlen testen: - -```python -def test_init_command_creates_project(tmp_path): - result = runner.invoke(cli, ['init'], input='test-project\n...') - assert result.exit_code == 0 - assert (tmp_path / "test-project").exists() -``` +## Coderegeln -**End-to-End-Tests** — komplette Flüsse testen: +- Code unter `src/fastapi_fastkit/` (außerhalb der Templates) liest und schreibt Textdateien über `src/fastapi_fastkit/utils/textio.py`. Dieses Modul setzt UTF-8 und behält die Zeilenenden ausdrücklich bei oder setzt sie ausdrücklich. +- Jeder Aufruf von `subprocess` übergibt `encoding="utf-8", errors="replace"`. +- Unterschiede zwischen Plattformen (Windows-Pfade virtueller Umgebungen, ausführbare Dateien, Kodierung der Konsole, Löschen von Dateien) laufen über `src/fastapi_fastkit/utils/platform.py`. +- Die Tests müssen unter Windows bestehen: kein fest eingetragenes `/tmp`, keine erwarteten Pfade, die mit `/` zusammengesetzt sind, und für Tests mit `chmod` ein Skip, der sie auf POSIX beschränkt. Um einen Windows-Zweig zu testen, patchst du die Prüfung in `src/fastapi_fastkit/utils/platform.py`; patche niemals `os.name`. +- Behalte die Zeilenenden jeder Datei bei. +- Neuer Code kommt mit Tests, die sein Verhalten prüfen. -```python -def test_full_project_creation_workflow(tmp_path): - # Create project - result = runner.invoke(cli, ['init'], input='...') - assert result.exit_code == 0 +### Optionen und erzeugter Code - # Add route - result = runner.invoke(cli, ['addroute', 'test-project', 'users']) - assert result.exit_code == 0 +Die Optionen, die `fastkit init` anbietet, ihre Pakete und die Regeln zwischen ihnen stammen aus `src/fastapi_fastkit/catalog/catalog.toml`. Eine neue Option gehört dort in ihre Feature-Gruppe und in die passende Optionsliste in `src/fastapi_fastkit/core/settings.py`; `tests/test_catalog/test_agreement.py` schlägt fehl, wenn die beiden nicht übereinstimmen. - # Verify files exist - assert (tmp_path / "test-project" / "src" / "api" / "routes" / "users.py").exists() -``` +Die Dateien, die Features zu einem Projekt hinzufügen, sind Jinja2-Templates unter `src/fastapi_fastkit/fragments/`, niemals in Python zusammengesetzte Strings. `src/fastapi_fastkit/fragments/README.md` beschreibt den Aufbau und die Schritte, mit denen du ein Feature hinzufügst. Jedes Fragment endet mit einem Zeilenumbruch. ## Dokumentation -### Dokumentation lokal bereitstellen - -
+Die Website wird mit MkDocs und Material gebaut. Installiere die Abhängigkeiten der Dokumentation mit `pdm install -G docs` oder `pip install -r requirements-docs.txt` und baue die Website dann so, wie es die CI tut: ```console -$ make serve-docs -INFO - Building documentation... -INFO - Cleaning site directory -INFO - Documentation built in 0.43 seconds -INFO - [14:30:00] Serving on http://127.0.0.1:8000/ +$ mkdocs build --strict -d site ``` -
- -### Dokumentation bauen - -
- -```console -$ make build-docs -INFO - Building documentation... -INFO - Documentation built in 0.43 seconds -``` - -
- -### Dokumentation schreiben - -Die Dokumentation wird in Markdown verfasst und mit MkDocs gebaut. Beispielstruktur: - -**Vorlage für einen Funktions-Leitfaden:** - -````markdown -# New Feature Guide - -This guide explains how to use the new feature. - -## Prerequisites - -- FastAPI-fastkit installed -- Basic Python knowledge - -## Usage - -
- -```console -$ fastkit new-feature --option value -✅ Feature executed successfully! -``` - -
- -!!! tip "Pro Tip" - Use `--help` to see all available options. -```` - -Für eine ausführliche Referenz zu `mkdocs-material` siehe [mkdocs-material-Dokumentation](https://squidfunk.github.io/mkdocs-material/reference/admonitions/). - -## Code-Stil-Richtlinien - -### Python-Codestil +`make serve-docs` stellt die Website unter `http://127.0.0.1:8000/` bereit, während du die Seiten bearbeitest; `make build-docs` baut ohne `--strict`. Die englischen Seiten liegen in `docs/en/`; um die anderen Sprachen geht es im [Übersetzungsleitfaden](translation-guide.md). -Folgen Sie [PEP 8](https://www.python.org/dev/peps/pep-0008/) mit folgenden Regeln: +### Generierte Blöcke -- **Zeilenlänge**: 88 Zeichen (Black-Standard) -- **Imports**: mit isort organisiert -- **Type Hints**: für alle öffentlichen Funktionen erforderlich -- **Docstrings**: Google-Style für alle öffentlichen APIs +Referenztabellen und Hilfetexte stehen in der Seite zwischen zwei Kommentarzeilen und werden aus dem Katalog und dem CLI erzeugt: -### Beispiel - -```python -from typing import List, Optional -from pathlib import Path - -def create_project_structure( - project_name: str, - template_path: Path, - output_dir: Optional[Path] = None, -) -> List[Path]: - """Create project structure from template. - - Args: - project_name: Name of the project to create - template_path: Path to the template directory - output_dir: Output directory, defaults to current directory - - Returns: - List of created file paths - - Raises: - ValueError: If project_name is invalid - FileNotFoundError: If template_path doesn't exist - """ - if not project_name.isidentifier(): - raise ValueError(f"Invalid project name: {project_name}") - - if not template_path.exists(): - raise FileNotFoundError(f"Template not found: {template_path}") - - # Implementation here... - return created_files -``` - -## Umgebungsvariablen - -Für die Entwicklung können Sie folgende Umgebungsvariablen setzen: - -| Variable | Beschreibung | Standard | -|----------|-------------|---------| -| `FASTKIT_DEBUG` | Debug-Logging aktivieren | `False` | -| `FASTKIT_DEV_MODE` | Entwicklungs-Funktionen aktivieren | `False` | -| `FASTKIT_TEMPLATE_DIR` | Verzeichnis für eigene Vorlagen | Eingebaute Vorlagen | -| `FASTKIT_CONFIG_DIR` | Konfigurationsverzeichnis | `~/.fastkit` | -| `TRANSLATION_API_KEY` | API-Schlüssel für Übersetzungen (verwenden Sie ein GitHub-PAT, wenn Sie den [GitHub-KI-Modell-Anbieter](https://github.com/marketplace/models/azure-openai) nutzen) | `None` | - -
- -```console -$ export FASTKIT_DEBUG=true -$ export FASTKIT_DEV_MODE=true -$ fastkit init -DEBUG: Loading configuration from /home/user/.fastkit/ -DEBUG: Available templates: ['fastapi-default', ...] -``` - -
- -Für weitere Einstellungen zu Umgebungsvariablen siehe das Modul [@settings.py](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/core/settings.py). - -## Fehlerbehebung - -### Häufige Probleme - -**1. Pre-Commit-Hooks schlagen fehl:** - -
- -```console -$ git commit -m "Fix bug" -black....................................................................Failed -hookid: black - -Files were modified by this hook. Additional output: - -would reformat src/cli.py -``` - -
- -**Lösung:** Formatter ausführen und erneut committen: - -
- -```console -$ make format -$ git add . -$ git commit -m "Fix bug" -``` - -
- -**2. Tests schlagen bei unterschiedlichen Python-Versionen fehl:** - -**Lösung:** tox verwenden, um mehrere Python-Versionen zu testen: - -
- -```console -$ pip install tox -$ tox -py38: commands succeeded -py39: commands succeeded -py310: commands succeeded -py311: commands succeeded -py312: commands succeeded +```markdown + +... + ``` -
- -**3. Import-Fehler in der Entwicklung:** - -**Lösung:** Paket im Editable-Modus installieren: -
+Bearbeite niemals den Inhalt eines Blocks. Nachdem du den Katalog, den Hilfetext eines Befehls oder die doctor-Prüfungen geändert hast, oder nachdem du einen Block hinzugefügt hast (die zwei Kommentarzeilen ohne etwas dazwischen), führst du das Skript aus: ```console -$ pip install -e . +$ python scripts/docs_blocks.py +$ python scripts/docs_blocks.py --check ``` -
- -### Hilfe bekommen - -- **[GitHub Issues](https://github.com/bnbong/FastAPI-fastkit/issues)**: Bugs und Feature-Requests melden -- **[GitHub Discussions](https://github.com/bnbong/FastAPI-fastkit/discussions)**: Fragen stellen und Ideen teilen -- **Dokumentation**: siehe [Benutzerhandbuch](../user-guide/installation.md) +Der erste Befehl schreibt jeden veralteten Block neu; `--check` listet die veralteten Blöcke auf und endet mit Exit-Status 1, und `--lang ko` beschränkt beide Befehle auf eine Sprache. `tests/test_docs` schlägt fehl, solange ein Block veraltet ist. -## Beitrags-Richtlinien +### Regeln für die Seiten -### Vor dem Einreichen einer PR +`tests/test_docs` prüft auch die englischen Seiten: -1. **Alle Prüfungen ausführen:** `make dev-check` -2. **Dokumentation aktualisieren**, falls nötig -3. **Tests** für neue Funktionen hinzufügen -4. **Commit-Konventionen** befolgen +- Jede Seite unter `docs/en/` steht in der `nav` von `mkdocs.yml`, und jeder Eintrag der `nav` existiert. +- Links auf die FastAPI-Dokumentation verwenden die Adressen der Katalogkonzepte (die generierten `concepts`-Blöcke) oder eine Adresse, die in `tests/test_docs/test_site_structure.py` aufgeführt ist. +- Keine Nummern von Pull Requests oder Issues. -### Format der Commit-Nachricht +Setze in ```` ```console ````-Blöcken `$ ` vor jeden Befehl und beginne nie eine Zeile mit `# `: Der Kopierbutton kopiert eine solche Zeile als Befehl. Schreibe Kommentare stattdessen hinter den Befehl. -``` -type(scope): brief description - -Longer description if needed - -Fixes #123 -``` +### Wenn du eine Seite verschiebst oder löschst -**Typen:** +Trage den alten Pfad in `REDIRECTS` in `scripts/mkdocs_hooks/redirects.py` ein, mit der neuen Adresse als Wert. Nach jedem Build schreibt der Hook in jeder Sprache unter der alten Adresse eine Seite, die die Leser zur neuen Adresse weiterleitet. `tests/test_docs/test_redirects.py` prüft, dass kein alter Pfad mehr als Seite existiert und dass jedes Ziel existiert. -- `feat`: neue Funktion -- `fix`: Bugfix -- `docs`: Dokumentationsänderungen -- `style`: Code-Stil-Änderungen -- `refactor`: Refactoring -- `test`: Tests hinzufügen/ändern -- `chore`: Wartungsaufgaben +### Seite des Web-Generators -**Beispiele:** +Die Seite `docs/en/start/web-generator.md` führt fastkit mit Pyodide im Browser aus. Sie lädt Dateien, die `scripts/web_generator/build_assets.py` aus dem Wheel von fastkit baut. Baue diese Dateien also, bevor du dir die Seite in der Vorschau ansiehst. Für den Vergleich weiter unten brauchst du Node.js (die CI verwendet 22) und eine virtuelle Umgebung, in die du fastkit neu installieren kannst, denn das Wheel ersetzt eine Editable-Installation. +```bash +python -m pip wheel --no-deps -w dist . +python -m pip install dist/fastapi_fastkit-*.whl +python scripts/web_generator/build_assets.py --wheel dist/fastapi_fastkit-*.whl \ + --out docs/en/assets/fastkit-generator +make serve-docs ``` -feat(cli): add new template command - -Add support for creating projects from custom templates. -The command accepts a template path and creates a new -project with the specified configuration. - -Fixes #45 -fix(templates): handle missing template files gracefully +Öffne dann `/start/web-generator/` auf dem lokalen Server. Der erste Build lädt Pyodide nach `.cache/web-generator` herunter und prüft jede Datei gegen die festgelegten Prüfsummen (`--no-cache` umgeht den Cache). `docs/en/assets/fastkit-generator/` und `.cache/web-generator/` werden von git ignoriert und nie committet. Ohne die Assets zeigt die Seite eine Meldung, dass die Dateien des Generators nicht gebaut sind. -When a template file is missing, show a clear error message -instead of crashing with a stack trace. +Um zu prüfen, dass die Seite dieselben Projekte erzeugt wie die Kommandozeile, schickst du jeden Fall der Fixture-Datei durch den Generator der Seite in Node und durch den Befehl `fastkit` des installierten Wheels: -Fixes #67 +```bash +python scripts/web_generator/compare_with_cli.py \ + --assets docs/en/assets/fastkit-generator \ + --cases tests/fixtures/web_generator/cases.json ``` -## Release-Prozess - -Für Maintainer sieht der Release-Prozess so aus: - -1. **Version aktualisieren** in `setup.py` und `__init__.py` -2. **CHANGELOG.md aktualisieren** -3. **Release-PR erstellen** -4. **Release nach dem Merge taggen** -5. **GitHub Actions** baut und veröffentlicht automatisch - -
- -```console -$ git tag v1.2.0 -$ git push origin v1.2.0 -``` +Mit `--only 01-hello,03-layered` führst du nur einige Fälle aus (verwende die IDs aus der Fixture), und mit `--keep DIR` behältst du beide Ausgaben. Um ein Zip, das du von der Seite heruntergeladen hast, mit dem daneben angezeigten Befehl zu vergleichen, verwendest du `compare_with_cli.py --zip demo.zip -- init --project-name demo ...`. Um eine gebaute Website zu prüfen, führst du `mkdocs build --strict -d site` und danach `python scripts/web_generator/check_site.py site` aus. -
+Die Strings der Seite liegen für jede Sprache in `docs/js/web-generator-strings/.json`, und die Texte zu Stufen und Features stammen aus den Katalog-Overlays in `src/fastapi_fastkit/catalog/i18n/`. `tests/test_docs` prüft, dass jede Sprache dieselben Schlüssel und Platzhalter hat. -## Nächste Schritte +In der CI läuft der Workflow „Web generator“ bei Pull Requests, die `src/`, `docs/`, `README.md`, `CHANGELOG.md`, die Skripte für Dokumentation und Web-Generator, `pyproject.toml` oder `mkdocs.yml` ändern, und bei Pushes auf `main`. Er baut das Wheel und die Assets, vergleicht jeden Fall mit der Kommandozeile, baut die Dokumentationswebsite im Strict-Modus und prüft die Seite in allen sieben Sprachen. Das Deployment der Dokumentation wiederholt den Build und den Vergleich, bevor es mit `mkdocs gh-deploy --strict` veröffentlicht. -Nachdem Ihre Entwicklungsumgebung eingerichtet ist: +## Pull Requests -1. **[Code erkunden](https://github.com/bnbong/FastAPI-fastkit/tree/main/src/fastapi_fastkit)**, um die Architektur zu verstehen -2. **Test-Suite ausführen**, um sicherzustellen, dass alles funktioniert -3. **Ein [Issue](https://github.com/bnbong/FastAPI-fastkit/issues)** auf GitHub auswählen -4. **Sich an [Discussions](https://github.com/bnbong/FastAPI-fastkit/discussions)** beteiligen, um sich mit anderen Mitwirkenden zu vernetzen +Beginne den Titel des Pull Requests mit einem Tag aus `CONTRIBUTING.md`: `[FEAT]`, `[FIX]`, `[DOCS]`, `[STYLE]`, `[TEST]`, `[REFACTOR]` oder `[CHORE]`, zum Beispiel `[FIX] Fix virtual environment activation in Windows`. Führe vor dem Push `make dev-check` aus. Ein Pull Request, der ein Template ändert, führt außerdem die Template-Inspektion aus, die im [Template-Leitfaden](template-creation-guide.md#checks) beschrieben ist. -Viel Spaß beim Programmieren! 🚀 +## Releases -!!! tip "Entwicklungs-Tipps" - - Vor dem Committen `make dev-check` ausführen - - Tests zuerst schreiben (TDD-Ansatz) - - Commits klein und fokussiert halten - - Dokumentation mit neuen Funktionen aktualisieren +1. Setze `__version__` in `src/fastapi_fastkit/__init__.py`; die Paketversion wird von dort gelesen. +2. Trage das Release in `CHANGELOG.md` unter einer Überschrift `## vX.Y.Z` ein. Jeder Eintrag besteht aus ein oder zwei Sätzen, ohne Nummern von Pull Requests und ohne Namen interner Funktionen. +3. Veröffentliche ein GitHub-Release. Der Workflow „Distribute“ schreibt dann den Release-Tag in `src/fastapi_fastkit/__init__.py`, baut das Paket mit PDM und veröffentlicht es auf PyPI. diff --git a/docs/de/contributing/template-creation-guide.md b/docs/de/contributing/template-creation-guide.md index 2f4d14b7..955dc6f6 100644 --- a/docs/de/contributing/template-creation-guide.md +++ b/docs/de/contributing/template-creation-guide.md @@ -1,578 +1,182 @@ -# Leitfaden zur Erstellung von FastAPI-Vorlagen +# Template-Leitfaden -Ein umfassender Leitfaden zum Hinzufügen neuer FastAPI-Projektvorlagen zu FastAPI-fastkit. +Diese Seite zeigt, wie ein mitgeliefertes Template aufgebaut ist, wie es im Katalog registriert wird, welche Konventionen jedes Template einhält und welche Prüfungen für Templates laufen. Richte zuerst das Repository ein, wie unter [Entwicklungsumgebung einrichten](development-setup.md) beschrieben. -## 🎯 Überblick +## Aufbau eines Templates -Das Hinzufügen einer neuen Vorlage erfolgt in einem Prozess aus 5 Schritten: +Jedes Template ist ein Ordner unter `src/fastapi_fastkit/fastapi_project_template/`, der nach der Template-ID benannt ist (`fastapi-`, zum Beispiel `fastapi-auth-jwt`). `modules/` im selben Ordner ist kein Template: Dort liegen die Dateien, die `fastkit addroute` schreibt. -1. **📋 Planung und Entwurf** — Zweck und Struktur der Vorlage definieren -2. **🏗️ Implementierung der Vorlage** — die erforderliche Struktur und Dateien erstellen -3. **🔍 Lokale Validierung** — die Vorlage mit dem Inspektor prüfen -4. **📚 Dokumentation** — README und Nutzungsleitfaden verfassen -5. **🚀 Einreichung und Review** — PR erstellen und Community-Review +Dateien, die auf `-tpl` enden, verlieren dieses Suffix, wenn fastkit das Template kopiert: Aus `src/main.py-tpl` wird `src/main.py`, aus `.env.example-tpl` wird `.env.example`. Jede Python-Datei muss auf `.py-tpl` enden; die Inspektion schlägt bei einer `.py`-Datei ohne das Suffix `-tpl` fehl. Beim Erzeugen werden in den kopierten Dateien vier Platzhalter ersetzt: ``, ``, `` und ``. -## 📋 Schritt 1: Planung und Entwurf +Ein Template braucht mindestens: -### Zweck der Vorlage definieren +- `README.md-tpl` und eine `main.py-tpl`, die die `FastAPI`-Anwendung erstellt, auf der obersten Ebene des Templates, in `src/` oder in `src/app/`. +- `pyproject.toml-tpl` mit `fastapi` in `[project].dependencies`. +- Einen Ordner `tests/` mit mindestens einem Modul `test_*.py-tpl`. -Bevor Sie eine neue Vorlage erstellen, beantworten Sie folgende Fragen: - -- **Welchen einzigartigen Wert bietet diese Vorlage?** -- **Wie unterscheidet sie sich von bestehenden Vorlagen?** -- **Welche Nutzergruppe ist die Zielgruppe?** -- **Welche Tech-Stack-Komponenten wird sie enthalten?** - -### Namenskonvention für Vorlagen +Die meisten Templates liefern außerdem die folgenden Dateien mit; kopiere sie aus `fastapi-default` und passe sie an: +```text +fastapi-default/ +├── .env.example-tpl +├── .gitattributes-tpl +├── .gitignore-tpl +├── README.md-tpl +├── pyproject.toml-tpl +├── requirements-dev.txt-tpl +├── requirements.txt-tpl +├── scripts/ +├── src/ +│ ├── api/ +│ ├── core/ +│ ├── crud/ +│ ├── main.py-tpl +│ ├── mocks/ +│ └── schemas/ +└── tests/ ``` -fastapi-{purpose}-{stack} -``` - -Beispiele: -- `fastapi-microservice` (Microservice-Vorlage) -- `fastapi-graphql` (GraphQL-Integrationsvorlage) -- `fastapi-auth-jwt` (JWT-Authentifizierungsvorlage) +`template-config.yml-tpl` ist optional und wird nur von der Inspektion gelesen: Zum Beispiel führt `requires_docker: true` die Tests des Templates in seinem Docker-Compose-Stack aus, und `app_module` nennt die Anwendung für den Smoke-Test. Die Datei wird nie in ein erzeugtes Projekt kopiert. -### Planung des Tech-Stacks +## Das Template im Katalog registrieren -Definieren Sie die wichtigsten Technologien vorab: +Füge `src/fastapi_fastkit/catalog/catalog.toml` einen Eintrag `[[templates]]` hinzu. Die Reihenfolge der Einträge ist die Reihenfolge von `fastkit list-templates`. -```yaml -# Example: fastapi-microservice template -core_dependencies: - - fastapi - - uvicorn - - pydantic - - pydantic-settings - -additional_features: - - sqlalchemy (ORM) - - alembic (migrations) - - redis (caching) - - celery (background tasks) - - pytest (testing) - -development_tools: - - black (code formatting) - - isort (import sorting) - - mypy (type checking) - - pre-commit (Git hooks) +```toml title="src/fastapi_fastkit/catalog/catalog.toml" +[[templates]] +id = "fastapi-auth-jwt" +kind = "example" +description = "FastAPI JWT Authentication" +read_first = "Read `src/app/main.py`, then `src/app/domains/auth/` and `src/app/core/security.py`." +addroute = false ``` -## 🏗️ Schritt 2: Implementierung der Vorlage +| Schlüssel | Bedeutung | +| --- | --- | +| `id` | Der Ordnername. Die Einträge und die Ordner müssen genau übereinstimmen. | +| `kind` | `level` (über eine Stufe erreichbar), `example` (mit `fastkit init --template` erreichbar) oder `internal` (mitgeliefert, aber nicht angeboten). Ein neues Beispielprojekt verwendet `example`. | +| `description` | Die erste Überschrift von `README.md-tpl` ohne das `# `. | +| `read_first` | Der Schritt „Zuerst lesen“ in der Liste „Next steps“; Pflicht für `level` und `example`. Jeder Pfad in Backticks muss im Template existieren. | +| `extend` | Optionaler Text für den Schritt „Erweitern“. | +| `concepts` | IDs der `[[concepts]]`-Einträge, deren Kommentare das Template enthält; lass den Schlüssel weg, wenn es keine gibt. | +| `addroute` | `false`, wenn die Liste „Next steps“ `fastkit addroute` nicht vorschlagen darf; der Defaultwert ist `true`. | -### Erforderliche Verzeichnisstruktur +Der Katalog-Loader weist unbekannte Schlüssel und unbekannte Konzept-IDs zurück. `tests/test_catalog/test_agreement.py` schlägt fehl, wenn ein Eintrag nicht zu seinem Ordner oder zur Überschrift seiner README passt. Füge `description`, `read_first` und `extend` außerdem übersetzt in jedes Overlay `src/fastapi_fastkit/catalog/i18n/.toml` ein; die Overlay-Tests schlagen fehl, bis jede Sprache diese Texte hat (siehe den [Übersetzungsleitfaden](translation-guide.md#catalog-overlays)). -``` -fastapi-{template-name}/ -├── src/ # Application source code -│ ├── main.py-tpl # ✅ FastAPI app entry point (required) -│ ├── __init__.py-tpl -│ ├── api/ # API routers -│ │ ├── __init__.py-tpl -│ │ ├── api.py-tpl # Main API router -│ │ └── routes/ # Individual routes -│ │ ├── __init__.py-tpl -│ │ └── items.py-tpl # Example route -│ ├── core/ # Core configuration -│ │ ├── __init__.py-tpl -│ │ └── config.py-tpl # Settings management -│ ├── crud/ # CRUD logic -│ │ ├── __init__.py-tpl -│ │ └── items.py-tpl -│ ├── schemas/ # Pydantic models -│ │ ├── __init__.py-tpl -│ │ └── items.py-tpl -│ └── utils/ # Utility functions -│ ├── __init__.py-tpl -│ └── helpers.py-tpl -├── tests/ # ✅ Tests (required) -│ ├── __init__.py-tpl -│ ├── conftest.py-tpl # pytest configuration -│ └── test_items.py-tpl # Example tests -├── scripts/ # Scripts -│ ├── format.sh-tpl # Code formatting -│ ├── lint.sh-tpl # Linting -│ ├── run-server.sh-tpl # Server execution -│ └── test.sh-tpl # Test execution -├── pyproject.toml-tpl # ✅ Primary metadata (PEP 621, required) -├── requirements.txt-tpl # 🟡 Optional when pyproject declares deps -├── setup.cfg-tpl # Development tools configuration -├── README.md-tpl # ✅ Project documentation (required) -├── .env-tpl # Environment variables template -└── .gitignore-tpl # Git ignore file -``` +## Konventionen -**Minimal erforderliche Dateien.** Eine Vorlage muss bereitstellen: +### HTTP-API -- ein `tests/`-Verzeichnis -- eine `README.md-tpl`-Datei -- `pyproject.toml-tpl` (PEP 621) -- eine Deklaration von `fastapi` als Abhängigkeit in `pyproject.toml-tpl` `[project].dependencies` oder `requirements.txt-tpl` +Templates mit fachlichen Routen folgen der API, die unter [Erzeugte Projekte](../reference/generated-projects.md#http-api) beschrieben ist: Routen unter `settings.API_V1_PREFIX`, `GET /health` auf der Wurzelebene, das `{"status": "ok"}` zurückgibt, Listen mit `limit` und `offset`, die `Page[XRead]` zurückgeben, 201 mit `Location`, 204 beim Löschen, `PUT` zum Ersetzen und `PATCH` zum Aktualisieren, 404 `{"detail": " not found"}` sowie die Schemanamen `XCreate`, `XUpdate` und `XRead`. Ein Router trägt nur das Präfix seiner Ressource (`APIRouter(prefix="/items", tags=["items"])`). -`requirements.txt-tpl` ist nicht erforderlich, wenn `pyproject.toml-tpl` `[project].dependencies` deklariert — liefert eine Vorlage jedoch beide Dateien mit, müssen sie übereinstimmen: Die Inspektion schlägt bei Abhängigkeitsabweichungen zwischen ihnen fehl. +`core/pagination.py-tpl` und `core/responses.py-tpl` müssen, wo ein Template sie mitliefert, mit den Dateien in `fastapi_project_template/modules/core/` identisch sein; ein Test des Repositorys vergleicht jede Kopie. -**Neue Vorlagen sind pyproject-first und dürfen keine `setup.py-tpl` mitliefern.** Seit v1.4.0 enthält keine mitgelieferte Vorlage mehr eine solche Datei. Die Inspektion akzeptiert die Datei weiterhin, damit externe Vorlagen funktionsfähig bleiben, aber es handelt sich um einen Legacy-Pfad. +### Einstellungen und Secrets -**Zielen Sie durchgängig auf Python 3.12**: `requires-python = ">=3.12"`, black `target-version = ["py312"]`, mypy `python_version = "3.12"` und `python:3.12-slim` für jedes Docker-Basis-Image. Die Inspektion prüft, dass die drei Festlegungen übereinstimmen. +- Ein einziges Einstellungsmodul auf Basis von pydantic-settings liest die Umgebung und `.env`. Übernimm die Prüfungen von `SECRET_KEY` und die Liste öffentlicher Beispielschlüssel aus `fastapi-default/src/core/config.py-tpl`: Mit `ENVIRONMENT=staging` oder `production` verweigert die Anwendung den Start, wenn `SECRET_KEY` fehlt, öffentlich bekannt oder zu kurz (unter 32 Byte) ist. +- Liefere `.env.example-tpl` mit Platzhalterwerten mit, niemals eine `.env-tpl`. fastkit erstellt daraus `.env` mit einem eindeutigen `SECRET_KEY`. +- `.gitignore-tpl` ignoriert `.env` und `.env.*` und nimmt `!.env.example` wieder auf. +- `.gitattributes-tpl` legt LF für Shell-Skripte, Docker-Dateien, `Makefile` und env-Dateien fest. +- CORS-Origins kommen nur aus `BACKEND_CORS_ORIGINS`, und `*` schaltet die Credentials ab. -**Deklarieren Sie `FastAPI-fastkit` niemals als Laufzeitabhängigkeit** eines generierten Projekts. Das CLI ist ein Entwicklungswerkzeug; die Abhängigkeitsliste einer Vorlage sollte nur enthalten, was die generierte Anwendung selbst importiert. +### Abhängigkeiten und Werkzeuge -### Anleitung zum Schreiben der Dateien +- Ziel ist überall Python 3.12: `requires-python = ">=3.12"`, für black `target-version = ["py312"]`, für mypy `python_version = "3.12"` und `python:3.12-slim` als Basis-Image für Docker. Die Inspektion prüft die ersten drei. +- Laufzeitpakete gehören in `[project].dependencies` und `requirements.txt-tpl`; Test- und Lint-Werkzeuge gehören in die Abhängigkeitsgruppe `dev` und in `requirements-dev.txt-tpl`, die mit `-r requirements.txt` beginnt. Ein `Dockerfile-tpl` installiert nur `requirements.txt`. Die Inspektion schlägt fehl, wenn ein Paket aus `[project].dependencies` in `requirements.txt-tpl` fehlt. +- Führe `FastAPI-fastkit` nie als Abhängigkeit des erzeugten Projekts auf. +- Behalte die Tabelle `[tool.fastapi-fastkit]` mit `managed = true` und das Präfix `[FastAPI-fastkit templated]` in `description` bei; den Rest des Blocks füllt fastkit beim Erzeugen aus. +- Lege jede Werkzeugeinstellung in `pyproject.toml-tpl` ab (`[tool.pytest.ini_options]`, `[tool.coverage.*]`, `[tool.black]`, `[tool.isort]`, `[tool.mypy]`, `[tool.ruff]`); kein Template liefert eine `setup.cfg-tpl` oder `pytest.ini-tpl` mit. Jedes Template außer `fastapi-hello` liefert denselben `[tool.ruff]`-Block mit, den `fastkit init --feature tooling=ruff` schreibt, und erzeugte Projekte müssen black, isort, `ruff check` und `ruff format --check` bestehen. Die Stufen-Templates nach `fastapi-hello` führen außerdem pytest-cov, black, isort, mypy und ruff in ihrer Gruppe `dev` auf und enthalten die Einstellungen für die Testabdeckung, sodass `pytest --cov` in jedem Projekt funktioniert, das aus ihnen erzeugt wird. -#### 1. main.py-tpl schreiben +### Kommentarzeilen und README-Markierung -```python -""" -FastAPI application entry point +- `main.py-tpl` und das Modul, das die Router der Ressourcen sammelt, behalten die Kommentarzeilen `# fastkit:imports` und `# fastkit:routes`: `fastkit init` und `fastkit addroute` fügen dort Code ein. +- `README.md-tpl` enthält genau eine Zeile ``, nach der Einleitung und vor der nächsten Überschrift `##`, mit einer Leerzeile davor und danach. Beim Erzeugen wird sie durch die Liste „Next steps“ ersetzt. -This file is the main application for the project created with FastAPI-fastkit. -""" -from fastapi import FastAPI -from fastapi.middleware.cors import CORSMiddleware +### Konzeptkommentare -from api.api import api_router -from core.config import settings +Ein Konzeptkommentar erklärt ein Konstrukt von FastAPI an der Stelle, an der es im Template zum ersten Mal vorkommt, in zwei Zeilen direkt über dem Code: -# Create FastAPI app (required for inspector validation) +```python title="fastapi-default/src/main.py-tpl" +# `app` is the FastAPI application that uvicorn serves: `uvicorn src.main:app`. +# https://fastapi.tiangolo.com/tutorial/first-steps/ app = FastAPI( - title="", - description="Project created with FastAPI-fastkit", - version="1.0.0", -) - -# CORS middleware configuration -app.add_middleware( - CORSMiddleware, - allow_origins=["*"], - allow_credentials=True, - allow_methods=["*"], - allow_headers=["*"], -) - -# Register API router -app.include_router(api_router, prefix="/api/v1") - -@app.get("/") -async def root(): - """Root endpoint""" - return {"message": "Hello from !"} - -@app.get("/health") -async def health_check(): - """Health check endpoint""" - return {"status": "healthy"} - -if __name__ == "__main__": - import uvicorn - uvicorn.run(app, host="0.0.0.0", port=8000) -``` - -#### 2. pyproject.toml-tpl schreiben (bevorzugt) - -Moderne Vorlagen sollten Metadaten und Abhängigkeiten in einem PEP-621-`pyproject.toml-tpl` deklarieren. Mindestens muss die Datei einen `[project]`-Abschnitt mit `name`, `version`, einer `description` und einer `dependencies`-Liste, die `fastapi` enthält, bereitstellen. Vorlagen müssen außerdem zwei FastAPI-fastkit-Identitätsmarker tragen, damit `is_fastkit_project()` generierte Projekte von unverwandten FastAPI-Projekten im Workspace des Nutzers unterscheiden kann: - -- `[FastAPI-fastkit templated]`-Präfix in `description` -- eine eigene Tabelle `[tool.fastapi-fastkit]` mit `managed = true` - -Die Erkennung akzeptiert jeden der beiden Marker (Vergleich ist case-insensitive). Die Metadaten-Injektion fügt beide bei der Projektgenerierung hinzu, falls die Vorlage sie weglässt — Autoren sollten sie aber explizit angeben. - -```toml -[project] -name = "" -version = "0.1.0" -description = "[FastAPI-fastkit templated] " -authors = [ - {name = "", email = ""}, -] -readme = "README.md" -requires-python = ">=3.12" -dependencies = [ - "fastapi>=0.115.0", - "uvicorn[standard]>=0.34.0", - "pydantic>=2.10.0", - "pydantic-settings>=2.7.0", - "python-dotenv>=1.0.0", -] - -[project.optional-dependencies] -dev = [ - "pytest>=8.0.0", - "httpx>=0.28.0", -] - -[tool.fastapi-fastkit] -managed = true - -[build-system] -requires = ["hatchling"] -build-backend = "hatchling.build" -``` - -#### 3. requirements.txt-tpl schreiben (optional) - -Optional, wenn `pyproject.toml-tpl` `[project].dependencies` deklariert. Weiterhin nützlich für Vorlagen, die reine `pip`-Workflows bevorzugen. - -```txt -# FastAPI core dependencies (required) -fastapi==0.104.1 -uvicorn[standard]==0.24.0 - -# Data validation -pydantic==2.5.0 -pydantic-settings==2.1.0 - -# Environment variable management -python-dotenv==1.0.0 - -# Database (if needed) -sqlalchemy==2.0.23 -alembic==1.13.0 - -# Development tools -pytest==7.4.3 -pytest-asyncio==0.21.1 -httpx==0.25.2 - -# Code quality -black==23.11.0 -isort==5.12.0 -mypy==1.7.1 -``` - -#### 4. Routen-Anker - -Vorlagen, die eine `main.py-tpl` oder ein API-Aggregatormodul mitliefern, sollten markieren, wo `fastkit addroute` Code einfügt: - -```python -from src.app.api import health - -# fastkit:imports - -api_router = APIRouter() -api_router.include_router(health.router) - -# fastkit:routes -``` - -Ohne die Anker greift `addroute` auf ein AST-basiertes Einfügen zurück, das den Importblock und die Router-Registrierungen selbst ermittelt — eine Vorlage ohne Anker funktioniert also weiterhin, das Ergebnis ist aber weniger vorhersehbar. Lassen Sie die Kommentare beim Bearbeiten dieser Dateien an ihrem Platz. - -#### 5. Test-Dateien schreiben - -```python -# tests/test_items.py-tpl -""" -Items API test module -""" -import pytest -from fastapi.testclient import TestClient -from main import app - -client = TestClient(app) - -def test_read_root(): - """Test root endpoint""" - response = client.get("/") - assert response.status_code == 200 - assert "message" in response.json() - -def test_health_check(): - """Test health check""" - response = client.get("/health") - assert response.status_code == 200 - assert response.json() == {"status": "healthy"} - -def test_create_item(): - """Test item creation""" - item_data = { - "name": "Test Item", - "description": "Test Description" - } - response = client.post("/api/v1/items/", json=item_data) - assert response.status_code == 200 - data = response.json() - assert data["name"] == item_data["name"] - assert data["description"] == item_data["description"] - -def test_read_items(): - """Test reading items list""" - response = client.get("/api/v1/items/") - assert response.status_code == 200 - assert isinstance(response.json(), list) -``` - -## 🔍 Schritt 3: Lokale Validierung - -### Automatisierte Validierungsskripte ausführen - -Sobald Ihre neue Vorlage fertig ist, prüfen Sie sie mit folgenden Befehlen: - -```bash -# Validate all templates -make inspect-templates - -# Validate specific template only -make inspect-template TEMPLATES="fastapi-your-template" - -# Validate with verbose output -python scripts/inspect-templates.py --templates "fastapi-your-template" --verbose - -# Fast local loop: no network, no server boot -python scripts/inspect-templates.py --templates "fastapi-your-template" \ - --offline --no-smoke - -# Full check before opening a PR (adds mypy over the generated project) -python scripts/inspect-templates.py --templates "fastapi-your-template" --mypy -``` - -`--offline` überspringt die PyPI-Abfragen zur Aktualität der Abhängigkeiten, `--no-smoke` überspringt das Starten des generierten Projekts (der langsamste Schritt), und `--mypy` führt eine Typprüfung des generierten Projekts durch. Was jede Prüfung tut, beschreibt [Qualitätssicherung der Vorlagen](../reference/template-quality-assurance.md). - -!!! note - - Wenn Sie eine PR einreichen, läuft der **Template PR Inspection**-Workflow automatisch und validiert Ihre Vorlagenänderungen. Sie erhalten das Feedback direkt in Ihrer PR. - -### Validierungs-Checkliste - -Der Inspektor validiert automatisch die folgenden Punkte: - -#### ✅ Validierung der Dateistruktur - -- [ ] `tests/`-Verzeichnis existiert -- [ ] `README.md-tpl`-Datei existiert -- [ ] `pyproject.toml-tpl` existiert (keine `setup.py-tpl` in neuen Vorlagen) - -#### ✅ Validierung der Dateiendungen - -- [ ] Alle Python-Dateien verwenden die Endung `.py-tpl` -- [ ] Keine `.py`-Dateien existieren - -#### ✅ Validierung der Abhängigkeiten - -- [ ] `fastapi` ist in mindestens einem von Folgendem deklariert: - - [ ] `pyproject.toml-tpl` unter `[project].dependencies` (bevorzugt) - - [ ] `requirements.txt-tpl` -- [ ] `requirements.txt-tpl` und `[project].dependencies` widersprechen sich nicht -- [ ] `FastAPI-fastkit` ist **keine** Laufzeitabhängigkeit - -#### ✅ Validierung der FastAPI-Implementierung - -- [ ] `FastAPI`-Import existiert in `main.py-tpl` -- [ ] App-Erstellung wie `app = FastAPI()` existiert in `main.py-tpl` - -#### ✅ Validierung der Testausführung - -- [ ] Erstellung der virtuellen Umgebung erfolgreich -- [ ] Installation der Abhängigkeiten erfolgreich -- [ ] Alle pytest-Tests bestehen - -#### ✅ Smoke-Test - -- [ ] Das generierte Projekt startet unter uvicorn -- [ ] `/docs` antwortet -- [ ] `/health` antwortet - -Das uvicorn-Ziel wird aus `[tool.fastapi-fastkit].app_module` in der generierten `pyproject.toml` ermittelt, danach aus `app_module` in `template-config.yml` und schließlich aus den üblichen `main.py`-Speicherorten. - -#### ✅ Konsistenz der Konfiguration - -- [ ] `requires-python`, black `target-version` und mypy `python_version` geben alle Python 3.12 an -- [ ] Keine Abhängigkeitsabweichung zwischen `requirements.txt-tpl` und `[project].dependencies` -- [ ] Keine Selbstabhängigkeit von `FastAPI-fastkit` - -#### ✅ Platzhalter-Rückstände - -- [ ] Kein `` übersteht die Projektgenerierung - -#### ✅ Automatisiertes Vorlagen-Testen - -FastAPI-fastkit enthält **automatisierte Vorlagen-Tests**, die umfassende Tests für alle Vorlagen ausführen: - -**Testabdeckung:** - -- ✅ Prozess der Projektanlegung -- ✅ Injektion der Projekt-Metadaten -- ✅ Einrichtung der virtuellen Umgebung -- ✅ Installation der Abhängigkeiten (alle Paketmanager) -- ✅ Validierung der grundlegenden Projektstruktur -- ✅ Identifikation als FastAPI-Projekt - -**Testausführung:** -```console -# Test all templates automatically -$ pytest tests/test_templates/test_all_templates.py -v - -# Test specific template -$ pytest tests/test_templates/test_all_templates.py::TestAllTemplates::test_template_creation[your-template-name] -v ``` -**Erkennung der Vorlagen-Tests:** -Neue Vorlagen werden **automatisch erkannt** und ohne manuelle Konfiguration getestet: +- Die erste Zeile ist ein einziger Satz und nennt fastkit nicht; die zweite Zeile enthält nur die URL, und diese muss die URL eines `[[concepts]]`-Eintrags im Katalog sein. Beide Zeilen passen in 88 Spalten. +- Ein Template verlinkt jedes Konzept höchstens einmal. Die IDs der Kommentare eines `level`-Templates müssen genau seiner `concepts`-Liste im Katalog entsprechen; die IDs der Kommentare eines `example`-Templates müssen in seiner Liste stehen. +- Der Block steht direkt über dem Code: nicht innerhalb eines Import-Blocks und nicht zwischen einem Dekorator und seiner Funktion. +- Die Dateien unter `modules/` enthalten keine Konzeptkommentare. -1. ✅ **Null Konfiguration**: Vorlage hinzufügen → automatische Tests -2. ✅ **Einheitliche Tests**: gleiche Qualitätsstandards für alle Vorlagen -3. ✅ **Mehrere Paketmanager**: Tests mit UV, PDM, Poetry und PIP -4. ✅ **Umfassende Validierung**: Struktur, Metadaten und Funktionsprüfungen +`tests/test_templates/test_concept_comments.py` prüft jede Regel dieses Abschnitts. -**Was das für Sie bedeutet:** +## Prüfungen {#checks} -- 🚀 **Keine zusätzlichen Test-Dateien in der Hauptquelle von `FastAPI-fastkit`**: Ihre Vorlage wird automatisch getestet -- ⚡ **Schnellere Entwicklung**: Fokus auf Vorlageninhalt, nicht auf Test-Setup -- 🛡️ **Qualitätssicherung**: einheitliche Tests über alle Vorlagen hinweg -- 🔄 **CI/CD-Integration**: automatische Tests in Pull-Requests +### Ein Template lokal inspizieren -**Manuelle Tests bleiben weiterhin nötig:** +`scripts/inspect-templates.py` erzeugt aus dem Template ein echtes Projekt (ohne virtuelle Umgebung), führt eine Reihe von Prüfungen daran aus und bricht beim ersten Fehlschlag ab: -- 🧪 **Vorlagenspezifische Funktionen**: Geschäftslogik und individuelle Features -- 🔧 **Integrationstests**: externe Dienste und komplexe Workflows -- 📱 **End-to-End-Szenarien**: vollständige Nutzerflüsse +| Schritt | Was er prüft | +| --- | --- | +| File structure | `tests/`, `README.md-tpl` und `pyproject.toml-tpl` existieren. | +| File extensions | Keine `.py`-Datei ohne `-tpl`. | +| Test suite presence | Mindestens ein `test_*.py-tpl` unter `tests/`. | +| Junk files | Kein `.DS_Store`, `__pycache__`, `.venv`, `.pyc` und Ähnliches. | +| Dependencies | `fastapi` ist deklariert. | +| Configuration consistency | Die Festlegungen auf Python 3.12, kein Paket aus `[project].dependencies`, das in `requirements.txt-tpl` fehlt, keine Abhängigkeit von `FastAPI-fastkit`. | +| FastAPI implementation | Das erzeugte Projekt hat eine `main.py` auf der obersten Ebene, in `src/` oder in `src/app/`, und diese erstellt eine Anwendung `FastAPI(...)`. | +| Placeholder substitution | Im erzeugten Projekt ist kein `` übrig. | +| Compile check | Jede Python-Datei lässt sich kompilieren. | +| Template tests | Erstellt eine virtuelle Umgebung, installiert die Abhängigkeiten und führt `scripts/test.sh` aus, oder `pytest tests/ -v`, wenn es dieses Skript nicht gibt. | +| Type check | `mypy .` im erzeugten Projekt, einschließlich der Tests, mit den mypy-Einstellungen des Templates (nur mit `--mypy`). | +| Smoke test | Startet die Anwendung mit uvicorn; `/docs` muss mit 200 antworten und `/health`, sofern vorhanden, ebenfalls mit 200. | +| Dependency freshness | Warnt vor gepinnten Versionen, die hinter dem neuesten Release auf PyPI zurückliegen (mit `--offline` übersprungen). | -**Best Practices für Tests:** ```console -# 1. Test your template locally -$ fastkit startdemo your-template-name - -# 2. Run automated tests -$ pytest tests/test_templates/test_all_templates.py::TestAllTemplates::test_template_creation[your-template-name] -v - -# 3. Test with different package managers -$ fastkit startdemo your-template-name --package-manager poetry -$ fastkit startdemo your-template-name --package-manager pdm -$ fastkit startdemo your-template-name --package-manager uv -``` - -### Manuelle Validierungs-Checkliste - -Zusätzlich zur automatisierten Validierung manuell überprüfen: - -#### 🔧 Code-Qualität - -- [ ] Code folgt dem PEP-8-Styleguide -- [ ] Angemessene Verwendung von Type Hints -- [ ] Sinnvolle Variablen- und Funktionsnamen -- [ ] Angemessene Kommentare und Docstrings - -#### 🏗️ Architektur - -- [ ] Trennung der Belange (API, Geschäftslogik, Datenzugriff getrennt) -- [ ] Wiederverwendbare Komponenten -- [ ] Skalierbare Struktur -- [ ] Best Practices für Sicherheit angewendet - -#### 📚 Dokumentation - -- [ ] README.md-tpl folgt dem Format von PROJECT_README_TEMPLATE.md -- [ ] Installations- und Ausführungsmethoden beschrieben -- [ ] API-Dokumentation (OpenAPI/Swagger) -- [ ] Erläuterung der Umgebungsvariablen +$ python scripts/inspect-templates.py --help +usage: inspect-templates.py [-h] [--templates TEMPLATES] [--output OUTPUT] + [--verbose] [--offline] [--no-smoke] [--mypy] -## 📚 Schritt 4: Dokumentation - -### README.md-tpl verfassen - -Schreiben Sie auf Basis des Leitfadens [PROJECT_README_TEMPLATE.md](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fastapi_project_template/PROJECT_README_TEMPLATE.md). - -### Beschreibung der Vorlage schreiben - -Fügen Sie eine Beschreibung Ihrer neuen Vorlage zu `src/fastapi_fastkit/fastapi_project_template/README.md` hinzu: - -```markdown -## fastapi-your-template - -Write a brief description and use cases for your new template here. - -### Features: -- Feature 1 -- Feature 2 -- Feature 3 - -### Use Cases: -- Use case 1 -- Use case 2 -``` - -## 🚀 Schritt 5: Einreichung und Review - -### Checkliste vor der PR - -- [ ] Alle automatisierten Validierungen bestanden (`make inspect-templates`) -- [ ] Code-Formatierung abgeschlossen (`make format`) -- [ ] Linting-Prüfungen bestanden (`make lint`) -- [ ] Alle Tests bestanden (`make test`) -- [ ] Dokumentation abgeschlossen -- [ ] Richtlinien aus CONTRIBUTING.md befolgt - -### PR-Titel und -Beschreibung +Inspect FastAPI templates locally +options: + -h, --help show this help message and exit + --templates TEMPLATES + Specific templates to inspect (comma-separated, leave + empty for all) + --output OUTPUT Output JSON file for results + --verbose Enable verbose output + --offline Skip every network lookup (dependency freshness + reporting) + --no-smoke Skip booting the generated project with uvicorn + --mypy Type check the generated project with mypy (slow) ``` -[TEMPLATE] Add fastapi-{template-name} template -## Overview -Adds a new {purpose} template. +Die Template-Tests brauchen uv im `PATH`. Ohne `--output` landen die Ergebnisse in `template_inspection_results.json`. Ein Lauf für ein einzelnes Template: -## Key Features -- Feature 1 -- Feature 2 -- Feature 3 - -## Validation Results -- [ ] Inspector validation passed -- [ ] All tests passed -- [ ] Documentation completed - -## Usage Example -\```bash -fastkit startdemo -# Select template: fastapi-{template-name} -\``` - -## Related Issues -Closes #issue-number +```console +$ python scripts/inspect-templates.py --templates fastapi-hello --offline --output results.json +📋 Found 1 templates to inspect: fastapi-hello +============================================================ +🔍 Inspecting template: fastapi-hello +... +✅ fastapi-hello: PASSED +---------------------------------------- +============================================================ +📊 INSPECTION SUMMARY + Total templates: 1 + ✅ Passed: 1 + ❌ Failed: 0 +🎉 All templates passed inspection! +📄 Results saved to: results.json ``` -### Review-Prozess - -1. **Automatisierte Validierung**: GitHub Actions validiert die Vorlage automatisch - - **Template PR Inspection**: führt `inspect-changed-templates.py` bei PRs aus, die Vorlagen ändern - - **Wöchentliche Inspektion**: vollständige Validierung der Vorlagen jeden Mittwoch -2. **Code-Review**: Maintainer und Community prüfen den Code -3. **Tests**: Die Vorlage wird in verschiedenen Umgebungen getestet -4. **Dokumentations-Review**: Genauigkeit und Vollständigkeit der Dokumentation prüfen -5. **Freigabe und Merge**: Merge in den Main-Branch, sobald alle Anforderungen erfüllt sind - -!!! note - - Sie erhalten automatische PR-Kommentare mit den Validierungsergebnissen. Prüfen Sie diese, bevor Sie ein Review anfordern! - -## 🎯 Best Practices - -### Sicherheitsüberlegungen - -- Sensible Informationen über Umgebungsvariablen verwalten -- Korrekte CORS-Konfiguration -- Eingabedaten validieren -- SQL-Injection verhindern - -### Performance-Optimierung - -- Asynchrone Verarbeitung nutzen -- Datenbankabfragen optimieren -- Passende Caching-Strategien -- Antwortkompression konfigurieren - -### Wartbarkeit +`make inspect-templates` inspiziert jedes Template, `make inspect-templates-verbose` fügt `--verbose` hinzu, und `make inspect-template TEMPLATES="fastapi-default,fastapi-hello"` inspiziert die Templates, die du nennst. Solange du an einer Änderung arbeitest, überspringt `--offline --no-smoke` das Netzwerk und den langsamsten Schritt. `--mypy` ist strenger als das, was die erzeugten Projekte selbst ausführen: Deren `scripts/lint.sh` prüft nur `mypy src`, während `--mypy` auch die Typen der Tests prüft. `fastapi-domain-starter` besteht jeden anderen Schritt, scheitert aber an `--mypy`, weil seine Tests keine Typannotationen haben. -- Klare Codestruktur -- Umfassende Testabdeckung -- Detaillierte Dokumentation -- Logging und Monitoring einrichten +### Tests des Repositorys -## 🆘 Brauchen Sie Hilfe? +`pytest` deckt auch die Templates ab: `tests/test_templates/` erzeugt aus jedem Template ein Projekt, führt die Linter auf erzeugten Projekten aus, vergleicht die Requirements-Dateien mit `pyproject.toml-tpl` und prüft die Konzeptkommentare und die README-Markierung. Einen neuen Template-Ordner erfassen die meisten dieser Tests von selbst; `tests/test_templates/test_template_requirements_split.py` führt jedes Template namentlich auf, trage deines also dort ein. -- 📖 [Anleitung zur Entwicklungsumgebung](development-setup.md) -- 📋 [Code-Richtlinien](code-guidelines.md) -- 💬 [GitHub Discussions](https://github.com/bnbong/FastAPI-fastkit/discussions) -- 📧 [Maintainer kontaktieren](mailto:bbbong9@gmail.com) +### In der CI -Eine neue Vorlage hinzuzufügen ist ein wertvoller Beitrag zur FastAPI-fastkit-Community. Ihre Ideen und Ihr Einsatz werden anderen Entwicklern enorm helfen! 🚀 +- Der Workflow „Template PR Inspection“ führt `scripts/inspect-changed-templates.py --offline` bei jedem Pull Request aus, der eine Datei unter `src/fastapi_fastkit/fastapi_project_template/` ändert, und kommentiert das Ergebnis im Pull Request. +- Der Workflow „Weekly Template Inspection“ inspiziert jedes Template mittwochs um 00:00 UTC, einschließlich der Prüfung auf veraltete Abhängigkeiten, und eröffnet ein Issue, wenn ein Template fehlschlägt. Er lässt sich auch von Hand für ausgewählte Templates starten. diff --git a/docs/de/contributing/translation-guide.md b/docs/de/contributing/translation-guide.md index da68bb17..bb80c051 100644 --- a/docs/de/contributing/translation-guide.md +++ b/docs/de/contributing/translation-guide.md @@ -1,367 +1,153 @@ # Übersetzungsleitfaden -Dieser Leitfaden erklärt, wie Sie Übersetzungen zur Dokumentation von FastAPI-fastkit beitragen. +Die Dokumentation erscheint in sieben Sprachen: Englisch (`en`), Koreanisch (`ko`), Japanisch (`ja`), Chinesisch (`zh`), Spanisch (`es`), Französisch (`fr`) und Deutsch (`de`). Diese Seite erklärt, was übersetzt wird, was auf Englisch bleibt, wie die generierten Tabellen, die Katalogtexte und die Seite des Web-Generators übersetzt werden und wie die Tests eine Übersetzung prüfen. -## Maßgebliche Referenz und Übersetzungsrichtlinie +## Englisch ist die Quelle -> **Englisch (`en`) ist die maßgebliche Referenz** für die FastAPI-fastkit-Dokumentation. Jede andere Sprache ist ein Übersetzungsziel, das dem Englischen um ein Release oder einzelne Seiten hinterherhängen kann. -> -> Wenn eine übersetzte Seite der englischen Seite widerspricht, **vertrauen Sie der englischen Seite**, bis die Übersetzung nachzieht. Übersetzungen werden in dem Vollständigkeitsgrad ausgeliefert, den die Mitwirkenden erreicht haben — eine teilweise Abdeckung ist normal und zu erwarten. +Jede Seite wird zuerst auf Englisch geschrieben, in `docs/en/`. Jede Sprache hat dieselbe Seite unter demselben Pfad in `docs//`, zum Beispiel `docs/en/learn/generate.md` und `docs/ko/learn/generate.md`. Jede Seite existiert in allen sieben Sprachen; wenn du eine englische Seite hinzufügst oder änderst, folgen die sechs Übersetzungen im selben Pull Request oder im nächsten. -Das nutzerseitige Pendant zu dieser Politik ist die Seite [Übersetzungsstatus](../reference/translation-status.md), die die tatsächliche Vollständigkeit jeder Sprache auflistet und erklärt, wie MkDocs noch nicht übersetzte Seiten rendert (kurz: sie fallen auf Englisch zurück). +Hat eine Sprache für eine Seite keine Datei, zeigt die Website im Menü dieser Sprache die englische Seite. Betrachte das als Lücke, die gefüllt werden muss, nicht als Normalzustand. -Die `CHANGELOG.md` im Stammverzeichnis des Repositorys bleibt ebenfalls als kanonische Releasehistorie auf Englisch. Falls eine Sprache eine `changelog.md`-Seite anbietet, sollte diese auf den kanonischen englischen Changelog verlinken oder ihn einbinden, statt einen separaten übersetzten Changelog zu pflegen — sofern die Projektrichtlinie das später nicht ändert. +`CHANGELOG.md` bleibt auf Englisch. Jede `docs//changelog.md` enthält nur `\{!CHANGELOG.md!}`, was die englische Datei einbindet. -Wenn Sie eine Übersetzung beitragen, aktualisieren Sie auch die Tabelle der Statusseite, damit Nutzer den Stand sehen können, ohne ihn aus dem Sprachumschalter erraten zu müssen. +## Was auf Englisch bleibt -## Übersicht +- Alles, was die Kommandozeile ausgibt oder abfragt: Abfragen, Meldungen, Tabellen, Hilfetexte und andere Ausgaben. Die Leser vergleichen die Seite mit ihrem Terminal. +- Befehle, Optionen, Dateinamen, Pfade, Code, Konfigurationsschlüssel und Paketnamen, innerhalb und außerhalb von Codeblöcken. +- Codeblöcke. Jeder umzäunte Block bleibt genau wie im Englischen, einschließlich Kommentaren und Beispielausgaben. +- Die generierten `cli`-Blöcke (die `--help`-Texte auf der Seite der CLI-Referenz) und die Titel der Prüfungen in der Tabelle `doctor-checks`. Das Skript erzeugt sie in jeder Sprache auf Englisch. +- Text in Bildern. Bilder sind gemeinsame Dateien in `docs/img/`; jede Sprache verwendet dasselbe Bild, verlinke es also und erstelle nie eine übersetzte Kopie. +- Linkziele und Überschriften-IDs. Manche Überschriften enden mit einer ID wie `{#features}`, weil andere Seiten und Weiterleitungen darauf verlinken. Übersetze den Text der Überschrift und behalte die ID bei. Die Überschriften mit Template-IDs auf der Seite der Beispielprojekte (`## fastapi-auth-jwt {#fastapi-auth-jwt}` und die anderen) bleiben, wie sie sind. -FastAPI-fastkit nutzt ein automatisiertes Übersetzungssystem auf KI-Basis, um die Dokumentation in mehrere Sprachen zu übersetzen. Das System: +Übersetze den Fließtext drumherum, die Überschriften, die Texte der Hinweisboxen, die Linktexte und den Alternativtext jedes Bildes. Lass relative Links, wie sie sind: Die Pfade sind in jeder Sprache gleich. -- Liest die Quelldokumentation auf Englisch -- Übersetzt Inhalte über KI-APIs (OpenAI oder Anthropic) -- Speichert Übersetzungen in sprachspezifischen Verzeichnissen -- Erstellt GitHub-Pull-Requests zur Überprüfung +## Generierte Blöcke -Die Automatisierung liefert einen Ausgangspunkt; eine menschliche Überprüfung ist vor dem Merge weiterhin erforderlich. KI-generierte Übersetzungen sollten in ihren PRs als „draft" markiert und von einem fließenden Sprecher überprüft werden, bevor sie gemergt werden. +Manche Tabellen werden aus dem Katalog und dem CLI erzeugt. In der Seite stehen sie zwischen zwei Kommentarzeilen: -## Unterstützte Sprachen - -Dies sind die Sprachen, für die die Dokumentations-Site derzeit einen Build erzeugt. Die bloße Konfiguration eines Sprach-Build-Ziels **bedeutet nicht**, dass die Seiten dieser Sprache bereits übersetzt sind — den tatsächlichen Stand sehen Sie im [Übersetzungsstatus](../reference/translation-status.md). - -- 🇰🇷 Koreanisch (ko) -- 🇯🇵 Japanisch (ja) -- 🇨🇳 Chinesisch (zh) -- 🇪🇸 Spanisch (es) -- 🇫🇷 Französisch (fr) -- 🇩🇪 Deutsch (de) - -## Voraussetzungen - -### 1. Abhängigkeiten für Übersetzungen installieren - -```bash -# Mit pip installieren -pip install openai anthropic - -# Oder mit pdm -pdm install -G translation -``` - -### 2. API-Schlüssel einrichten - -Sie benötigen einen API-Schlüssel von OpenAI oder Anthropic: - -```bash -# Für OpenAI -export TRANSLATION_API_KEY="sk-..." - -# Oder für Anthropic -export TRANSLATION_API_KEY="sk-ant-..." +```markdown + +... + ``` -### 3. GitHub CLI installieren (optional) - -Für die automatische PR-Erstellung: - -```bash -# macOS -brew install gh - -# Linux -curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | sudo dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg -echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null -sudo apt update -sudo apt install gh - -# Anmelden -gh auth login -``` - -## Nutzung - -### Mit Make-Befehlen (empfohlen) +Kopiere die zwei Kommentarzeilen aus der englischen Seite und übersetze oder bearbeite nie, was dazwischen steht. Erzeuge dann die Blöcke deiner Sprache: -Der einfachste Weg, Übersetzungen auszuführen: - -```bash -# Alle Dokumente in alle Sprachen übersetzen -make translate - -# In eine bestimmte Sprache übersetzen -make translate LANG=ko - -# API-Anbieter und Modell festlegen -make translate LANG=ko PROVIDER=openai MODEL=gpt-4 -make translate LANG=ko PROVIDER=github MODEL=gpt-4o-mini +```console +$ python scripts/docs_blocks.py --lang ko +$ python scripts/docs_blocks.py --check ``` -### Mit dem Skript direkt +Katalogblöcke (`levels`, `features`, `rules`, `package-managers`, `examples`, `concepts`) nehmen ihre Texte aus dem Katalog-Overlay der Sprache der Seite, das weiter unten beschrieben ist. Die festen Wörter der Tabellen stammen aus der Tabelle `HEADINGS` am Anfang von `scripts/docs_blocks.py`: Spaltenüberschriften, kurze Sätze wie `{when} needs {require}.` sowie die Satzzeichen und Verbindungswörter von Listen (`separator`, `join_or`, `join_and`), damit eine Sprache wie Japanisch die Leerzeichen um sie herum weglassen kann. Eine übersetzte Sprache braucht einen Eintrag mit jedem Schlüssel von `en` und denselben `{placeholders}`; eine Sprache ohne Eintrag bekommt die englischen Wörter. Die `cli`-Blöcke und die Titel der Prüfungen in der Tabelle `doctor-checks` bleiben auf Englisch, weil sie der eigene Text der Kommandozeile sind. -#### Die gesamte Dokumentation übersetzen +## Katalog-Overlays {#catalog-overlays} -Die gesamte Dokumentation in alle unterstützten Sprachen übersetzen: +Beschreibungen der Stufen, Bezeichnungen und Zusammenfassungen der Features, Regelmeldungen, Konzepttitel und die Texte der Liste „Next steps“ stammen aus dem Katalog. Der englische Text steht in `src/fastapi_fastkit/catalog/catalog.toml`; jede Sprache hat ein Overlay unter `src/fastapi_fastkit/catalog/i18n/.toml` mit denselben Schlüsseln: -```bash -python scripts/translate.py --api-provider openai +```toml title="src/fastapi_fastkit/catalog/i18n/ko.toml" +[levels."hello"] +label = "Hello" +description = "main.py 하나에 엔드포인트 3개와 메모리 데이터가 들어 있고, 테스트도 함께 제공됩니다." ``` -### In eine bestimmte Sprache übersetzen +Die Overlays speisen die generierten Blöcke und die Seite des Web-Generators. Um jeden zu übersetzenden Schlüssel zu sehen, gibst du das englische Grundgerüst aus: -Nur ins Koreanische übersetzen: - -```bash -python scripts/translate.py --target-lang ko --api-provider openai +```console +$ python -m fastapi_fastkit.catalog strings +[levels."hello"] +label = "Hello" +description = "One main.py: 3 endpoints, in-memory data, tests." +... ``` -### Bestimmte Dateien übersetzen +Regeln, die `tests/test_catalog` prüft: -Nur bestimmte Dokumentationsdateien übersetzen: +- Ein Overlay übersetzt jeden Text des Grundgerüsts und hat keinen Schlüssel, den der Katalog nicht hat. +- IDs, Paketnamen und URLs werden nie übersetzt, und Code-Spans in Backticks bleiben genau wie im Englischen. +- Platzhalter wie `{services}` bleiben erhalten, mit denselben Namen. +- Ein Text darf nur bei den wenigen Namen, die in `tests/test_catalog/test_overlays.py` aufgeführt sind, mit dem Englischen übereinstimmen (zum Beispiel bei der Bezeichnung `Hello` der Stufe). -```bash -python scripts/translate.py \ - --target-lang ko \ - --files user-guide/installation.md user-guide/quick-start.md \ - --api-provider openai -``` +## Seite des Web-Generators -### PR-Erstellung überspringen +`docs//start/web-generator.md` ist eine Kopie der englischen Seite, in der du nur Folgendes übersetzt: -Übersetzen, ohne eine GitHub-PR zu erstellen: +- die H1 und den einleitenden Absatz (behalte den Pyodide-Link und den Code-Span `fastkit init ... --no-venv` bei); +- den Text von `