diff --git a/CHANGELOG.md b/CHANGELOG.md index bd6fc5f0..309fc128 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,92 @@ # Changelog +## v2.0.0 + +### Breaking changes + +Every template except `fastapi-hello`, the code `fastkit init` generates for its options, and `fastkit addroute` output now share one HTTP contract: + +| | 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` | + +Every 401 carries `WWW-Authenticate`, and each project reads its configuration from one settings module that loads `.env`. + +- **Removed templates:** `fastapi-async-crud`, `fastapi-dockerized` and `fastapi-psql-orm` are gone, together with their tutorials. Projects generated from them keep working, and `fastkit doctor` still recognises their example secrets. Use `fastapi-sqlmodel` (async; SQLite, PostgreSQL or MySQL) or `fastapi-default` for new projects. +- **Secrets outside development:** every template and generated settings module now refuses to start with any `ENVIRONMENT` other than `development` (`staging` or `production`) and a missing, example, or shorter than 32-byte `SECRET_KEY`. In `development` an example key only warns. +- **`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`, and `/auth/users` becomes `GET /api/v1/users` (superusers only). `/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 `Authorization` can carry a user token and write tools work in API-key mode. +- **`fastapi-auth-jwt`:** a rejected refresh token returns 400 `{"error": "invalid_grant"}` instead of 401; token responses add `expires_in`; `GET /api/v1/users` returns the page envelope. +- **`fastapi-sqlmodel`:** `ItemPublic` is renamed `ItemRead`. +- **`fastapi-llm-agent`:** the server generates conversation ids. Send `conversation_id` only to continue a conversation; an unknown id returns 404. +- **`fastapi-custom-response`:** errors, including validation errors and unhandled exceptions, use the response envelope; 500 responses no longer contain exception text. +- **`init` Session-based / OAuth2:** `GET /auth/me` moves to `GET /api/v1/users/me`, and logout returns 204. +- **`init` FastAPI-Users** needs PostgreSQL, MySQL or SQLite; other database choices are rejected. +- **`init` WebSocket:** the connection list moves from `/api/v1/ws/connections` to `/api/v1/connections`; `/ws` is unchanged. +- **CLI:** `startdemo` exits with status 1 when it refuses to run or fails, including an in-place overwrite without a terminal or `--yes`. `addroute` exits with status 1 on errors and refuses route names that are not lower-case ASCII. `deleteproject` exits with status 1 when the project does not exist, is not a fastkit project or cannot be deleted (declining the confirmation still exits 0). `runserver` in a project without `.venv` exits with status 1 unless you choose to continue with the current Python. +- **`init` utilities menu:** CORS and Pagination are no longer offered, because every project includes them; the menu is now 1 = Rate-Limiting, 2 = WebSocket. Saved configs that list them still load. + +### CLI + +- New `fastkit doctor [PATH]` checks a generated project for problems that newer templates fixed: a committed or unignored `.env`, a missing `.env.example`, example secrets, an MCP server without authentication, CORS `*` with credentials, Prometheus set up inside the lifespan, `sqlalchemy` without `greenlet`, CRLF scripts, a missing `.gitattributes`, an old `requires-python`, a pinned pre-commit Python, a commit after `yield`, `SlowAPIMiddleware`, Motor, the old pagination demo router and configuration read outside the settings module. It never prints secret values. +- `doctor --fix` shows the diff of the safe fixes and asks once (`--yes` skips the question and is required without a terminal); `--dry-run` / `--diff` only previews. `--format json` is for CI, and `--force` checks projects generated before 1.4.0. Exit status: 0 no problem left, 1 problems remain, 2 doctor could not run. +- `fastkit addroute` generates a typed CRUD resource with tests in both layouts (schemas, 201 with `Location`, 204, 404, paginated list) and adds `core/pagination.py` to older projects. The domain layout is chosen when the project has a `domains/` package. New options: `--entity` (class name), `--dry-run` (list files) and `--diff` (show changes). It refuses a route whose files already exist. +- `startdemo -y` also skips the creation prompt. `runserver` rejects an invalid `app_module` in `[tool.fastapi-fastkit]`. +- `startdemo` checks the template name before it asks anything, suggests close matches and points to `fastkit list-templates`; the internal template path is shown only with `--debug`. +- `runserver` in a project without `.venv` prints the commands that create it for the project's package manager (for PDM, ones that keep the `.venv` inside the project) before offering to continue. If you continue, it runs the uvicorn of the Python that runs fastkit and exits with a clear message if that Python has none. +- `addroute` on a real single-file project such as `fastapi-hello` explains how to extend it by hand instead of adding packages. Projects that keep `main.py` at the root with their code in packages are handled as before. +- `doctor` passed checks say only what was verified, with no severity, and checks that do not apply to a project (secrets, settings, `.gitattributes`) are skipped. JSON output is unchanged. +- `list-features` shows the utility and tooling options that `init` offers and lists CORS and pagination as built into every project. +- Projects created with Poetry now get a working virtual environment and install with `poetry install`; fastkit sets `package-mode = false` so Poetry installs the dependencies without packaging the application. Poetry 2 or later is required: with an older Poetry, fastkit stops before creating anything, reports the version it found and explains how to upgrade or choose another package manager. +- Projects created with PDM now get their `.venv` inside the project even when PDM is configured with `venv.in_project = false`, and `fastapi-hello` installs with PDM without being built as a package. +- `list-templates` lists templates from the simplest to the most involved, in the same order on every operating system. `fastkit --help` has a one-sentence description and a "Start here" section. + +### `fastkit init` options + +- **JWT** generates an OAuth2 password flow: `POST /api/v1/auth/register`, `POST /api/v1/auth/token` and `GET /api/v1/users/me`, with users stored in the selected SQL database or MongoDB (in memory otherwise). +- **FastAPI-Users** generates working routes (`/api/v1/auth/jwt/*`, `/api/v1/auth/register`, `/api/v1/users/*`) 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` (refused outside development). **OAuth2** requires `OAUTH_REDIRECT_BASE_URL` outside development. +- **CORS and Pagination** are built into every project and no longer offered in the menu; `fastapi-pagination` is no longer installed. +- **Rate-Limiting** applies `RATE_LIMIT_DEFAULT` to every route and the stricter `RATE_LIMIT_AUTH` to the auth endpoints, using `limits` instead of slowapi. +- **MongoDB** uses PyMongo's async client instead of Motor. The SQL session dependency no longer commits; services commit. +- `classic-layered` and `domain-starter` wire every selected feature into the template's `main.py`. +- Generated tests run against in-memory SQLite and do not export telemetry. +- **Docker:** the image runs as a non-root user and has a healthcheck, `.dockerignore` is generated, compose points the app at its services, and `.env` is supplied at run time instead of copied into the image. **Loguru** is now configured at startup. + +### Templates + +- New `fastapi-hello`: a single `main.py` and its tests, for people who have never written a FastAPI app. `POST /items` stores an item in memory and returns it with an id, and `GET /items/{item_id}` returns it or 404. It has no settings module and no secrets. +- `fastapi-sqlmodel` runs on SQLite, PostgreSQL or MySQL, selected by `DATABASE_URL`. Install the `postgresql` or `mysql` driver extra, start a local server with the new docker compose file, and use the migrations, which work on all three. A malformed `DATABASE_URL` is reported without echoing credentials. +- `fastapi-mcp`: item reads are public; PUT and PATCH work as specified. +- `fastapi-auth-jwt`: login, register and refresh are rate limited (`AUTH_RATE_LIMIT_*`); timestamps are timezone-aware (new migration); `GET /api/v1/users/{user_id}` (superusers only) is added. +- `fastapi-sqlmodel`: timestamps are timezone-aware (new migration) and PUT is added. +- `fastapi-llm-agent`: the SSE stream is declared in OpenAPI, the calculator tool and the conversation store are 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, write atomically, and their tests no longer overwrite the shipped data. +- Unused dependencies and `setup.cfg` files are removed. Template Dockerfiles run as a non-root user and ship a `.dockerignore`. + +### Documentation + +- The English docs cover the changes above, including a `fastkit doctor` section in the CLI reference and the conventions a new template must follow. +- The translated locales are not re-synced in this release; `reference/translation-status` lists the affected pages. + +### 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:** new images set `ENVIRONMENT=production` and do not contain `.env`; pass `SECRET_KEY` (at least 32 bytes) and the other settings at run time, e.g. `docker run --env-file .env ...`. +3. **`fastapi-auth-jwt` and `fastapi-sqlmodel` projects that adopt the new template code:** run `alembic upgrade head` for the new migration. +4. **Projects from the removed templates** need no change. To move to PostgreSQL or MySQL with `fastapi-sqlmodel`, set `DATABASE_URL` and install the matching driver extra. +5. **Saved `--config` files** with the CORS or Pagination option still work. + ## v1.5.2 (2026-12-01) ### Security diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b7933cd6..b46df962 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -238,10 +238,10 @@ When adding a new FastAPI template project, follow these guidelines: 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,7 +249,9 @@ 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: @@ -258,11 +260,16 @@ template-name/ - `.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` + +See [Template Creation Guide](docs/en/contributing/template-creation-guide.md) for the full rules and the conventions checklist. ### Security Requirements diff --git a/Makefile b/Makefile index 3970ebc6..3661f584 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)" diff --git a/README.md b/README.md index e608e813..2437dabe 100644 --- a/README.md +++ b/README.md @@ -86,7 +86,7 @@ fastkit init --interactive - **Caching**: Redis, fastapi-cache2 - **Monitoring**: Loguru, OpenTelemetry, Prometheus - **Testing**: Basic (pytest), Coverage, Advanced (with faker, factory-boy) - - **Utilities**: CORS, Rate-Limiting, Pagination, WebSocket + - **Utilities**: Rate-Limiting, WebSocket (CORS and pagination are built into every project) - **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) @@ -94,12 +94,12 @@ fastkit init --interactive - **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 + - `main.py` regenerated from selected features for `minimal` / `single-module`; for `classic-layered` / `domain-starter` the shipped `main.py` is kept and every feature is wired into it + - Database module and authentication package at preset-specific paths, with routes under `/api/v1` - 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 + - `GET /health` on every generated project, and `GET /ready` when it has a database or cache + - Real working code with tests — not just installed packages — for background tasks, caching, WebSocket, rate limiting, OpenTelemetry, and JWT, FastAPI-Users, 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 @@ -113,14 +113,30 @@ fastkit startdemo [TEMPLATE] [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` + - Refuses to run if the target project directory already exists (`--dry-run` excepted), and then exits with status 1 +- Tip: List available templates with `fastkit list-templates` (simplest first). A misspelled name suggests the closest match +- New to FastAPI? Start with `fastkit startdemo fastapi-hello`: one `main.py` with three endpoints and their tests ### Add a new route ```console -fastkit addroute +fastkit addroute [project_dir] [OPTIONS] ``` -- What it does: Adds a new API route to the specified project +- What it does: Adds a CRUD resource with tests (paginated list, create, read, replace, update, delete) under `/api/v1/` +- Key options: + - `--layout` [classic-layer|domain]: defaults to `domain` for `domain-starter` projects and projects with a `domains/` package + - `--entity`: class name for the resource (e.g. `Order`) + - `--dry-run` / `--diff`: preview the files and changes without writing anything + +### Check an existing project +```console +fastkit doctor [PATH] [OPTIONS] +``` +- What it does: Checks a generated project for problems that newer fastkit versions fixed (committed `.env`, example secrets, CORS `*` with credentials, CRLF scripts, and more); upgrading fastkit never changes an existing project +- Key options: + - `--fix`: apply the safe fixes after showing the diff and asking once (`--yes` skips the question) + - `--dry-run` / `--diff`: show what `--fix` would change + - `--format json`: machine-readable report for CI + - Exit status: 0 no problem, 1 problems remain, 2 doctor could not run ### Run the development server ```console @@ -139,25 +155,24 @@ Available templates: | Template | Description | Notes | |---|---|---| +| [`fastapi-hello`](src/fastapi_fastkit/fastapi_project_template/fastapi-hello/README.md-tpl) | Smallest FastAPI app: three endpoints, one pydantic model, one test file | Start here | | [`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-sqlmodel`](src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/README.md-tpl) | Async SQLModel + Alembic migrations + generic CRUD with pagination; SQLite, PostgreSQL or MySQL through one `DATABASE_URL` | 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. +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 ``` +Exits with status 1 when the project does not exist, is not a fastkit project or cannot be deleted; declining the confirmation exits with status 0. ## Documentation diff --git a/docs/de/contributing/development-setup.md b/docs/de/contributing/development-setup.md index 9f63f89d..4e432105 100644 --- a/docs/de/contributing/development-setup.md +++ b/docs/de/contributing/development-setup.md @@ -322,13 +322,11 @@ FastAPI-fastkit/ │ │ ├── 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-hello/ │ │ │ ├── fastapi-mcp/ -│ │ │ ├── fastapi-psql-orm/ │ │ │ ├── fastapi-single-module/ │ │ │ └── modules/ │ │ │ ├── api/ diff --git a/docs/de/index.md b/docs/de/index.md index 50ec32d8..0a795d92 100644 --- a/docs/de/index.md +++ b/docs/de/index.md @@ -507,21 +507,20 @@ Um die Liste der verfügbaren FastAPI-Demos anzuzeigen, prüfen Sie mit: ```console $ fastkit list-templates Available Templates -┌────────────────────────┬───────────────────────────────────────────────────────┐ -│ fastapi-custom-response│ Async Item Management API with Custom Response System │ -│ fastapi-mcp │ FastAPI MCP Project │ -│ fastapi-domain-starter │ FastAPI Domain Starter │ -│ fastapi-dockerized │ Dockerized FastAPI Item Management API │ -│ fastapi-empty │ Minimal FastAPI Template │ -│ fastapi-async-crud │ Async Item Management API Server │ -│ fastapi-psql-orm │ Dockerized FastAPI Item Management API with │ -│ │ PostgreSQL │ -│ fastapi-default │ Simple FastAPI Project │ -│ fastapi-single-module │ FastAPI Single Module Template │ -│ fastapi-auth-jwt │ FastAPI JWT Authentication │ -│ fastapi-sqlmodel │ FastAPI SQLModel │ -│ fastapi-llm-agent │ FastAPI LLM Agent │ -└────────────────────────┴───────────────────────────────────────────────────────┘ +┌───────────────────────────┬──────────────────────────────────────────────────┐ +│fastapi-hello │ Smallest FastAPI app: three endpoints, one model,│ +│ │ their tests │ +│fastapi-empty │ Minimal FastAPI Template │ +│fastapi-single-module │ FastAPI Single Module Template │ +│fastapi-default │ Simple FastAPI Project │ +│fastapi-domain-starter │ FastAPI Domain Starter │ +│fastapi-custom-response │ Async Item Management API with Custom Response │ +│ │ System │ +│fastapi-auth-jwt │ FastAPI JWT Authentication │ +│fastapi-sqlmodel │ FastAPI SQLModel │ +│fastapi-mcp │ FastAPI MCP Project │ +│fastapi-llm-agent │ FastAPI LLM Agent │ +└───────────────────────────┴──────────────────────────────────────────────────┘ ``` @@ -530,20 +529,18 @@ Verfügbare Vorlagen: | Vorlage | Beschreibung | Hinweise | |---|---|---| +| [`fastapi-hello`](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fastapi_project_template/fastapi-hello/README.md-tpl) | Kleinste FastAPI-App: drei Endpunkte, ein pydantic-Modell, eine Testdatei | Hier beginnen | | [`fastapi-default`](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fastapi_project_template/fastapi-default/README.md-tpl) | Einfaches FastAPI-Projekt mit klassischem Schichten-Layout | Gute erste Wahl | | [`fastapi-empty`](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/README.md-tpl) | Minimale FastAPI-Vorlage | Basis für das Preset `minimal` | | [`fastapi-single-module`](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/README.md-tpl) | FastAPI-App in einer Datei | Basis für das Preset `single-module` | | [`fastapi-domain-starter`](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/README.md-tpl) | Domänenorientierter, pyproject-first Starter für mittelgroße APIs | Basis für das Preset `domain-starter` | | [`fastapi-auth-jwt`](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/README.md-tpl) | JWT-Authentifizierung mit Refresh-Token-Rotation, argon2-Hashing und Scopes | Neu in v1.4.0 | -| [`fastapi-sqlmodel`](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/README.md-tpl) | Asynchrones SQLModel + Alembic-Migrationen + generisches CRUD mit Paginierung | Neu in v1.4.0 | +| [`fastapi-sqlmodel`](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/README.md-tpl) | Asynchrones SQLModel + Alembic-Migrationen + generisches CRUD mit Paginierung; SQLite, PostgreSQL oder MySQL über eine einzige `DATABASE_URL` | Neu in v1.4.0 | | [`fastapi-llm-agent`](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/README.md-tpl) | Streaming-Claude-Chat-Agent (SSE) mit Tool-Call-Schleife | Neu in v1.4.0 | | [`fastapi-mcp`](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/README.md-tpl) | FastAPI-App, die als MCP-Server bereitgestellt wird | | -| [`fastapi-psql-orm`](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/README.md-tpl) | Item-Management-API mit PostgreSQL, SQLModel, Alembic und docker-compose | Erfordert Docker | | [`fastapi-custom-response`](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/README.md-tpl) | Item-Management-API mit eigener Antwort-Hülle, Fehlerbehandlung und Paginierung | | -| [`fastapi-async-crud`](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/README.md-tpl) | Asynchrone Item-Management-API | **Veraltet** — verwenden Sie `fastapi-sqlmodel` | -| [`fastapi-dockerized`](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/README.md-tpl) | Dockerisierte Item-Management-API | **Veraltet** — verwenden Sie `fastapi-default` mit der Docker-Option in `init --interactive` | -Veraltete Vorlagen funktionieren weiterhin, werden aber nicht mehr als Ausgangspunkt empfohlen. Eine Entscheidungshilfe finden Sie unter [Welchen Starter soll ich wählen?](user-guide/choosing-a-starter.md). +Eine Entscheidungshilfe finden Sie unter [Welchen Starter soll ich wählen?](user-guide/choosing-a-starter.md). ## Dokumentation @@ -563,15 +560,12 @@ Lernen Sie die FastAPI-Entwicklung anhand praktischer Anwendungsfälle mit unser ### 📖 Kerntutorials - **[Einen einfachen API-Server bauen](tutorial/basic-api-server.md)** — erstellen Sie Ihren ersten FastAPI-Server mit der Vorlage `fastapi-default` -- **[Eine asynchrone CRUD-API bauen](tutorial/async-crud-api.md)** — entwickeln Sie eine leistungsstarke asynchrone API mit der Vorlage `fastapi-async-crud` - **[Domänenorientiertes Projekt (Domain Starter)](tutorial/domain-starter.md)** — bauen Sie eine mittelgroße API mit der Vorlage `fastapi-domain-starter`, dem empfohlenen modernen Standard - **[JWT-Authentifizierung](tutorial/auth-jwt.md)** — fügen Sie mit der Vorlage `fastapi-auth-jwt` echte Konten hinzu: rotierende Refresh-Tokens, argon2id-Hashing, Rollen- und Scope-Guards ### 🗄️ Datenbank und Infrastruktur -- **[Integration einer Datenbank](tutorial/database-integration.md)** — nutzen Sie PostgreSQL + SQLAlchemy mit der Vorlage `fastapi-psql-orm` - **[Asynchrone Persistenz mit SQLModel](tutorial/sqlmodel.md)** — asynchrones SQLModel, Alembic-Migrationen, eine generische CRUD-Basis und paginierte Listen mit der Vorlage `fastapi-sqlmodel` -- **[Docker-Containerisierung und Deployment](tutorial/docker-deployment.md)** — richten Sie eine produktionsreife Deployment-Umgebung mit der Vorlage `fastapi-dockerized` ein *(veraltete Vorlage — für bestehende Nutzer beibehalten)* ### ⚡ Erweiterte Funktionen diff --git a/docs/de/reference/faq.md b/docs/de/reference/faq.md index b9f71db0..a189c457 100644 --- a/docs/de/reference/faq.md +++ b/docs/de/reference/faq.md @@ -320,17 +320,21 @@ async def upload_file(file: UploadFile = File(...)): ```console $ fastkit list-templates - Available Templates -┌─────────────────────────┬───────────────────────────────────┐ -│ fastapi-default │ Simple FastAPI Project │ -│ fastapi-async-crud │ Async Item Management API Server │ -│ fastapi-custom-response │ Custom Response System │ -│ fastapi-dockerized │ Dockerized FastAPI API │ -│ fastapi-empty │ Minimal FastAPI Project │ -│ fastapi-mcp │ MCP (Model Context Protocol) API │ -│ fastapi-psql-orm │ PostgreSQL FastAPI API │ -│ fastapi-single-module │ Single-file FastAPI Project │ -└─────────────────────────┴───────────────────────────────────┘ + Available Templates +┌───────────────────────────┬──────────────────────────────────────────────────┐ +│fastapi-hello │ Smallest FastAPI app: three endpoints, one model,│ +│ │ their tests │ +│fastapi-empty │ Minimal FastAPI Template │ +│fastapi-single-module │ FastAPI Single Module Template │ +│fastapi-default │ Simple FastAPI Project │ +│fastapi-domain-starter │ FastAPI Domain Starter │ +│fastapi-custom-response │ Async Item Management API with Custom Response │ +│ │ System │ +│fastapi-auth-jwt │ FastAPI JWT Authentication │ +│fastapi-sqlmodel │ FastAPI SQLModel │ +│fastapi-mcp │ FastAPI MCP Project │ +│fastapi-llm-agent │ FastAPI LLM Agent │ +└───────────────────────────┴──────────────────────────────────────────────────┘ ``` @@ -344,7 +348,7 @@ $ fastkit list-templates ```console $ fastkit startdemo Enter the project name: my-blog -Select template: fastapi-psql-orm +Select template: fastapi-hello ``` @@ -447,8 +451,8 @@ $ fastkit runserver --reload $ pip install gunicorn $ gunicorn src.main:app -w 4 -k uvicorn.workers.UvicornWorker -# Or use Docker with the fastapi-dockerized template -$ fastkit startdemo # Select fastapi-dockerized +# Or use Docker with a template that ships a Dockerfile +$ fastkit startdemo fastapi-sqlmodel $ docker build -t my-app . $ docker run -p 8000:8000 my-app ``` diff --git a/docs/de/reference/template-quality-assurance.md b/docs/de/reference/template-quality-assurance.md index 44ff401a..0dc6d8ca 100644 --- a/docs/de/reference/template-quality-assurance.md +++ b/docs/de/reference/template-quality-assurance.md @@ -68,9 +68,7 @@ $ pytest tests/test_templates/test_all_templates.py -v # Results show all discovered templates PASSED tests/test_templates/test_all_templates.py::TestAllTemplates::test_template_creation[fastapi-default] -PASSED tests/test_templates/test_all_templates.py::TestAllTemplates::test_template_creation[fastapi-async-crud] -PASSED tests/test_templates/test_all_templates.py::TestAllTemplates::test_template_creation[fastapi-dockerized] -PASSED tests/test_templates/test_all_templates.py::TestAllTemplates::test_template_creation[fastapi-psql-orm] +PASSED tests/test_templates/test_all_templates.py::TestAllTemplates::test_template_creation[fastapi-hello] ``` ### Umfassende Testabdeckung @@ -163,7 +161,7 @@ Für Entwicklung und Debugging können Sie Vorlagen manuell mit unserem lokalen $ python scripts/inspect-templates.py # Inspect specific templates -$ python scripts/inspect-templates.py --templates fastapi-default,fastapi-async-crud +$ python scripts/inspect-templates.py --templates fastapi-default,fastapi-hello # Verbose output with detailed information $ python scripts/inspect-templates.py --verbose @@ -206,7 +204,7 @@ $ make inspect-templates $ make inspect-templates-verbose # Inspect specific templates -$ make inspect-template TEMPLATES="fastapi-default,fastapi-async-crud" +$ make inspect-template TEMPLATES="fastapi-default,fastapi-hello" ``` ## Ergebnisse der Inspektion @@ -220,12 +218,8 @@ $ make inspect-template TEMPLATES="fastapi-default,fastapi-async-crud" Beim Ausführen der Vorlagen-Inspektion sehen Sie eine Ausgabe wie diese: ```console -📋 Found 6 templates to inspect: fastapi-async-crud, fastapi-custom-response, fastapi-default, fastapi-dockerized, fastapi-empty, fastapi-psql-orm +📋 Found 4 templates to inspect: fastapi-custom-response, fastapi-default, fastapi-empty, fastapi-hello ============================================================ -🔍 Inspecting template: fastapi-async-crud - Path: /path/to/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud -✅ fastapi-async-crud: PASSED ----------------------------------------- 🔍 Inspecting template: fastapi-custom-response Path: /path/to/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response ✅ fastapi-custom-response: PASSED @@ -233,8 +227,8 @@ Beim Ausführen der Vorlagen-Inspektion sehen Sie eine Ausgabe wie diese: ... ============================================================ 📊 INSPECTION SUMMARY - Total templates: 6 - ✅ Passed: 6 + Total templates: 4 + ✅ Passed: 4 ❌ Failed: 0 🎉 All templates passed inspection! 📄 Results saved to: template_inspection_results.json diff --git a/docs/de/tutorial/async-crud-api.md b/docs/de/tutorial/async-crud-api.md deleted file mode 100644 index d0ae5338..00000000 --- a/docs/de/tutorial/async-crud-api.md +++ /dev/null @@ -1,665 +0,0 @@ -# Asynchrone CRUD-APIs bauen - -Lernen Sie, wie Sie hochperformante CRUD-APIs mit den asynchronen Verarbeitungsmöglichkeiten von FastAPI bauen. In diesem Tutorial implementieren wir asynchrone Datei-I/O und effiziente Datenverarbeitung mit der Vorlage `fastapi-async-crud`. - -## Was Sie in diesem Tutorial lernen - -- Asynchrone FastAPI-Anwendungen verstehen -- Asynchrone CRUD-Operationen mit der `async/await`-Syntax -- Asynchrone Dateiverarbeitung mit aiofiles -- Asynchrone Tests schreiben und ausführen -- Techniken zur Leistungsoptimierung - -## Voraussetzungen - -- Das [Tutorial Einfacher API-Server](basic-api-server.md) abgeschlossen -- Verständnis der Grundkonzepte von Pythons `async/await` -- FastAPI-fastkit installiert - -## Warum asynchrone Verarbeitung nötig ist - -Verstehen wir den Unterschied zwischen synchroner und asynchroner Verarbeitung: - -### Synchrone Verarbeitung - -```python -def process_items(): - item1 = read_file("item1.json") # Wait 2 seconds - item2 = read_file("item2.json") # Wait 2 seconds - item3 = read_file("item3.json") # Wait 2 seconds - return [item1, item2, item3] # Total: 6 seconds -``` - -### Asynchrone Verarbeitung - -```python -async def process_items(): - item1_task = read_file_async("item1.json") # Start concurrently - item2_task = read_file_async("item2.json") # Start concurrently - item3_task = read_file_async("item3.json") # Start concurrently - - items = await asyncio.gather(item1_task, item2_task, item3_task) - return items # Total: 2 seconds -``` - -## Schritt 1: Ein asynchrones CRUD-Projekt erstellen - -Erstellen Sie ein Projekt mit der Vorlage `fastapi-async-crud`: - -
- -```console -$ fastkit startdemo fastapi-async-crud -Enter the project name: async-todo-api -Enter the author name: Developer Kim -Enter the author email: developer@example.com -Enter the project description: Asynchronous todo management API -Deploying FastAPI project using 'fastapi-async-crud' template - - Project Information -┌──────────────┬─────────────────────────────────────────┐ -│ Project Name │ async-todo-api │ -│ Author │ Developer Kim │ -│ Author Email │ developer@example.com │ -│ Description │ Asynchronous todo management API │ -└──────────────┴─────────────────────────────────────────┘ - - Template Dependencies -┌──────────────┬───────────────────┐ -│ Dependency 1 │ fastapi │ -│ Dependency 2 │ uvicorn │ -│ Dependency 3 │ pydantic │ -│ Dependency 4 │ pydantic-settings │ -│ Dependency 5 │ aiofiles │ -│ Dependency 6 │ pytest-asyncio │ -└──────────────┴───────────────────┘ - -Select package manager (pip, uv, pdm, poetry) [uv]: uv -Do you want to proceed with project creation? [y/N]: y - -✨ FastAPI project 'async-todo-api' from 'fastapi-async-crud' has been created successfully! -``` - -
- -## Schritt 2: Projektstruktur analysieren - -Sehen wir uns die wichtigsten Unterschiede des generierten Projekts an: - -``` -async-todo-api/ -├── src/ -│ ├── main.py # Asynchronous FastAPI application -│ ├── api/ -│ │ └── routes/ -│ │ └── items.py # Asynchronous CRUD endpoints -│ ├── crud/ -│ │ └── items.py # Asynchronous data processing logic -│ ├── schemas/ -│ │ └── items.py # Data models (same) -│ ├── mocks/ -│ │ └── mock_items.json # JSON file database -│ └── core/ -│ └── config.py # Configuration file -└── tests/ - ├── conftest.py # Asynchronous test configuration - └── test_items.py # Asynchronous test cases -``` - -### Wichtige Unterschiede - -1. **aiofiles**: asynchrone Datei-I/O-Verarbeitung -2. **pytest-asyncio**: Unterstützung für asynchrone Tests -3. **async/await-Muster**: alle CRUD-Operationen asynchron implementiert - -## Schritt 3: Die asynchrone CRUD-Logik verstehen - -### Asynchrone Datenverarbeitung (`src/crud/items.py`) - -```python -import json -import asyncio -from typing import List, Optional -from aiofiles import open as aio_open -from pathlib import Path - -from src.schemas.items import Item, ItemCreate, ItemUpdate - -class AsyncItemCRUD: - def __init__(self, data_file: str = "src/mocks/mock_items.json"): - self.data_file = Path(data_file) - - async def _read_data(self) -> List[dict]: - """Asynchronously read data from JSON file""" - try: - async with aio_open(self.data_file, 'r', encoding='utf-8') as f: - content = await f.read() - return json.loads(content) - except FileNotFoundError: - return [] - - async def _write_data(self, data: List[dict]) -> None: - """Asynchronously write data to JSON file""" - async with aio_open(self.data_file, 'w', encoding='utf-8') as f: - await f.write(json.dumps(data, indent=2, ensure_ascii=False)) - - async def get_items(self) -> List[Item]: - """Retrieve all items (asynchronous)""" - data = await self._read_data() - return [Item(**item) for item in data] - - async def get_item(self, item_id: int) -> Optional[Item]: - """Retrieve specific item (asynchronous)""" - data = await self._read_data() - item_data = next((item for item in data if item["id"] == item_id), None) - return Item(**item_data) if item_data else None - - async def create_item(self, item: ItemCreate) -> Item: - """Create new item (asynchronous)""" - data = await self._read_data() - new_id = max([item["id"] for item in data], default=0) + 1 - - new_item = Item(id=new_id, **item.dict()) - data.append(new_item.dict()) - - await self._write_data(data) - return new_item - - async def update_item(self, item_id: int, item_update: ItemUpdate) -> Optional[Item]: - """Update item (asynchronous)""" - data = await self._read_data() - - for i, item in enumerate(data): - if item["id"] == item_id: - update_data = item_update.dict(exclude_unset=True) - data[i].update(update_data) - await self._write_data(data) - return Item(**data[i]) - - return None - - async def delete_item(self, item_id: int) -> bool: - """Delete item (asynchronous)""" - data = await self._read_data() - original_length = len(data) - - data = [item for item in data if item["id"] != item_id] - - if len(data) < original_length: - await self._write_data(data) - return True - - return False -``` - -### Asynchrone API-Endpunkte (`src/api/routes/items.py`) - -```python -from typing import List -from fastapi import APIRouter, HTTPException, status - -from src.schemas.items import Item, ItemCreate, ItemUpdate -from src.crud.items import AsyncItemCRUD - -router = APIRouter() -crud = AsyncItemCRUD() - -@router.get("/", response_model=List[Item]) -async def read_items(): - """Retrieve all items (asynchronous)""" - return await crud.get_items() - -@router.get("/{item_id}", response_model=Item) -async def read_item(item_id: int): - """Retrieve specific item (asynchronous)""" - item = await crud.get_item(item_id) - if item is None: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Item with id {item_id} not found" - ) - return item - -@router.post("/", response_model=Item, status_code=status.HTTP_201_CREATED) -async def create_item(item: ItemCreate): - """Create new item (asynchronous)""" - return await crud.create_item(item) - -@router.put("/{item_id}", response_model=Item) -async def update_item(item_id: int, item_update: ItemUpdate): - """Update item (asynchronous)""" - updated_item = await crud.update_item(item_id, item_update) - if updated_item is None: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Item with id {item_id} not found" - ) - return updated_item - -@router.delete("/{item_id}", status_code=status.HTTP_204_NO_CONTENT) -async def delete_item(item_id: int): - """Delete item (asynchronous)""" - deleted = await crud.delete_item(item_id) - if not deleted: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Item with id {item_id} not found" - ) -``` - -## Schritt 4: Server starten und testen - -Wechseln Sie ins Projektverzeichnis und starten Sie den Server: - -
- -```console -$ cd async-todo-api -$ fastkit runserver -Starting FastAPI server at 127.0.0.1:8000... - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -INFO: Started reloader process [12345] using WatchFiles -INFO: Started server process [12346] -INFO: Waiting for application startup. -INFO: Application startup complete. -``` - -
- -### Leistungstests - -Prüfen wir die Leistung der asynchronen Verarbeitung. Versuchen Sie, mehrere Anfragen gleichzeitig zu senden: - -**Test paralleler Anfragen (Python-Skript)** - -```python -import asyncio -import aiohttp -import time - -async def create_item(session, item_data): - async with session.post("http://127.0.0.1:8000/items/", json=item_data) as response: - return await response.json() - -async def test_concurrent_requests(): - start_time = time.time() - - items_to_create = [ - {"name": f"Item {i}", "description": f"Description {i}", "price": i * 10, "tax": i} - for i in range(1, 11) # Create 10 items concurrently - ] - - async with aiohttp.ClientSession() as session: - tasks = [create_item(session, item) for item in items_to_create] - results = await asyncio.gather(*tasks) - - end_time = time.time() - print(f"Created 10 items in: {end_time - start_time:.2f} seconds") - print(f"Number of items created: {len(results)}") - -# Run test -# asyncio.run(test_concurrent_requests()) -``` - -## Schritt 5: Asynchrone Tests schreiben - -### Test-Konfiguration (`tests/conftest.py`) - -```python -import pytest -import asyncio -from httpx import AsyncClient -from src.main import app - -@pytest.fixture(scope="session") -def event_loop(): - """Event loop configuration""" - loop = asyncio.get_event_loop_policy().new_event_loop() - yield loop - loop.close() - -@pytest.fixture -async def async_client(): - """Asynchronous test client""" - async with AsyncClient(app=app, base_url="http://test") as client: - yield client -``` - -### Asynchrone Testfälle (`tests/test_items.py`) - -```python -import pytest -from httpx import AsyncClient - -@pytest.mark.asyncio -async def test_create_item_async(async_client: AsyncClient): - """Asynchronous item creation test""" - item_data = { - "name": "Test Item", - "description": "Item for asynchronous testing", - "price": 100.0, - "tax": 10.0 - } - - response = await async_client.post("/items/", json=item_data) - - assert response.status_code == 201 - data = response.json() - assert data["name"] == item_data["name"] - assert data["price"] == item_data["price"] - assert "id" in data - -@pytest.mark.asyncio -async def test_read_items_async(async_client: AsyncClient): - """Asynchronous item list retrieval test""" - response = await async_client.get("/items/") - - assert response.status_code == 200 - items = response.json() - assert isinstance(items, list) - -@pytest.mark.asyncio -async def test_concurrent_operations(async_client: AsyncClient): - """Concurrent operations test""" - import asyncio - - # Create multiple items concurrently - tasks = [] - for i in range(5): - item_data = { - "name": f"ConcurrentItem{i}", - "description": f"Description{i}", - "price": i * 10, - "tax": i - } - task = async_client.post("/items/", json=item_data) - tasks.append(task) - - responses = await asyncio.gather(*tasks) - - # Verify all requests succeeded - for response in responses: - assert response.status_code == 201 - - # Verify created items - response = await async_client.get("/items/") - items = response.json() - assert len(items) >= 5 -``` - -### Tests ausführen - -
- -```console -$ pytest tests/ -v --asyncio-mode=auto -======================== test session starts ======================== -collected 8 items - -tests/test_items.py::test_create_item_async PASSED [ 12%] -tests/test_items.py::test_read_items_async PASSED [ 25%] -tests/test_items.py::test_read_item_async PASSED [ 37%] -tests/test_items.py::test_update_item_async PASSED [ 50%] -tests/test_items.py::test_delete_item_async PASSED [ 62%] -tests/test_items.py::test_concurrent_operations PASSED [ 75%] -tests/test_items.py::test_item_not_found_async PASSED [ 87%] -tests/test_items.py::test_invalid_item_data_async PASSED [100%] - -======================== 8 passed in 0.24s ======================== -``` - -
- -## Schritt 6: Performance-Monitoring und -Optimierung - -### Middleware zur Messung der Antwortzeit hinzufügen - -Fügen wir Performance-Monitoring in `src/main.py` hinzu: - -```python -import time -from fastapi import FastAPI, Request -from src.api.api import api_router -from src.core.config import settings - -app = FastAPI( - title=settings.PROJECT_NAME, - version=settings.VERSION, - description=settings.DESCRIPTION, -) - -@app.middleware("http") -async def add_process_time_header(request: Request, call_next): - """Add request processing time to headers""" - start_time = time.time() - response = await call_next(request) - process_time = time.time() - start_time - response.headers["X-Process-Time"] = str(process_time) - return response - -app.include_router(api_router) - -@app.get("/") -async def read_root(): - return {"message": "Welcome to the Asynchronous Todo API!"} -``` - -### Asynchrone Batch-Verarbeitung implementieren - -Fügen wir Batch-Endpunkte hinzu, um mehrere Items gleichzeitig zu verarbeiten: - -```python -# Add to src/api/routes/items.py - -@router.post("/batch", response_model=List[Item]) -async def create_items_batch(items: List[ItemCreate]): - """Create multiple items concurrently (batch processing)""" - import asyncio - - # Execute all item creation tasks concurrently - tasks = [crud.create_item(item) for item in items] - created_items = await asyncio.gather(*tasks) - - return created_items - -@router.get("/batch/{item_ids}") -async def read_items_batch(item_ids: str): - """Retrieve multiple items concurrently (batch processing)""" - import asyncio - - # Parse comma-separated IDs - ids = [int(id.strip()) for id in item_ids.split(",")] - - # Execute all item retrieval tasks concurrently - tasks = [crud.get_item(item_id) for item_id in ids] - items = await asyncio.gather(*tasks) - - # Return only non-None items - return [item for item in items if item is not None] -``` - -### Batch-Verarbeitung testen - -
- -```console -# Batch creation test -$ curl -X POST "http://127.0.0.1:8000/items/batch" \ - -H "Content-Type: application/json" \ - -d '[ - {"name": "Item1", "description": "Description1", "price": 10.0, "tax": 1.0}, - {"name": "Item2", "description": "Description2", "price": 20.0, "tax": 2.0}, - {"name": "Item3", "description": "Description3", "price": 30.0, "tax": 3.0} - ]' - -# Batch retrieval test -$ curl -X GET "http://127.0.0.1:8000/items/batch/1,2,3" -``` - -
- -## Schritt 7: Fortgeschrittene asynchrone Muster - -### Rate-Limiting implementieren - -```python -import asyncio -from collections import defaultdict -from fastapi import HTTPException, Request -from datetime import datetime, timedelta - -class AsyncRateLimiter: - def __init__(self, max_requests: int = 100, window_seconds: int = 60): - self.max_requests = max_requests - self.window_seconds = window_seconds - self.requests = defaultdict(list) - - async def is_allowed(self, client_ip: str) -> bool: - now = datetime.now() - cutoff = now - timedelta(seconds=self.window_seconds) - - # remove old request records - self.requests[client_ip] = [ - req_time for req_time in self.requests[client_ip] - if req_time > cutoff - ] - - # check current request count - if len(self.requests[client_ip]) >= self.max_requests: - return False - - # add current request record - self.requests[client_ip].append(now) - return True - -# global rate limiter instance -rate_limiter = AsyncRateLimiter() - -@app.middleware("http") -async def rate_limit_middleware(request: Request, call_next): - client_ip = request.client.host - - if not await rate_limiter.is_allowed(client_ip): - raise HTTPException( - status_code=429, - detail="Too many requests" - ) - - response = await call_next(request) - return response -``` - -### Asynchrones Caching implementieren - -```python -import asyncio -from typing import Optional, Any -from datetime import datetime, timedelta - -class AsyncCache: - def __init__(self): - self._cache = {} - self._expiry = {} - - async def get(self, key: str) -> Optional[Any]: - # remove expired items - if key in self._expiry and datetime.now() > self._expiry[key]: - del self._cache[key] - del self._expiry[key] - return None - - return self._cache.get(key) - - async def set(self, key: str, value: Any, ttl_seconds: int = 300): - self._cache[key] = value - self._expiry[key] = datetime.now() + timedelta(seconds=ttl_seconds) - - async def delete(self, key: str): - self._cache.pop(key, None) - self._expiry.pop(key, None) - -# global cache instance -cache = AsyncCache() - -# modify CRUD methods to use cache -async def get_items_cached(self) -> List[Item]: - """Retrieve items using cache""" - cache_key = "all_items" - cached_items = await cache.get(cache_key) - - if cached_items: - return cached_items - - # if cache is not found, read from file - items = await self.get_items() - await cache.set(cache_key, items, ttl_seconds=60) # 1 minute cache - - return items -``` - -## Schritt 8: Produktionsüberlegungen - -### Verbindungspools verwalten - -```python -# add to src/core/config.py -class Settings(BaseSettings): - # ... existing settings ... - - # asynchronous processing related settings - MAX_CONCURRENT_REQUESTS: int = 100 - REQUEST_TIMEOUT: int = 30 - CONNECTION_POOL_SIZE: int = 20 - -settings = Settings() -``` - -### Fehlerbehandlung verbessern - -```python -import logging -from fastapi import HTTPException -from typing import Union - -logger = logging.getLogger(__name__) - -async def safe_async_operation(operation, *args, **kwargs) -> Union[Any, None]: - """Execute safe asynchronous operation""" - try: - return await operation(*args, **kwargs) - except asyncio.TimeoutError: - logger.error(f"Timeout in {operation.__name__}") - raise HTTPException(status_code=504, detail="Request timeout") - except Exception as e: - logger.error(f"Error in {operation.__name__}: {str(e)}") - raise HTTPException(status_code=500, detail="Internal server error") - -# usage example -@router.get("/safe/{item_id}") -async def read_item_safe(item_id: int): - return await safe_async_operation(crud.get_item, item_id) -``` - -## Nächste Schritte - -Sie haben den Bau einer asynchronen CRUD-API abgeschlossen! Nächste Schritte zum Ausprobieren: - -1. **[Datenbankintegration](database-integration.md)** — PostgreSQL mit asynchronem SQLAlchemy nutzen -2. **[Docker-Containerisierung](docker-deployment.md)** — asynchrone Anwendungen containerisieren -3. **[Benutzerdefinierte Antwortbehandlung](custom-response-handling.md)** — fortgeschrittene Antwortformate und Fehlerbehandlung - - - -## Zusammenfassung - -In diesem Tutorial haben wir mit asynchronem FastAPI: - -- ✅ Asynchrone CRUD-Operationen implementiert -- ✅ Datei-I/O mit aiofiles optimiert -- ✅ Parallele Anfragen behandelt und Leistung getestet -- ✅ Asynchrone Tests geschrieben und ausgeführt -- ✅ Batch-Verarbeitung und fortgeschrittene asynchrone Muster implementiert -- ✅ Produktionsüberlegungen behandelt (Caching, Fehlerbehandlung, Verbindungsverwaltung) - -Asynchrone Verarbeitung zu beherrschen ermöglicht es Ihnen, hochperformante API-Server zu bauen! diff --git a/docs/de/tutorial/basic-api-server.md b/docs/de/tutorial/basic-api-server.md index 0271d918..77479d95 100644 --- a/docs/de/tutorial/basic-api-server.md +++ b/docs/de/tutorial/basic-api-server.md @@ -367,10 +367,9 @@ tests/test_items.py::test_update_item PASSED [100%] Sie haben den Bau eines einfachen API-Servers abgeschlossen! Nächste Schritte zum Ausprobieren: -1. **[Asynchrone CRUD-APIs bauen](async-crud-api.md)** — lernen Sie komplexere asynchrone Verarbeitung -2. **[Datenbankintegration](database-integration.md)** — PostgreSQL und SQLAlchemy nutzen -3. **[Docker-Containerisierung](docker-deployment.md)** — auf ein Produktionsdeployment vorbereiten -4. **[Benutzerdefinierte Antwortbehandlung](custom-response-handling.md)** — erweiterte Konfiguration der Antwortformate +1. **[Asynchrone Persistenz mit SQLModel](sqlmodel.md)** — asynchroner Datenzugriff mit SQLite, PostgreSQL oder MySQL +2. **[Domänenorientiertes Projekt](domain-starter.md)** — eine mittelgroße API strukturieren +3. **[Benutzerdefinierte Antwortbehandlung](custom-response-handling.md)** — erweiterte Konfiguration der Antwortformate ## Fehlerbehebung diff --git a/docs/de/tutorial/custom-response-handling.md b/docs/de/tutorial/custom-response-handling.md index 92fcf105..3b23c2d5 100644 --- a/docs/de/tutorial/custom-response-handling.md +++ b/docs/de/tutorial/custom-response-handling.md @@ -14,7 +14,7 @@ Lernen Sie, wie Sie mit den fortgeschrittenen Funktionen von FastAPI konsistente ## Voraussetzungen -- Das [Tutorial Docker-Containerisierung](docker-deployment.md) abgeschlossen +- Das Tutorial [Einfacher API-Server](basic-api-server.md) abgeschlossen - Verständnis der REST-API-Designprinzipien - Kenntnisse der HTTP-Statuscodes - Grundkonzepte von OpenAPI / Swagger diff --git a/docs/de/tutorial/database-integration.md b/docs/de/tutorial/database-integration.md deleted file mode 100644 index 0ad41bd2..00000000 --- a/docs/de/tutorial/database-integration.md +++ /dev/null @@ -1,1028 +0,0 @@ -# Datenbankintegration (PostgreSQL + SQLAlchemy) - -Bauen Sie eine FastAPI-Anwendung mit PostgreSQL-Datenbank und SQLAlchemy-ORM, die in echten Produktionsumgebungen eingesetzt werden kann. In diesem Tutorial implementieren wir ein vollständiges Datenbankintegrationssystem mit der Vorlage `fastapi-psql-orm`. - -## Was Sie in diesem Tutorial lernen - -- PostgreSQL-Datenbank einrichten und integrieren -- Datenmodellierung mit SQLAlchemy-ORM -- Datenbankmigrationen mit Alembic -- Entwicklungsumgebung mit Docker Compose einrichten -- Verbindungspool der Datenbank verwalten -- Transaktionsverarbeitung und Datenintegrität - -## Voraussetzungen - -- Das [Tutorial Asynchrone CRUD-API](async-crud-api.md) abgeschlossen -- Docker und Docker Compose installiert -- Grundkenntnisse von PostgreSQL -- Verständnis der Grundkonzepte des SQLAlchemy-ORM - -## Warum PostgreSQL und SQLAlchemy? - -### Vergleich JSON-Dateien vs. PostgreSQL - -| Kategorie | JSON-Dateien | PostgreSQL | -|----------|------------|------------| -| **Leistung** | Begrenzt | Hochleistungs-Indexierung | -| **Nebenläufigkeit** | Datei-Sperrprobleme | Transaktionsunterstützung | -| **Skalierbarkeit** | Speicherbegrenzt | Verarbeitung großer Datenmengen | -| **Integrität** | Nicht garantiert | ACID-Eigenschaften garantiert | -| **Abfragen** | Müssen alle Daten laden | Unterstützung komplexer Abfragen | -| **Backup** | Dateikopie | Vollständiges Backup/Restore | - -## Schritt 1: Ein PostgreSQL-+-ORM-Projekt erstellen - -Erstellen Sie ein Projekt mit der Vorlage `fastapi-psql-orm`: - -
- -```console -$ fastkit startdemo fastapi-psql-orm -Enter the project name: todo-postgres-api -Enter the author name: Developer Kim -Enter the author email: developer@example.com -Enter the project description: Todo management API using PostgreSQL -Deploying FastAPI project using 'fastapi-psql-orm' template - - Project Information -┌──────────────┬─────────────────────────────────────────┐ -│ Project Name │ todo-postgres-api │ -│ Author │ Developer Kim │ -│ Author Email │ developer@example.com │ -│ Description │ Todo management API using PostgreSQL │ -└──────────────┴─────────────────────────────────────────┘ - - Template Dependencies -┌──────────────┬────────────────┐ -│ Dependency 1 │ fastapi │ -│ Dependency 2 │ uvicorn │ -│ Dependency 3 │ sqlalchemy │ -│ Dependency 4 │ alembic │ -│ Dependency 5 │ psycopg2 │ -│ Dependency 6 │ asyncpg │ -│ Dependency 7 │ sqlmodel │ -└──────────────┴────────────────┘ - -Select package manager (pip, uv, pdm, poetry) [uv]: uv -Do you want to proceed with project creation? [y/N]: y - -✨ FastAPI project 'todo-postgres-api' from 'fastapi-psql-orm' has been created successfully! -``` - -
- -## Schritt 2: Projektstruktur analysieren - -Das generierte Projekt bietet eine vollständige Datenbankintegrationsumgebung: - -``` -todo-postgres-api/ -├── docker-compose.yml # PostgreSQL container configuration -├── Dockerfile # Application container -├── alembic.ini # Alembic configuration -├── template-config.yml # Template configuration -├── scripts/ -│ ├── pre-start.sh # Pre-start initialization -│ └── test.sh # Test execution script -├── src/ -│ ├── main.py # FastAPI application -│ ├── core/ -│ │ ├── config.py # Environment configuration -│ │ └── db.py # Database connection setup -│ ├── api/ -│ │ ├── deps.py # Dependency injection -│ │ └── routes/ -│ │ └── items.py # API endpoints -│ ├── crud/ -│ │ └── items.py # Database operations -│ ├── schemas/ -│ │ └── items.py # Pydantic models -│ ├── utils/ -│ │ ├── backend_pre_start.py # Backend initialization -│ │ ├── init_data.py # Initial data loading -│ │ └── tests_pre_start.py # Test preparation -│ └── alembic/ -│ ├── env.py # Alembic environment configuration -│ └── versions/ # Migration files -└── tests/ - ├── conftest.py # Test configuration - └── test_items.py # API tests -``` - -### Kernkomponenten - -1. **SQLModel**: SQLAlchemy + Pydantic-Integration -2. **Alembic**: Schema-Migration für die Datenbank -3. **asyncpg**: asynchroner PostgreSQL-Treiber -4. **Docker Compose**: Containerisierung der Entwicklungsumgebung - -## Schritt 3: Die Datenbankkonfiguration verstehen - -### Konfiguration der Datenbankverbindung (`src/core/db.py`) - -```python -from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine -from sqlalchemy.orm import sessionmaker -from sqlmodel import SQLModel - -from src.core.config import settings - -# Create asynchronous PostgreSQL engine -engine = create_async_engine( - settings.DATABASE_URL, - echo=settings.DEBUG, # Output SQL logs - pool_size=20, # Connection pool size - max_overflow=0, # Number of additional connections allowed - pool_pre_ping=True, # Check connection status -) - -# Asynchronous session factory -AsyncSessionLocal = sessionmaker( - autocommit=False, - autoflush=False, - bind=engine, - class_=AsyncSession, - expire_on_commit=False, -) - -async def create_tables(): - """Create database tables""" - async with engine.begin() as conn: - await conn.run_sync(SQLModel.metadata.create_all) - -async def get_session() -> AsyncSession: - """Provide database session (for dependency injection)""" - async with AsyncSessionLocal() as session: - try: - yield session - finally: - await session.close() -``` - -### Umgebungskonfiguration (`src/core/config.py`) - -```python -from pydantic_settings import BaseSettings -from typing import Optional - -class Settings(BaseSettings): - PROJECT_NAME: str = "Todo PostgreSQL API" - VERSION: str = "1.0.0" - DESCRIPTION: str = "Todo management API using PostgreSQL" - - # Database configuration - POSTGRES_SERVER: str = "localhost" - POSTGRES_USER: str = "postgres" - POSTGRES_PASSWORD: str = "password" - POSTGRES_DB: str = "todoapp" - POSTGRES_PORT: int = 5432 - - # Test database - TEST_DATABASE_URL: Optional[str] = None - - # Debug mode - DEBUG: bool = False - - @property - def DATABASE_URL(self) -> str: - """Generate PostgreSQL connection URL""" - return ( - f"postgresql+asyncpg://{self.POSTGRES_USER}:" - f"{self.POSTGRES_PASSWORD}@{self.POSTGRES_SERVER}:" - f"{self.POSTGRES_PORT}/{self.POSTGRES_DB}" - ) - - class Config: - env_file = ".env" - -settings = Settings() -``` - -## Schritt 4: Datenmodell definieren - -### Datenmodell mit SQLModel (`src/schemas/items.py`) - -```python -from sqlmodel import SQLModel, Field -from typing import Optional -from datetime import datetime - -# Define common fields -class ItemBase(SQLModel): - name: str = Field(index=True, max_length=100) - description: Optional[str] = Field(default=None, max_length=500) - price: float = Field(gt=0, description="Price must be greater than 0") - tax: Optional[float] = Field(default=None, ge=0) - is_active: bool = Field(default=True) - -# Database table model -class Item(ItemBase, table=True): - __tablename__ = "items" - - id: Optional[int] = Field(default=None, primary_key=True) - created_at: datetime = Field(default_factory=datetime.utcnow) - updated_at: Optional[datetime] = Field(default=None) - - # Set index - class Config: - schema_extra = { - "example": { - "name": "notebook", - "description": "High-performance gaming notebook", - "price": 1500000.0, - "tax": 150000.0, - "is_active": True - } - } - -# API request/response model -class ItemCreate(ItemBase): - pass - -class ItemUpdate(SQLModel): - name: Optional[str] = Field(default=None, max_length=100) - description: Optional[str] = Field(default=None, max_length=500) - price: Optional[float] = Field(default=None, gt=0) - tax: Optional[float] = Field(default=None, ge=0) - is_active: Optional[bool] = Field(default=None) - -class ItemResponse(ItemBase): - id: int - created_at: datetime - updated_at: Optional[datetime] -``` - -## Schritt 5: CRUD-Operationen implementieren - -### Datenbank-CRUD-Logik (`src/crud/items.py`) - -```python -from typing import List, Optional -from sqlalchemy.ext.asyncio import AsyncSession -from sqlalchemy import select, update, delete -from sqlalchemy.orm import selectinload -from datetime import datetime - -from src.schemas.items import Item, ItemCreate, ItemUpdate - -class ItemCRUD: - def __init__(self, db: AsyncSession): - self.db = db - - async def create(self, item_create: ItemCreate) -> Item: - """Create new item""" - db_item = Item(**item_create.dict()) - - self.db.add(db_item) - await self.db.commit() - await self.db.refresh(db_item) - - return db_item - - async def get_by_id(self, item_id: int) -> Optional[Item]: - """Get item by ID""" - statement = select(Item).where(Item.id == item_id) - result = await self.db.execute(statement) - return result.scalar_one_or_none() - - async def get_many( - self, - skip: int = 0, - limit: int = 100, - active_only: bool = True - ) -> List[Item]: - """Get multiple items (pagination supported)""" - statement = select(Item) - - if active_only: - statement = statement.where(Item.is_active == True) - - statement = statement.offset(skip).limit(limit) - result = await self.db.execute(statement) - return result.scalars().all() - - async def update(self, item_id: int, item_update: ItemUpdate) -> Optional[Item]: - """Update item""" - # Prepare update data - update_data = item_update.dict(exclude_unset=True) - if update_data: - update_data["updated_at"] = datetime.utcnow() - - # Execute update - statement = ( - update(Item) - .where(Item.id == item_id) - .values(**update_data) - .returning(Item) - ) - - result = await self.db.execute(statement) - await self.db.commit() - - return result.scalar_one_or_none() - - async def delete(self, item_id: int) -> bool: - """Delete item (soft delete)""" - statement = ( - update(Item) - .where(Item.id == item_id) - .values(is_active=False, updated_at=datetime.utcnow()) - ) - - result = await self.db.execute(statement) - await self.db.commit() - - return result.rowcount > 0 - - async def hard_delete(self, item_id: int) -> bool: - """Delete item completely""" - statement = delete(Item).where(Item.id == item_id) - result = await self.db.execute(statement) - await self.db.commit() - - return result.rowcount > 0 - - async def search(self, query: str) -> List[Item]: - """Search item (name, description)""" - statement = select(Item).where( - (Item.name.ilike(f"%{query}%")) | - (Item.description.ilike(f"%{query}%")) - ).where(Item.is_active == True) - - result = await self.db.execute(statement) - return result.scalars().all() - - async def get_total_count(self, active_only: bool = True) -> int: - """Get total item count""" - from sqlalchemy import func - - statement = select(func.count(Item.id)) - if active_only: - statement = statement.where(Item.is_active == True) - - result = await self.db.execute(statement) - return result.scalar() -``` - -## Schritt 6: API-Endpunkte implementieren - -### Dependency-Injection einrichten (`src/api/deps.py`) - -```python -from typing import AsyncGenerator -from fastapi import Depends -from sqlalchemy.ext.asyncio import AsyncSession - -from src.core.db import get_session -from src.crud.items import ItemCRUD - -async def get_db() -> AsyncGenerator[AsyncSession, None]: - """Database session dependency""" - async for session in get_session(): - yield session - -def get_item_crud(db: AsyncSession = Depends(get_db)) -> ItemCRUD: - """Item CRUD dependency""" - return ItemCRUD(db) -``` - -### API-Router-Implementierung (`src/api/routes/items.py`) - -```python -from typing import List -from fastapi import APIRouter, Depends, HTTPException, Query, status - -from src.api.deps import get_item_crud -from src.crud.items import ItemCRUD -from src.schemas.items import Item, ItemCreate, ItemUpdate, ItemResponse - -router = APIRouter() - -@router.post("/", response_model=ItemResponse, status_code=status.HTTP_201_CREATED) -async def create_item( - item_create: ItemCreate, - crud: ItemCRUD = Depends(get_item_crud) -): - """Create new item""" - return await crud.create(item_create) - -@router.get("/", response_model=List[ItemResponse]) -async def read_items( - skip: int = Query(0, ge=0, description="Skip items"), - limit: int = Query(100, ge=1, le=1000, description="Maximum items to retrieve"), - active_only: bool = Query(True, description="Only active items"), - crud: ItemCRUD = Depends(get_item_crud) -): - """Get item list (pagination supported)""" - return await crud.get_many(skip=skip, limit=limit, active_only=active_only) - -@router.get("/search", response_model=List[ItemResponse]) -async def search_items( - q: str = Query(..., min_length=1, description="Search term"), - crud: ItemCRUD = Depends(get_item_crud) -): - """Search item""" - return await crud.search(q) - -@router.get("/count") -async def get_items_count( - active_only: bool = Query(True, description="Only active items"), - crud: ItemCRUD = Depends(get_item_crud) -): - """Get total item count""" - count = await crud.get_total_count(active_only) - return {"total": count} - -@router.get("/{item_id}", response_model=ItemResponse) -async def read_item( - item_id: int, - crud: ItemCRUD = Depends(get_item_crud) -): - """Get specific item""" - item = await crud.get_by_id(item_id) - if not item: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Item ID {item_id} not found" - ) - return item - -@router.put("/{item_id}", response_model=ItemResponse) -async def update_item( - item_id: int, - item_update: ItemUpdate, - crud: ItemCRUD = Depends(get_item_crud) -): - """Update item""" - updated_item = await crud.update(item_id, item_update) - if not updated_item: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Item ID {item_id} not found" - ) - return updated_item - -@router.delete("/{item_id}", status_code=status.HTTP_204_NO_CONTENT) -async def delete_item( - item_id: int, - hard_delete: bool = Query(False, description="Complete delete"), - crud: ItemCRUD = Depends(get_item_crud) -): - """Delete item""" - if hard_delete: - deleted = await crud.hard_delete(item_id) - else: - deleted = await crud.delete(item_id) - - if not deleted: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Item ID {item_id} not found" - ) -``` - -## Schritt 7: Docker-Container starten - -### Docker-Compose-Konfiguration prüfen (`docker-compose.yml`) - -```yaml -version: '3.8' - -services: - db: - image: postgres:15 - restart: always - environment: - POSTGRES_DB: todoapp - POSTGRES_USER: postgres - POSTGRES_PASSWORD: password - ports: - - "5432:5432" - volumes: - - postgres_data:/var/lib/postgresql/data - - app: - build: . - restart: always - ports: - - "8000:8000" - environment: - POSTGRES_SERVER: db - POSTGRES_USER: postgres - POSTGRES_PASSWORD: password - POSTGRES_DB: todoapp - depends_on: - - db - volumes: - - ./src:/app/src - -volumes: - postgres_data: -``` - -### Container starten - -
- -```console -$ cd todo-postgres-api - -# Start service in background -$ docker-compose up -d -Creating network "todo-postgres-api_default" with the default driver -Creating volume "todo-postgres-api_postgres_data" with default driver -Pulling db (postgres:15)... -Creating todo-postgres-api_db_1 ... done -Building app -Creating todo-postgres-api_app_1 ... done - -# Check service status -$ docker-compose ps - Name Command State Ports -------------------------------------------------------------------------------------- -todo-postgres-api_app_1 uvicorn src.main:app --host=0.0.0.0 --port=8000 Up 0.0.0.0:8000->8000/tcp -todo-postgres-api_db_1 docker-entrypoint.sh postgres Up 0.0.0.0:5432->5432/tcp - -# Check log -$ docker-compose logs app -``` - -
- -## Schritt 8: Datenbankmigration - -### Erste Migration mit Alembic erstellen - -
- -```console -# Run migration inside container -$ docker-compose exec app alembic revision --autogenerate -m "Create items table" -INFO [alembic.runtime.migration] Context impl PostgresqlImpl. -INFO [alembic.runtime.migration] Will assume transactional DDL. -INFO [alembic.autogenerate.compare] Detected added table 'items' -Generating migration script /app/src/alembic/versions/001_create_items_table.py ... done - -# Apply migration -$ docker-compose exec app alembic upgrade head -INFO [alembic.runtime.migration] Context impl PostgresqlImpl. -INFO [alembic.runtime.migration] Will assume transactional DDL. -INFO [alembic.runtime.migration] Running upgrade -> 001, Create items table -``` - -
- -### Migrationsdatei prüfen - -Sehen Sie sich die erstellte Migrationsdatei an: - -```python -# src/alembic/versions/001_create_items_table.py -"""Create items table - -Revision ID: 001 -Revises: -Create Date: 2024-01-01 12:00:00.000000 - -""" -from alembic import op -import sqlalchemy as sa -import sqlmodel - -# revision identifiers -revision = '001' -down_revision = None -branch_labels = None -depends_on = None - -def upgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.create_table('items', - sa.Column('name', sqlmodel.sql.sqltypes.AutoString(length=100), nullable=False), - sa.Column('description', sqlmodel.sql.sqltypes.AutoString(length=500), nullable=True), - sa.Column('price', sa.Float(), nullable=False), - sa.Column('tax', sa.Float(), nullable=True), - sa.Column('is_active', sa.Boolean(), nullable=False), - sa.Column('id', sa.Integer(), nullable=False), - sa.Column('created_at', sa.DateTime(), nullable=False), - sa.Column('updated_at', sa.DateTime(), nullable=True), - sa.PrimaryKeyConstraint('id') - ) - op.create_index(op.f('ix_items_name'), 'items', ['name'], unique=False) - # ### end Alembic commands ### - -def downgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.drop_index(op.f('ix_items_name'), table_name='items') - op.drop_table('items') - # ### end Alembic commands ### -``` - -## Schritt 9: API testen - -### Grundlegender CRUD-Test - -
- -```console -# Create new item -$ curl -X POST "http://localhost:8000/items/" \ - -H "Content-Type: application/json" \ - -d '{ - "name": "MacBook Pro", - "description": "M2 chipset-equipped high-performance notebook", - "price": 2500000, - "tax": 250000 - }' - -{ - "id": 1, - "name": "MacBook Pro", - "description": "M2 chipset-equipped high-performance notebook", - "price": 2500000.0, - "tax": 250000.0, - "is_active": true, - "created_at": "2024-01-01T12:00:00.123456", - "updated_at": null -} - -# Get item list -$ curl "http://localhost:8000/items/" - -# Get item list with pagination -$ curl "http://localhost:8000/items/?skip=0&limit=10" - -# Search item -$ curl "http://localhost:8000/items/search?q=MacBook" - -# Get item count -$ curl "http://localhost:8000/items/count" -{"total": 1} -``` - -
- -### Test fortgeschrittener Abfragefunktionen - -
- -```console -# Get item list with inactive items -$ curl "http://localhost:8000/items/?active_only=false" - -# Update item -$ curl -X PUT "http://localhost:8000/items/1" \ - -H "Content-Type: application/json" \ - -d '{ - "price": 2300000, - "tax": 230000 - }' - -# Soft delete item -$ curl -X DELETE "http://localhost:8000/items/1" - -# Hard delete item -$ curl -X DELETE "http://localhost:8000/items/1?hard_delete=true" -``` - -
- -## Schritt 10: Erweiterte Datenbankfunktionen - -### Transaktionsverarbeitung - -```python -# Add to src/crud/items.py - -from sqlalchemy.exc import SQLAlchemyError - -async def create_items_batch(self, items_create: List[ItemCreate]) -> List[Item]: - """Create multiple items in a transaction""" - created_items = [] - - try: - for item_create in items_create: - db_item = Item(**item_create.dict()) - self.db.add(db_item) - created_items.append(db_item) - - await self.db.commit() - - # Refresh all items - for item in created_items: - await self.db.refresh(item) - - return created_items - - except SQLAlchemyError: - await self.db.rollback() - raise -``` - -### Relationale Datenmodellierung - -```python -# Add to src/schemas/items.py - -from sqlmodel import Relationship - -class Category(SQLModel, table=True): - __tablename__ = "categories" - - id: Optional[int] = Field(default=None, primary_key=True) - name: str = Field(max_length=50, unique=True) - description: Optional[str] = None - - # Set relationship - items: List["Item"] = Relationship(back_populates="category") - -class Item(ItemBase, table=True): - __tablename__ = "items" - - id: Optional[int] = Field(default=None, primary_key=True) - created_at: datetime = Field(default_factory=datetime.utcnow) - updated_at: Optional[datetime] = Field(default=None) - - # Add foreign key - category_id: Optional[int] = Field(foreign_key="categories.id") - - # Set relationship - category: Optional[Category] = Relationship(back_populates="items") -``` - -### Index-Optimierung - -```python -# Add to src/schemas/items.py - -from sqlalchemy import Index - -class Item(ItemBase, table=True): - __tablename__ = "items" - - # ... existing fields ... - - # Set composite index - __table_args__ = ( - Index('ix_items_price_active', 'price', 'is_active'), - Index('ix_items_created_at', 'created_at'), - Index('ix_items_name_description', 'name', 'description'), # For full text search - ) -``` - -## Schritt 11: Tests schreiben - -### Test-Setup für die Datenbank (`tests/conftest.py`) - -```python -import pytest -import asyncio -from httpx import AsyncClient -from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine -from sqlalchemy.orm import sessionmaker -from sqlmodel import SQLModel - -from src.main import app -from src.core.db import get_session -from src.core.config import settings - -# Test database engine -test_engine = create_async_engine( - settings.TEST_DATABASE_URL or "sqlite+aiosqlite:///./test.db", - echo=False, -) - -TestSessionLocal = sessionmaker( - autocommit=False, - autoflush=False, - bind=test_engine, - class_=AsyncSession, - expire_on_commit=False, -) - -@pytest.fixture(scope="session") -def event_loop(): - loop = asyncio.get_event_loop_policy().new_event_loop() - yield loop - loop.close() - -@pytest.fixture(scope="function") -async def db_session(): - # Create test table - async with test_engine.begin() as conn: - await conn.run_sync(SQLModel.metadata.create_all) - - # Provide session - async with TestSessionLocal() as session: - yield session - - # Delete table after test - async with test_engine.begin() as conn: - await conn.run_sync(SQLModel.metadata.drop_all) - -@pytest.fixture -async def client(db_session: AsyncSession): - # Override dependency - async def override_get_session(): - yield db_session - - app.dependency_overrides[get_session] = override_get_session - - async with AsyncClient(app=app, base_url="http://test") as client: - yield client - - app.dependency_overrides.clear() -``` - -### Integrationstests (`tests/test_items.py`) - -```python -import pytest -from httpx import AsyncClient - -@pytest.mark.asyncio -async def test_create_and_read_item(client: AsyncClient): - """Integration test for creating and reading item""" - # Create item - item_data = { - "name": "Test Item", - "description": "Database test", - "price": 50000, - "tax": 5000 - } - - response = await client.post("/items/", json=item_data) - assert response.status_code == 201 - - created_item = response.json() - assert created_item["name"] == item_data["name"] - assert "id" in created_item - assert "created_at" in created_item - - # Get created item - item_id = created_item["id"] - response = await client.get(f"/items/{item_id}") - assert response.status_code == 200 - - retrieved_item = response.json() - assert retrieved_item["id"] == item_id - assert retrieved_item["name"] == item_data["name"] - -@pytest.mark.asyncio -async def test_item_pagination(client: AsyncClient): - """Test pagination feature""" - # Create multiple items - for i in range(15): - item_data = { - "name": f"Item {i}", - "description": f"Description {i}", - "price": i * 1000, - "tax": i * 100 - } - await client.post("/items/", json=item_data) - - # Get first page - response = await client.get("/items/?skip=0&limit=10") - assert response.status_code == 200 - - items = response.json() - assert len(items) == 10 - - # Get second page - response = await client.get("/items/?skip=10&limit=10") - assert response.status_code == 200 - - items = response.json() - assert len(items) == 5 - -@pytest.mark.asyncio -async def test_item_search(client: AsyncClient): - """Test search feature""" - # Create test items - items = [ - {"name": "iPhone 15", "description": "Latest smartphone", "price": 1200000, "tax": 120000}, - {"name": "Galaxy S24", "description": "Samsung flagship", "price": 1100000, "tax": 110000}, - {"name": "MacBook Air", "description": "Apple notebook", "price": 1500000, "tax": 150000}, - ] - - for item in items: - await client.post("/items/", json=item) - - # Search "iPhone" - response = await client.get("/items/search?q=iPhone") - assert response.status_code == 200 - - results = response.json() - assert len(results) == 1 - assert results[0]["name"] == "iPhone 15" - - # Search "smartphone" (description) - response = await client.get("/items/search?q=smartphone") - assert response.status_code == 200 - - results = response.json() - assert len(results) == 1 - assert results[0]["description"] == "Latest smartphone" -``` - -### Tests ausführen - -
- -```console -# Tests im Container ausführen -$ docker-compose exec app python -m pytest tests/ -v -======================== test session starts ======================== -collected 12 items - -tests/test_items.py::test_create_and_read_item PASSED [ 8%] -tests/test_items.py::test_item_pagination PASSED [16%] -tests/test_items.py::test_item_search PASSED [25%] -tests/test_items.py::test_update_item PASSED [33%] -tests/test_items.py::test_delete_item PASSED [41%] -tests/test_items.py::test_soft_delete PASSED [50%] -tests/test_items.py::test_item_not_found PASSED [58%] -tests/test_items.py::test_invalid_item_data PASSED [66%] -tests/test_items.py::test_database_transaction PASSED [75%] -tests/test_items.py::test_concurrent_operations PASSED [83%] -tests/test_items.py::test_item_count PASSED [91%] -tests/test_items.py::test_batch_operations PASSED [100%] - -======================== 12 passed in 2.34s ======================== -``` - -
- -## Schritt 12: Überlegungen für ein Produktionsdeployment - -### Verbindungspool optimieren - -```python -# Add to src/core/config.py - -class Settings(BaseSettings): - # ... existing settings ... - - # Database connection pool settings - DB_POOL_SIZE: int = 20 - DB_MAX_OVERFLOW: int = 0 - DB_POOL_PRE_PING: bool = True - DB_POOL_RECYCLE: int = 300 # 5 minutes - - # Query timeout - DB_QUERY_TIMEOUT: int = 30 - - # Connection retry settings - DB_RETRY_ATTEMPTS: int = 3 - DB_RETRY_DELAY: int = 1 -``` - -### Datenbank-Monitoring - -```python -# Add to src/core/db.py - -import logging -from sqlalchemy import event -from sqlalchemy.engine import Engine - -logger = logging.getLogger(__name__) - -@event.listens_for(Engine, "before_cursor_execute") -def receive_before_cursor_execute(conn, cursor, statement, parameters, context, executemany): - """Log before query execution""" - context._query_start_time = time.time() - -@event.listens_for(Engine, "after_cursor_execute") -def receive_after_cursor_execute(conn, cursor, statement, parameters, context, executemany): - """Log after query execution""" - total = time.time() - context._query_start_time - if total > 1.0: # Log slow queries (1 second or more) - logger.warning(f"Slow query: {total:.2f}s - {statement[:100]}...") -``` - -## Nächste Schritte - -Sie haben die PostgreSQL-Datenbankintegration abgeschlossen! Nächste Schritte zum Ausprobieren: - -1. **[Docker-Containerisierung](docker-deployment.md)** — eine Produktionsumgebung aufbauen -2. **[Benutzerdefinierte Antwortbehandlung](custom-response-handling.md)** — erweiterte API-Antwortformate - - - - -## Zusammenfassung - -In diesem Tutorial haben wir mit PostgreSQL und SQLAlchemy: - -- ✅ Eine PostgreSQL-Datenbank integriert -- ✅ ORM mit SQLModel implementiert -- ✅ Das Alembic-Migrationssystem eingerichtet -- ✅ Fortgeschrittene CRUD-Operationen und Abfrageoptimierung umgesetzt -- ✅ Transaktionsverarbeitung und Datenintegrität behandelt -- ✅ Paginierung, Suche und Sortierung implementiert -- ✅ Integrationstests und Datenbank-Tests geschrieben -- ✅ Überlegungen zum Produktionsdeployment angestellt - -Jetzt können Sie robuste, datenbankgetriebene APIs für echte Produktionsumgebungen bauen! diff --git a/docs/de/tutorial/docker-deployment.md b/docs/de/tutorial/docker-deployment.md deleted file mode 100644 index 166cf4cd..00000000 --- a/docs/de/tutorial/docker-deployment.md +++ /dev/null @@ -1,1178 +0,0 @@ -# Docker-Containerisierung und Deployment - -Lernen Sie, wie Sie FastAPI-Anwendungen mit Docker containerisieren, um konsistente Entwicklungsumgebungen zu bauen und sich auf das Produktionsdeployment vorzubereiten. Wir richten eine vollständige Docker-basierte Deployment-Umgebung mit der Vorlage `fastapi-dockerized` ein. - -## Was Sie in diesem Tutorial lernen - -- FastAPI-Anwendungen mit Docker containerisieren -- Optimierte Docker-Images mit mehrstufigen Builds erstellen -- Entwicklungsumgebungen mit Docker Compose einrichten -- Docker-Konfiguration für das Produktionsdeployment -- Container-Monitoring und Log-Verwaltung -- CI/CD-Pipelines aufbauen - -## Voraussetzungen - -- Das [Tutorial Datenbankintegration](database-integration.md) abgeschlossen -- Docker und Docker Compose installiert -- Verständnis der grundlegenden Docker-Befehle -- Grundkenntnisse zu Container-Konzepten - -## Vorteile der Docker-Containerisierung - -### Klassischer Ansatz vs. Docker - -| Kategorie | Klassischer Ansatz | Docker-Ansatz | -|----------|---------------------|-----------------| -| **Umgebungskonsistenz** | Unterschiede zwischen Umgebungen | Überall gleiche Umgebung | -| **Abhängigkeitsverwaltung** | Manuelle Installation erforderlich | Alle Abhängigkeiten im Image | -| **Deployment-Geschwindigkeit** | Langsam | Schnelles Deployment möglich | -| **Skalierbarkeit** | Begrenzt | Einfache Skalierung | -| **Rollback** | Komplex | Sofortiger Rollback auf vorherige Version | -| **Ressourcennutzung** | Schwer | Leichtgewichtige Container | - -## Schritt 1: Ein Docker-basiertes Projekt erstellen - -Erstellen Sie ein Projekt mit der Vorlage `fastapi-dockerized`: - -
- -```console -$ fastkit startdemo fastapi-dockerized -Enter the project name: dockerized-todo-api -Enter the author name: Developer Kim -Enter the author email: developer@example.com -Enter the project description: Dockerized todo management API -Deploying FastAPI project using 'fastapi-dockerized' template - - Project Information -┌──────────────┬─────────────────────────────────────────────┐ -│ Project Name │ dockerized-todo-api │ -│ Author │ Developer Kim │ -│ Author Email │ developer@example.com │ -│ Description │ Dockerized todo management API │ -└──────────────┴─────────────────────────────────────────────┘ - - Template Dependencies -┌──────────────┬───────────────────┐ -│ Dependency 1 │ fastapi │ -│ Dependency 2 │ uvicorn │ -│ Dependency 3 │ pydantic │ -│ Dependency 4 │ pydantic-settings │ -│ Dependency 5 │ python-dotenv │ -└──────────────┴───────────────────┘ - -Select package manager (pip, uv, pdm, poetry) [uv]: uv -Do you want to proceed with project creation? [y/N]: y - -✨ FastAPI project 'dockerized-todo-api' from 'fastapi-dockerized' has been created successfully! -``` - -
- -## Schritt 2: Docker-Konfigurationsdateien analysieren - -Untersuchen wir die Docker-bezogenen Dateien im generierten Projekt: - -``` -dockerized-todo-api/ -├── Dockerfile # Docker image build configuration -├── docker-compose.yml # Development environment container setup -├── docker-compose.prod.yml # Production environment configuration -├── .dockerignore # Files to exclude during Docker build -├── scripts/ -│ ├── start.sh # Container startup script -│ ├── prestart.sh # Pre-start initialization script -│ └── gunicorn.conf.py # Gunicorn configuration -├── src/ -│ ├── main.py # FastAPI application -│ └── ... # Other source code -└── requirements.txt # Python dependencies -``` - -### Dockerfile-Analyse - -```dockerfile -# Optimized Dockerfile using multi-stage build - -# ============================================ -# Stage 1: Build stage -# ============================================ -FROM python:3.12-slim as builder - -# Install build tools -RUN apt-get update && apt-get install -y \ - build-essential \ - curl \ - && rm -rf /var/lib/apt/lists/* - -# Copy dependency file and install -COPY requirements.txt . -RUN pip install --user --no-cache-dir -r requirements.txt - -# ============================================ -# Stage 2: Runtime stage -# ============================================ -FROM python:3.12-slim - -# System update and essential package installation -RUN apt-get update && apt-get install -y \ - curl \ - && rm -rf /var/lib/apt/lists/* \ - && apt-get clean - -# Create non-root user (security enhancement) -RUN groupadd -r appuser && useradd -r -g appuser appuser - -# Create application directory -WORKDIR /app - -# Copy Python packages from build stage -COPY --from=builder /root/.local /home/appuser/.local - -# Copy application code -COPY . . - -# Set file permissions -RUN chown -R appuser:appuser /app -RUN chmod +x scripts/start.sh scripts/prestart.sh - -# Add Python package path to PATH -ENV PATH=/home/appuser/.local/bin:$PATH - -# Switch to non-root user -USER appuser - -# Configure health check -HEALTHCHECK --interval=30s --timeout=30s --start-period=5s --retries=3 \ - CMD curl -f http://localhost:8000/health || exit 1 - -# Expose port -EXPOSE 8000 - -# Execute startup script -CMD ["./scripts/start.sh"] -``` - -### Docker-Compose-Entwicklungsumgebung (`docker-compose.yml`) - -```yaml -version: '3.8' - -services: - app: - build: - context: . - dockerfile: Dockerfile - container_name: dockerized-todo-api - restart: unless-stopped - ports: - - "8000:8000" - environment: - - ENVIRONMENT=development - - DEBUG=true - - RELOAD=true - volumes: - # Mount volume for development (auto-reload on code changes) - - ./src:/app/src:ro - - ./scripts:/app/scripts:ro - networks: - - app-network - healthcheck: - test: ["CMD", "curl", "-f", "http://localhost:8000/health"] - interval: 30s - timeout: 10s - retries: 3 - start_period: 40s - - # Redis (für Caching und Session-Speicher) - redis: - image: redis:7-alpine - container_name: dockerized-todo-redis - restart: unless-stopped - ports: - - "6379:6379" - volumes: - - redis_data:/data - networks: - - app-network - healthcheck: - test: ["CMD", "redis-cli", "ping"] - interval: 30s - timeout: 10s - retries: 3 - - # Nginx (reverse proxy) - nginx: - image: nginx:alpine - container_name: dockerized-todo-nginx - restart: unless-stopped - ports: - - "80:80" - - "443:443" - volumes: - - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro - - ./nginx/ssl:/etc/nginx/ssl:ro - depends_on: - - app - networks: - - app-network - healthcheck: - test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost/health"] - interval: 30s - timeout: 10s - retries: 3 - -volumes: - redis_data: - -networks: - app-network: - driver: bridge -``` - -### Docker-Compose-Produktionsumgebung (`docker-compose.prod.yml`) - -```yaml -version: '3.8' - -services: - app: - build: - context: . - dockerfile: Dockerfile - restart: always - environment: - - ENVIRONMENT=production - - DEBUG=false - - WORKERS=4 - - MAX_WORKERS=8 - volumes: - - app_logs:/app/logs - networks: - - app-network - deploy: - replicas: 2 - resources: - limits: - cpus: '1.0' - memory: 1G - reservations: - cpus: '0.5' - memory: 512M - restart_policy: - condition: on-failure - delay: 5s - max_attempts: 3 - - redis: - image: redis:7-alpine - restart: always - command: redis-server --appendonly yes --requirepass ${REDIS_PASSWORD} - volumes: - - redis_data:/data - networks: - - app-network - deploy: - resources: - limits: - cpus: '0.5' - memory: 512M - - nginx: - image: nginx:alpine - restart: always - ports: - - "80:80" - - "443:443" - volumes: - - ./nginx/nginx.prod.conf:/etc/nginx/nginx.conf:ro - - ./nginx/ssl:/etc/nginx/ssl:ro - - nginx_logs:/var/log/nginx - depends_on: - - app - networks: - - app-network - deploy: - resources: - limits: - cpus: '0.5' - memory: 256M - -volumes: - redis_data: - app_logs: - nginx_logs: - -networks: - app-network: - driver: overlay - attachable: true -``` - -## Schritt 3: Startskripte konfigurieren - -### Haupt-Startskript (`scripts/start.sh`) - -```bash -#!/bin/bash - -set -e - -# Set environment variables -export PYTHONPATH=/app:$PYTHONPATH - -# Run pre-start script -echo "Running pre-start script..." -./scripts/prestart.sh - -# Determine execution mode based on environment -if [[ "$ENVIRONMENT" == "production" ]]; then - echo "Starting production server with Gunicorn..." - exec gunicorn src.main:app \ - --config scripts/gunicorn.conf.py \ - --bind 0.0.0.0:8000 \ - --workers ${WORKERS:-4} \ - --worker-class uvicorn.workers.UvicornWorker \ - --max-requests 1000 \ - --max-requests-jitter 100 \ - --preload \ - --access-logfile - \ - --error-logfile - -else - echo "Starting development server with Uvicorn..." - if [[ "$RELOAD" == "true" ]]; then - exec uvicorn src.main:app \ - --host 0.0.0.0 \ - --port 8000 \ - --reload \ - --reload-dir src \ - --log-level debug - else - exec uvicorn src.main:app \ - --host 0.0.0.0 \ - --port 8000 \ - --log-level info - fi -fi -``` - -### Pre-Start-Skript (`scripts/prestart.sh`) - -```bash -#!/bin/bash - -set -e - -echo "Running pre-start checks..." - -# Check Python modules and dependencies -echo "Checking Python dependencies..." -python -c "import fastapi, uvicorn, pydantic; print('✓ Core dependencies OK')" - -# Check environment variables -if [[ -z "$ENVIRONMENT" ]]; then - export ENVIRONMENT="development" - echo "ℹ ENVIRONMENT not set, defaulting to development" -fi - -# Create log directory -mkdir -p /app/logs -touch /app/logs/app.log - -# Check if health endpoint is present -echo "Checking health endpoint..." -python -c " -from src.main import app -routes = [route.path for route in app.routes] -if '/health' not in routes: - print('⚠ Warning: /health endpoint not found') -else: - print('✓ Health endpoint OK') -" - -echo "Pre-start checks completed successfully!" -``` - -### Gunicorn-Konfiguration (`scripts/gunicorn.conf.py`) - -```python -import multiprocessing -import os - -# Server socket -bind = "0.0.0.0:8000" -backlog = 2048 - -# Worker process -workers = int(os.getenv("WORKERS", multiprocessing.cpu_count() * 2 + 1)) -worker_class = "uvicorn.workers.UvicornWorker" -worker_connections = 1000 -max_requests = 1000 -max_requests_jitter = 100 - -# Worker restart settings -preload_app = True -timeout = 120 -keepalive = 2 - -# Logging -accesslog = "-" -errorlog = "-" -loglevel = "info" -access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" %(D)s' - -# Process name -proc_name = "dockerized-todo-api" - -# Security -limit_request_line = 4094 -limit_request_fields = 100 -limit_request_field_size = 8190 - -# Performance tuning -def when_ready(server): - server.log.info("Server is ready. Spawning workers") - -def worker_int(worker): - worker.log.info("worker received INT or QUIT signal") - -def pre_fork(server, worker): - server.log.info("Worker spawned (pid: %s)", worker.pid) - -def post_fork(server, worker): - server.log.info("Worker spawned (pid: %s)", worker.pid) - -def worker_abort(worker): - worker.log.info("worker received SIGABRT signal") -``` - -## Schritt 4: Health-Check und Monitoring implementieren - -### Health-Check-Endpunkt hinzufügen (`src/main.py`) - -```python -from fastapi import FastAPI, status, Depends -from fastapi.responses import JSONResponse -import psutil -import time -from datetime import datetime - -app = FastAPI( - title="Dockerized Todo API", - description="Dockerized todo management API", - version="1.0.0" -) - -# Application start time -start_time = time.time() - -@app.get("/health", status_code=status.HTTP_200_OK) -async def health_check(): - """ - Container health check endpoint - """ - current_time = time.time() - uptime = current_time - start_time - - # System resource information - memory_info = psutil.virtual_memory() - cpu_percent = psutil.cpu_percent(interval=1) - - health_data = { - "status": "healthy", - "timestamp": datetime.utcnow().isoformat(), - "uptime_seconds": round(uptime, 2), - "version": app.version, - "system": { - "memory_usage_percent": memory_info.percent, - "memory_available_mb": round(memory_info.available / 1024 / 1024, 2), - "cpu_usage_percent": cpu_percent, - }, - "checks": { - "database": await check_database_connection(), - "redis": await check_redis_connection(), - "disk_space": check_disk_space(), - } - } - - # Check if all checks passed - all_checks_passed = all(health_data["checks"].values()) - - if not all_checks_passed: - return JSONResponse( - status_code=status.HTTP_503_SERVICE_UNAVAILABLE, - content=health_data - ) - - return health_data - -async def check_database_connection() -> bool: - """Check database connection status""" - try: - # In der echten Implementierung sollte hier die Datenbankverbindung geprüft werden - return True - except Exception: - return False - -async def check_redis_connection() -> bool: - """Status der Redis-Verbindung prüfen""" - try: - # In einer echten Implementierung würde hier die Redis-Verbindung geprüft - return True - except Exception: - return False - -def check_disk_space() -> bool: - """Check disk space""" - disk_usage = psutil.disk_usage('/') - free_percentage = (disk_usage.free / disk_usage.total) * 100 - return free_percentage > 10 # 10% or more free space needed - -@app.get("/health/ready", status_code=status.HTTP_200_OK) -async def readiness_check(): - """ - Kubernetes readiness probe endpoint - """ - # Check if application is ready to receive traffic - return {"status": "ready", "timestamp": datetime.utcnow().isoformat()} - -@app.get("/health/live", status_code=status.HTTP_200_OK) -async def liveness_check(): - """ - Kubernetes liveness probe endpoint - """ - return {"status": "alive", "timestamp": datetime.utcnow().isoformat()} -``` - -## Schritt 5: Nginx-Reverse-Proxy konfigurieren - -### Nginx-Konfiguration für die Entwicklung (`nginx/nginx.conf`) - -```nginx -events { - worker_connections 1024; -} - -http { - upstream fastapi_backend { - # Specify backend by container name - server app:8000; - } - - # Define log format - log_format main '$remote_addr - $remote_user [$time_local] "$request" ' - '$status $body_bytes_sent "$http_referer" ' - '"$http_user_agent" "$http_x_forwarded_for" ' - 'rt=$request_time uct="$upstream_connect_time" ' - 'uht="$upstream_header_time" urt="$upstream_response_time"'; - - access_log /var/log/nginx/access.log main; - error_log /var/log/nginx/error.log warn; - - # Default settings - sendfile on; - tcp_nopush on; - tcp_nodelay on; - keepalive_timeout 65; - types_hash_max_size 2048; - client_max_body_size 100M; - - # Gzip compression - gzip on; - gzip_vary on; - gzip_min_length 1024; - gzip_types text/plain text/css text/xml text/javascript - application/json application/javascript application/xml+rss - application/atom+xml image/svg+xml; - - server { - listen 80; - server_name localhost; - - # Security headers - add_header X-Content-Type-Options nosniff; - add_header X-Frame-Options DENY; - add_header X-XSS-Protection "1; mode=block"; - - # Health check endpoint - location /health { - proxy_pass http://fastapi_backend; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; - - # Health check should respond quickly - proxy_connect_timeout 5s; - proxy_send_timeout 5s; - proxy_read_timeout 5s; - } - - # API endpoint - location / { - proxy_pass http://fastapi_backend; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; - - # Timeout settings - proxy_connect_timeout 30s; - proxy_send_timeout 30s; - proxy_read_timeout 30s; - - # Buffering settings - proxy_buffering on; - proxy_buffer_size 4k; - proxy_buffers 8 4k; - } - - # Static file caching (future use) - location /static { - expires 1y; - add_header Cache-Control public; - add_header ETag ""; - } - } -} -``` - -### Nginx-Konfiguration für die Produktion (`nginx/nginx.prod.conf`) - -```nginx -events { - worker_connections 2048; -} - -http { - upstream fastapi_backend { - # Load balancing for multiple app instances - server app:8000 max_fails=3 fail_timeout=30s; - # server app2:8000 max_fails=3 fail_timeout=30s; # For scaling - - # Keep-alive - keepalive 32; - } - - # Security settings - server_tokens off; - - # Rate limiting - limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s; - limit_req_zone $binary_remote_addr zone=health:10m rate=100r/s; - - # SSL settings - ssl_protocols TLSv1.2 TLSv1.3; - ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384; - ssl_prefer_server_ciphers off; - ssl_session_cache shared:SSL:10m; - ssl_session_timeout 10m; - - server { - listen 80; - server_name your-domain.com; - return 301 https://$server_name$request_uri; - } - - server { - listen 443 ssl http2; - server_name your-domain.com; - - ssl_certificate /etc/nginx/ssl/cert.pem; - ssl_certificate_key /etc/nginx/ssl/key.pem; - - # Security headers - add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; - add_header X-Content-Type-Options nosniff always; - add_header X-Frame-Options DENY always; - add_header X-XSS-Protection "1; mode=block" always; - add_header Referrer-Policy "strict-origin-when-cross-origin" always; - - # Health check (rate limit applied) - location /health { - limit_req zone=health burst=20 nodelay; - proxy_pass http://fastapi_backend; - include /etc/nginx/proxy_params; - } - - # API endpoint (rate limit applied) - location / { - limit_req zone=api burst=20 nodelay; - proxy_pass http://fastapi_backend; - include /etc/nginx/proxy_params; - } - } -} -``` - -## Schritt 6: Container bauen und starten - -### In der Entwicklungsumgebung ausführen - -
- -```console -$ cd dockerized-todo-api - -# Build Docker image -$ docker-compose build -Building app -Step 1/15 : FROM python:3.12-slim as builder - ---> abc123def456 -Step 2/15 : RUN apt-get update && apt-get install -y build-essential curl - ---> Running in xyz789abc123 -... -Successfully built def456ghi789 -Successfully tagged dockerized-todo-api_app:latest - -# Run container (background) -$ docker-compose up -d -Creating network "dockerized-todo-api_app-network" with driver "bridge" -Creating volume "dockerized-todo-api_redis_data" with default driver -Creating dockerized-todo-redis ... done -Creating dockerized-todo-api ... done -Creating dockerized-todo-nginx ... done - -# Check container status -$ docker-compose ps - Name Command State Ports ------------------------------------------------------------------------------------------------- -dockerized-todo-api ./scripts/start.sh Up (healthy) 8000/tcp -dockerized-todo-nginx /docker-entrypoint.sh ngin ... Up 0.0.0.0:80->80/tcp, :::80->80/tcp -dockerized-todo-redis docker-entrypoint.sh redis ... Up (healthy) 0.0.0.0:6379->6379/tcp, :::6379->6379/tcp -``` - -
- -### Logs prüfen - -
- -```console -# Check all service logs -$ docker-compose logs - -# Check specific service logs -$ docker-compose logs app -$ docker-compose logs nginx -$ docker-compose logs redis - -# Check real-time logs -$ docker-compose logs -f app -``` - -
- -### Health-Check-Test - -
- -```console -# Basic health check -$ curl http://localhost/health -{ - "status": "healthy", - "timestamp": "2024-01-01T12:00:00.123456", - "uptime_seconds": 45.67, - "version": "1.0.0", - "system": { - "memory_usage_percent": 25.3, - "memory_available_mb": 3072.45, - "cpu_usage_percent": 5.2 - }, - "checks": { - "database": true, - "redis": true, - "disk_space": true - } -} - -# Kubernetes probe test -$ curl http://localhost/health/ready -$ curl http://localhost/health/live -``` - -
- -## Schritt 7: Produktionsdeployment - -### Umgebungsvariablen setzen (`.env.prod`) - -```bash -# Application settings -ENVIRONMENT=production -DEBUG=false -SECRET_KEY=your-super-secret-key-here -WORKERS=4 - -# Database settings -DATABASE_URL=postgresql://user:password@db:5432/todoapp -REDIS_URL=redis://:password@redis:6379/0 -REDIS_PASSWORD=your-redis-password - -# Logging settings -LOG_LEVEL=info -LOG_FILE=/app/logs/app.log - -# Security settings -ALLOWED_HOSTS=["your-domain.com"] -CORS_ORIGINS=["https://your-frontend.com"] - -# Monitoring -SENTRY_DSN=https://your-sentry-dsn@sentry.io/project-id -``` - -### Befehle für das Produktionsdeployment - -
- -```console -# Deploy in production environment -$ docker-compose -f docker-compose.prod.yml --env-file .env.prod up -d - -# Scaling (app instance scaling) -$ docker-compose -f docker-compose.prod.yml up -d --scale app=3 - -# Rolling update -$ docker-compose -f docker-compose.prod.yml build app -$ docker-compose -f docker-compose.prod.yml up -d --no-deps app - -# Safe shutdown before backup -$ docker-compose -f docker-compose.prod.yml down --timeout 30 -``` - -
- -## Schritt 8: Monitoring und Logging - -### Ressourcen-Monitoring von Docker-Containern - -
- -```console -# Check real-time resource usage -$ docker stats - -CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS -abc123def456 dockerized-todo-api 2.34% 128.5MiB / 1GiB 12.55% 1.23MB / 456kB 12.3MB / 4.56MB 15 -def456ghi789 dockerized-todo-nginx 0.12% 12.5MiB / 256MiB 4.88% 456kB / 1.23MB 1.23MB / 456kB 3 -ghi789jkl012 dockerized-todo-redis 1.45% 32.1MiB / 512MiB 6.27% 789kB / 2.34MB 4.56MB / 1.23MB 4 - -# Check specific container details -$ docker inspect dockerized-todo-api - -# Check container internal processes -$ docker-compose exec app ps aux -``` - -
- -### Log-Aggregation und -Analyse - -```yaml -# docker-compose.logging.yml -version: '3.8' - -services: - # ELK Stack for log aggregation - elasticsearch: - image: docker.elastic.co/elasticsearch/elasticsearch:8.6.0 - environment: - - discovery.type=single-node - - xpack.security.enabled=false - volumes: - - elasticsearch_data:/usr/share/elasticsearch/data - networks: - - logging - - logstash: - image: docker.elastic.co/logstash/logstash:8.6.0 - volumes: - - ./logstash/pipeline:/usr/share/logstash/pipeline:ro - - ./logstash/config:/usr/share/logstash/config:ro - networks: - - logging - depends_on: - - elasticsearch - - kibana: - image: docker.elastic.co/kibana/kibana:8.6.0 - ports: - - "5601:5601" - environment: - - ELASTICSEARCH_HOSTS=http://elasticsearch:9200 - networks: - - logging - depends_on: - - elasticsearch - - # Fluentd for log collection - fluentd: - image: fluent/fluentd:v1.16-debian-1 - volumes: - - ./fluentd/conf:/fluentd/etc:ro - - /var/log:/var/log:ro - networks: - - logging - depends_on: - - elasticsearch - -volumes: - elasticsearch_data: - -networks: - logging: - driver: bridge -``` - -### Prometheus-Metriken sammeln - -```python -# src/monitoring.py -from prometheus_client import Counter, Histogram, Gauge, generate_latest -from fastapi import Request, Response -import time - -# Define metrics -REQUEST_COUNT = Counter( - 'http_requests_total', - 'Total HTTP requests', - ['method', 'endpoint', 'status_code'] -) - -REQUEST_DURATION = Histogram( - 'http_request_duration_seconds', - 'HTTP request duration in seconds', - ['method', 'endpoint'] -) - -ACTIVE_CONNECTIONS = Gauge( - 'active_connections', - 'Number of active connections' -) - -async def metrics_middleware(request: Request, call_next): - """Prometheus metric collection middleware""" - start_time = time.time() - method = request.method - endpoint = request.url.path - - ACTIVE_CONNECTIONS.inc() - - try: - response = await call_next(request) - status_code = response.status_code - except Exception as e: - status_code = 500 - raise - finally: - duration = time.time() - start_time - REQUEST_DURATION.labels(method=method, endpoint=endpoint).observe(duration) - REQUEST_COUNT.labels(method=method, endpoint=endpoint, status_code=status_code).inc() - ACTIVE_CONNECTIONS.dec() - - return response - -@app.get("/metrics") -async def get_metrics(): - """Prometheus metric endpoint""" - return Response(generate_latest(), media_type="text/plain") -``` - -## Schritt 9: CI/CD-Pipeline aufbauen - -### GitHub-Actions-Workflow (`.github/workflows/deploy.yml`) - -```yaml -name: Deploy to Production - -on: - push: - branches: [main] - pull_request: - branches: [main] - -env: - REGISTRY: ghcr.io - IMAGE_NAME: ${{ github.repository }} - -jobs: - test: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - - name: Set up Python - uses: actions/setup-python@v4 - with: - python-version: '3.12' - - - name: Install dependencies - run: | - python -m pip install --upgrade pip - pip install -r requirements.txt - pip install pytest pytest-asyncio httpx - - - name: Run tests - run: | - pytest tests/ -v --cov=src --cov-report=xml - - - name: Upload coverage reports - uses: codecov/codecov-action@v3 - with: - file: ./coverage.xml - - build: - needs: test - runs-on: ubuntu-latest - if: github.event_name == 'push' && github.ref == 'refs/heads/main' - - steps: - - uses: actions/checkout@v4 - - - name: Log in to Container Registry - uses: docker/login-action@v3 - with: - registry: ${{ env.REGISTRY }} - username: ${{ github.actor }} - password: ${{ secrets.GITHUB_TOKEN }} - - - name: Extract metadata - id: meta - uses: docker/metadata-action@v5 - with: - images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} - tags: | - type=ref,event=branch - type=ref,event=pr - type=sha - type=raw,value=latest - - - name: Build and push Docker image - uses: docker/build-push-action@v5 - with: - context: . - file: ./Dockerfile - push: true - tags: ${{ steps.meta.outputs.tags }} - labels: ${{ steps.meta.outputs.labels }} - cache-from: type=gha - cache-to: type=gha,mode=max - - deploy: - needs: build - runs-on: ubuntu-latest - if: github.event_name == 'push' && github.ref == 'refs/heads/main' - - steps: - - uses: actions/checkout@v4 - - - name: Deploy to production - uses: appleboy/ssh-action@v1.0.0 - with: - host: ${{ secrets.PROD_HOST }} - username: ${{ secrets.PROD_USERNAME }} - key: ${{ secrets.PROD_SSH_KEY }} - script: | - cd /opt/dockerized-todo-api - - # Pull new image - docker-compose -f docker-compose.prod.yml pull - - # Rolling update - docker-compose -f docker-compose.prod.yml up -d --no-deps app - - # Health check - sleep 30 - curl -f http://localhost/health || exit 1 - - # Clean up previous image - docker image prune -f -``` - -## Schritt 10: Sicherheit verbessern - -### Sicherheitsoptionen für Container - -```dockerfile -# Add security enhancement to Dockerfile - -# Run as non-root user -USER appuser - -# Read-only root filesystem -# docker run --read-only --tmpfs /tmp dockerized-todo-api - -# Limit permissions -# docker run --cap-drop=ALL dockerized-todo-api - -# Network isolation -# docker run --network=none dockerized-todo-api -``` - -### Sicherheitsoptionen für Docker Compose - -```yaml -# Add security settings to docker-compose.yml -services: - app: - # ... existing settings ... - security_opt: - - no-new-privileges:true - cap_drop: - - ALL - cap_add: - - NET_BIND_SERVICE - read_only: true - tmpfs: - - /tmp - - /app/logs - user: "1000:1000" -``` - -### Secrets-Verwaltung - -```yaml -# Add secrets settings to docker-compose.yml -version: '3.8' - -services: - app: - secrets: - - db_password - - api_key - environment: - - DB_PASSWORD_FILE=/run/secrets/db_password - - API_KEY_FILE=/run/secrets/api_key - -secrets: - db_password: - file: ./secrets/db_password.txt - api_key: - external: true -``` - -## Nächste Schritte - -Sie haben die Docker-Containerisierung abgeschlossen! Nächste Schritte zum Ausprobieren: - -1. **[Benutzerdefinierte Antwortbehandlung](custom-response-handling.md)** — fortgeschrittene API-Antwortformate implementieren - - - - - -## Zusammenfassung - -In diesem Tutorial haben wir mit Docker: - -- ✅ Optimierte Container-Images mit mehrstufigen Builds erstellt -- ✅ Entwicklungs-/Produktionsumgebungen mit Docker Compose eingerichtet -- ✅ Nginx-Reverse-Proxy und Lastverteilung konfiguriert -- ✅ Health-Check- und Monitoring-Systeme aufgebaut -- ✅ Automatisiertes Deployment über CI/CD-Pipelines implementiert -- ✅ Produktionsreife Sicherheitsoptionen konfiguriert -- ✅ Systeme für Logging und Metrik-Sammlung implementiert - -Jetzt können Sie FastAPI-Anwendungen sicher und effizient in Produktionsumgebungen deployen! diff --git a/docs/de/tutorial/domain-starter.md b/docs/de/tutorial/domain-starter.md index c06775c0..a46cf4b8 100644 --- a/docs/de/tutorial/domain-starter.md +++ b/docs/de/tutorial/domain-starter.md @@ -363,7 +363,7 @@ Ein erneutes Ausführen von `addroute` erhält bestehende Domänendateien, erste - Die [Architektur-Preset-Matrix](../reference/preset-feature-matrix.md) zeigt, was `fastkit init --interactive` für jedes Preset generiert, einschließlich der Funktionsauswahlen, die unter `domain-starter` manuelle Verdrahtung benötigen. - Das [`fastapi-default`-Tutorial](basic-api-server.md) behandelt die geschichtete Alternative, falls Sie Layouts vergleichen möchten, bevor Sie sich festlegen. -- Für die Datenbankintegration zeigt das [Tutorial Datenbankintegration](database-integration.md) das Muster PostgreSQL + SQLAlchemy + Alembic. Dieselben Ideen passen in `src/app/db/` und die `repository.py`-Dateien je Domäne. +- Für die Datenbankanbindung zeigt das [SQLModel-Tutorial](sqlmodel.md) das Muster asynchrones SQLModel + Alembic. Dieselben Ideen passen in `src/app/db/` und die `repository.py`-Dateien je Domäne. ## Rückblick diff --git a/docs/de/tutorial/first-project.md b/docs/de/tutorial/first-project.md index 26cf6572..0aa0222c 100644 --- a/docs/de/tutorial/first-project.md +++ b/docs/de/tutorial/first-project.md @@ -1238,7 +1238,7 @@ Glückwunsch! Sie haben erfolgreich eine vollständige Blog-API gebaut mit: ### Weiter lernen -1. **[Vorlagen verwenden](../user-guide/using-templates.md)**: erkunden Sie die Vorlage `fastapi-psql-orm` für Datenbankintegration +1. **[Vorlagen verwenden](../user-guide/using-templates.md)**: erkunden Sie die Vorlage `fastapi-sqlmodel` für Datenbankintegration 2. **[Routen hinzufügen](../user-guide/adding-routes.md)**: lernen Sie fortgeschrittenere Routenmuster 3. **[Mitwirken](../contributing/development-setup.md)**: tragen Sie zu FastAPI-fastkit bei diff --git a/docs/de/tutorial/sqlmodel.md b/docs/de/tutorial/sqlmodel.md index c0a6d5b1..d90b800a 100644 --- a/docs/de/tutorial/sqlmodel.md +++ b/docs/de/tutorial/sqlmodel.md @@ -16,7 +16,7 @@ Bauen Sie eine datenbankgestützte API, in der jedes Konzept **einmal** definier - FastAPI-fastkit installiert (`pip install fastapi-fastkit`) - Vertrautheit mit `async`/`await` und grundlegenden SQL-Konzepten -Wenn Sie stattdessen den synchronen, Compose-basierten PostgreSQL-Stack möchten, lesen Sie [Datenbankintegration](database-integration.md), das `fastapi-psql-orm` verwendet. +`fastapi-sqlmodel` funktioniert mit SQLite, PostgreSQL oder MySQL über eine einzige `DATABASE_URL`. ## Schritt 1: Generieren und ausführen diff --git a/docs/de/user-guide/choosing-a-starter.md b/docs/de/user-guide/choosing-a-starter.md index 2a003b55..cb667d49 100644 --- a/docs/de/user-guide/choosing-a-starter.md +++ b/docs/de/user-guide/choosing-a-starter.md @@ -13,10 +13,10 @@ Der Rest dieser Seite erklärt, warum das so ist und wann eine andere Wahl sinnv | Sie sind … | Beginnen Sie mit | |---|---| | Neu bei FastAPI und möchten eine geführte Tour | `fastkit init --interactive` (Preset: **`domain-starter`**) | +| Möchten zuerst die kleinste App lesen | `fastkit startdemo fastapi-hello` | | Möchten eine funktionierende CRUD-Demo zum Lesen und Anpassen | `fastkit startdemo fastapi-default` | | Möchten das kleinstmögliche Gerüst | `fastkit init --interactive` (Preset: **`minimal`**) | | Schreiben einen schnellen Prototyp / ein Single-File-Skript | `fastkit init --interactive` (Preset: **`single-module`**) | -| Brauchen eine echte Datenbank (PostgreSQL + SQLAlchemy + Alembic) | `fastkit startdemo fastapi-psql-orm` | | Möchten asynchrone Persistenz mit Migrationen und generischem CRUD | `fastkit startdemo fastapi-sqlmodel` | | Brauchen vom ersten Tag an Benutzerkonten, Login und geschützte Routen | `fastkit startdemo fastapi-auth-jwt` | | Bauen ein LLM-Chat-Backend mit Streaming und Tools | `fastkit startdemo fastapi-llm-agent` | @@ -28,7 +28,7 @@ Dies sind die beiden Haupteinstiegspunkte. Sie decken unterschiedliche Bedürfni ### `fastkit startdemo