From cc294f6eccb0c6a32d6a7e5ba7f9a769818ce4f4 Mon Sep 17 00:00:00 2001 From: bnbong Date: Fri, 4 Dec 2026 21:13:32 +0900 Subject: [PATCH] [DOCS, FIX] finish the docs translation: remove unused assets, recheck hard sentences - remove the terminal animation assets (termynal) and their settings; no page uses them - remove update_nav_translations.py and setup-i18n-structure.sh, which the current process no longer uses, and point CONTRIBUTING.md to the translation guide - recheck in all six languages the sentences that reviews found mistranslated in later languages, and review the Korean pages that had not been compared with English - translate.py: drop a chunk size that was sized for a retired service - changelog: documentation in seven languages; services step wording Closes #100 Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 2 + CONTRIBUTING.md | 197 +--------- docs/css/custom.css | 14 - docs/css/termynal.css | 101 ----- docs/de/learn/extend.md | 2 +- docs/es/learn/extend.md | 2 +- docs/es/learn/generate.md | 2 +- docs/es/learn/test.md | 2 +- docs/es/learn/understand.md | 2 +- .../contributing/template-creation-guide.md | 2 +- docs/fr/learn/migrate.md | 2 +- docs/fr/learn/understand.md | 2 +- .../contributing/template-creation-guide.md | 2 +- docs/ja/how-to/example-projects.md | 4 +- docs/ja/learn/generate.md | 4 +- docs/ja/learn/migrate.md | 2 +- docs/ja/learn/test.md | 2 +- docs/js/custom.js | 123 ------ docs/js/termynal.js | 263 ------------- docs/ko/contributing/development-setup.md | 2 +- .../contributing/template-creation-guide.md | 4 +- docs/ko/how-to/choose-a-level.md | 2 +- docs/ko/how-to/example-projects.md | 4 +- docs/ko/learn/deploy.md | 2 +- docs/ko/learn/extend.md | 4 +- docs/ko/learn/generate.md | 2 +- docs/ko/learn/understand.md | 2 +- docs/ko/reference/cli.md | 4 +- docs/ko/reference/levels-and-features.md | 4 +- .../contributing/template-creation-guide.md | 4 +- docs/zh/how-to/example-projects.md | 2 +- docs/zh/learn/extend.md | 2 +- docs/zh/learn/generate.md | 2 +- docs/zh/learn/test.md | 2 +- docs/zh/learn/understand.md | 2 +- mkdocs.yml | 13 +- scripts/setup-i18n-structure.sh | 135 ------- scripts/translate.py | 9 +- scripts/update_nav_translations.py | 360 ------------------ tests/test_docs/test_site_structure.py | 21 +- tests/test_docs/test_web_generator_page.py | 4 +- 41 files changed, 76 insertions(+), 1240 deletions(-) delete mode 100644 docs/css/termynal.css delete mode 100644 docs/js/custom.js delete mode 100644 docs/js/termynal.js delete mode 100755 scripts/setup-i18n-structure.sh delete mode 100755 scripts/update_nav_translations.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 71ae6233..b0504f97 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,6 +50,7 @@ Every 401 carries `WWW-Authenticate`, and each project reads its configuration f - A prompt that gets 10 invalid answers, or whose input ends, exits with status 1. `startdemo -y` asks only for the project name, and `runserver` rejects an invalid `app_module` in `[tool.fastapi-fastkit]`. - `init --template` and `startdemo` check the template name before they ask anything, suggest close matches and point to `fastkit list-templates`; the internal template path is shown only with `--debug`. - After `init` or `startdemo` creates a project, fastkit prints a "Next steps" panel with the commands that apply to that run (project folder, environment, reviewing `.env`, database, server, tests, `addroute`, the next level), and puts the same list in the project's `README.md`. The old "To start your project" line is gone. +- The services step of the next steps reads correctly for one service or several. - `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. @@ -114,6 +115,7 @@ Every 401 carries `WWW-Authenticate`, and each project reads its configuration f ### Documentation - The documentation is reorganised into Start, Learn, How-to, Reference and Contributing; the Learn track follows one project from `hello` to `production`, and old page addresses redirect to their new pages. +- The documentation is available in seven languages (English, Korean, Japanese, Chinese, Spanish, French and German), with the same pages, menus and generated tables in each. - CLI reference tables and help texts are generated from the catalog and the CLI, and the configuration-file and environment-variable sections that described settings fastkit never read are removed. - The documentation translation script leaves code and generated blocks untouched, skips hand-translated pages and fails when a page could not be translated; its workflow offers only the provider the script supports. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e8a9d8ab..86b54e06 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -416,203 +416,18 @@ For more detailed information about security requirements and project guidelines ## Contributing Translations -FastAPI-fastkit documentation supports multiple languages. Contributing translations helps users worldwide. +The documentation is published in seven languages: English (`en`), Korean (`ko`), Japanese (`ja`), Chinese (`zh`), Spanish (`es`), French (`fr`) and German (`de`). English in `docs/en/` is the source, and every page exists at the same path under `docs//` in each language. -### Supported Languages +The [Translation Guide](docs/en/contributing/translation-guide.md) describes the whole process: what stays in English, the generated tables, the catalog overlays, the web generator page, the menu labels in `mkdocs.yml`, machine translation with `scripts/translate.py` (`make translate`), and the checks a translation must pass. Follow it rather than this file. -- 🇬🇧 English (en) - Default -- 🇰🇷 Korean (ko) -- 🇯🇵 Japanese (ja) -- 🇨🇳 Chinese (zh) -- 🇪🇸 Spanish (es) -- 🇫🇷 French (fr) -- 🇩🇪 German (de) - -### Translation Setup - -#### 1. Install Dependencies - -```bash -pdm install -G docs -G translation -# Or: pip install mkdocs mkdocs-material mkdocs-static-i18n openai -``` - -#### 2. Set Up API Key - -Get an OpenAI API key (or a key for another OpenAI-compatible API, used with `--api-base-url`) and set it as an environment variable: - -```bash -export TRANSLATION_API_KEY="your-api-key-here" -``` - -#### 3. First-Time Setup (Maintainers Only) - -If this is the first time setting up the i18n structure: - -```bash -./scripts/setup-i18n-structure.sh -``` - -This migrates existing English docs to `docs/en/` and creates language directories. - -### Translating Documentation - -#### Using Make Commands (Recommended) - -```bash -# Translate all docs to all configured languages -make translate - -# Translate to specific language -make translate LANG=ko - -# Specify the model -make translate LANG=ko MODEL=gpt-4 -``` - -#### Using Script Directly +Before opening a translation PR (with the `[DOCS]` tag), run the checks from the guide: ```bash -# Translate all docs to Korean -python scripts/translate.py --target-lang ko --api-provider openai - -# Translate specific files (paths relative to docs/en/) -python scripts/translate.py --target-lang ko --files index.md start/installation.md --api-provider openai - -# Translate without creating PR (for local testing) -python scripts/translate.py --target-lang ko --no-pr --api-provider openai +python scripts/docs_blocks.py --check +python -m pytest tests/test_docs tests/test_catalog -q +mkdocs build --strict -d site ``` -#### Using GitHub Actions - -1. Go to repository → Actions → "Translate Documentation" -2. Click "Run workflow" -3. Select target language and options -4. Wait for automated PR to be created -5. Review and merge the translation - -### Translation Workflow - -1. **Write English documentation** in `docs/en/` -2. **Test locally**: `mkdocs serve` -3. **Commit English version** to main branch -4. **Run translation script** or trigger GitHub Actions -5. **Review PR**: Check formatting, technical terms, links -6. **Merge** and deploy - -### Translation Quality Guidelines - -When reviewing translations: - -- ✅ Markdown formatting is preserved -- ✅ Code blocks are unchanged -- ✅ Technical terms are appropriate -- ✅ Links work correctly -- ✅ Grammar and spelling are correct - -### Manual Translation - -You can also translate manually: - -1. Copy file from `docs/en/` to `docs/{lang}/` -2. Translate the content -3. Create PR with `[DOCS]` tag - -### Adding New Languages - -To add support for a new language: - -1. **Update `mkdocs.yml`**: -```yaml -- locale: pt - name: Português - build: true -``` - -2. **Run translation**: -```bash -python scripts/translate.py --target-lang pt -``` - -### Translation System Architecture - -**Core Components:** - -- **`scripts/translate.py`**: AI-powered translation script - - Calls the OpenAI API, or another OpenAI-compatible API with `--api-base-url` - - Sends only the prose: code blocks and generated blocks stay unchanged - - Creates GitHub PRs automatically - -- **`scripts/setup-i18n-structure.sh`**: Migration tool - - Moves docs to language-specific directories - - Creates symbolic links for shared assets - -- **`.github/workflows/translate-docs.yml`**: GitHub Actions workflow - - Automated translation on trigger - - Manual workflow dispatch - -**Directory Structure:** - -``` -docs/ -├── en/ # English (source) -├── ko/ # Korean -├── ja/ # Japanese -├── zh/ # Chinese -├── es/ # Spanish -├── fr/ # French -├── de/ # German -├── css/ # Shared assets -├── js/ -└── img/ -``` - -### Troubleshooting - -**Import Error:** -```bash -pip install openai -``` - -**API Key Error:** -```bash -export TRANSLATION_API_KEY="your-key" -``` - -**Build Fails:** -```bash -# Ensure docs are in language directories -ls -la docs/en/index.md -``` - -For detailed translation guidelines, see [Translation Guide](docs/en/contributing/translation-guide.md). - -### Updating Navigation Translations - -When you add new documentation pages, update navigation translations: - -**Option 1: Automatic Update (Recommended)** - -```bash -# Update all language nav translations automatically -python scripts/update_nav_translations.py - -# With AI translation for missing items -python scripts/update_nav_translations.py --api-key "your-key" -``` - -**Option 2: Manual Update** - -Edit `mkdocs.yml` and add translations for each language under `nav_translations`: - -```yaml -- locale: ko - nav_translations: - New Page Title: 새로운 페이지 제목 -``` - -**Note:** Korean translations should be kept complete. Other languages use basic translations (Home, User Guide, Tutorial, etc.). Native speakers can contribute more detailed translations via PR. - ## Additional note If you look at source codes, you will see a commentary at the top of the module that describes about the module. diff --git a/docs/css/custom.css b/docs/css/custom.css index eff3c30a..0d8a1d9f 100644 --- a/docs/css/custom.css +++ b/docs/css/custom.css @@ -1,17 +1,3 @@ -.termynal-comment { - color: #4a968f; - font-style: italic; - display: block; -} - -.termy [data-termynal] { - white-space: pre-wrap; -} - -.termy .linenos { - display: none; -} - a.external-link::after { /* \00A0 is a non-breaking space to make the mark be on the same line as the link diff --git a/docs/css/termynal.css b/docs/css/termynal.css deleted file mode 100644 index 998b42b8..00000000 --- a/docs/css/termynal.css +++ /dev/null @@ -1,101 +0,0 @@ -/** - * termynal.js - * - * @author Ines Montani - * @version 0.0.1 - * @license MIT - */ - - :root { - --color-bg: #252a33; - --color-text: #eee; - --color-text-subtle: #a2a2a2; -} - -[data-termynal] { - width: 750px; - max-width: 100%; - background: var(--color-bg); - color: var(--color-text); - font-size: 14px; - font-family: 'Fira Mono', Consolas, Menlo, Monaco, 'Courier New', Courier, monospace; - border-radius: 4px; - padding: 75px 45px 35px; - position: relative; - -webkit-box-sizing: border-box; - box-sizing: border-box; -} - -[data-termynal]:before { - content: ''; - position: absolute; - top: 15px; - left: 15px; - display: inline-block; - width: 15px; - height: 15px; - border-radius: 50%; - /* A little hack to display the window buttons in one pseudo element. */ - background: #d9515d; - -webkit-box-shadow: 25px 0 0 #f4c025, 50px 0 0 #3ec930; - box-shadow: 25px 0 0 #f4c025, 50px 0 0 #3ec930; -} - -[data-termynal]:after { - content: 'bash'; - position: absolute; - color: var(--color-text-subtle); - top: 5px; - left: 0; - width: 100%; - text-align: center; -} - -[data-ty] { - display: block; - line-height: 1.6; -} - -[data-ty]:before { - /* Set up defaults and ensure empty lines are displayed. */ - content: ''; - display: inline-block; - vertical-align: middle; -} - -[data-ty="input"]:before, -[data-ty-prompt]:before { - margin-right: 0.75em; - color: var(--color-text-subtle); -} - -[data-ty="input"]:before { - content: '$'; -} - -[data-ty][data-ty-prompt]:before { - content: attr(data-ty-prompt); -} - -[data-ty-cursor]:after { - content: attr(data-ty-cursor); - font-family: monospace; - margin-left: 0.5em; - -webkit-animation: blink 1s infinite; - animation: blink 1s infinite; -} - - -/* Cursor animation */ - -@-webkit-keyframes blink { - 50% { - opacity: 0; - } -} - -@keyframes blink { - 50% { - opacity: 0; - } -} diff --git a/docs/de/learn/extend.md b/docs/de/learn/extend.md index fd8cc964..e22dcf10 100644 --- a/docs/de/learn/extend.md +++ b/docs/de/learn/extend.md @@ -161,7 +161,7 @@ UserRepositoryDep = Annotated[UserRepository, Depends(get_user_repository)] `uv run pytest -q` meldet jetzt `91 passed`: die 74 Tests, die das Projekt mitgebracht hat, und 17 neue in `tests/test_users.py`. -Zwischen `hello` und `layered` liegt die Stufe `single-file`: die ganze Anwendung in einer einzigen `src/main.py`, dazu Einstellungen und Tests. Dort legt `fastkit addroute` bei der ersten Verwendung die Pakete `api`, `crud`, `schemas` und `core` rund um `src/main.py` an. +Zwischen `hello` und `layered` liegt die Stufe `single-file`: Die ganze Anwendung steckt in einer einzigen `src/main.py`, und das Projekt enthält außerdem Einstellungen und Tests. Dort legt `fastkit addroute` bei der ersten Verwendung die Pakete `api`, `crud`, `schemas` und `core` rund um `src/main.py` an. ## FastAPI-Dokumentation diff --git a/docs/es/learn/extend.md b/docs/es/learn/extend.md index faa69f2e..2c77e9d0 100644 --- a/docs/es/learn/extend.md +++ b/docs/es/learn/extend.md @@ -59,7 +59,7 @@ $ uv run pytest -q ## Cuando un solo archivo no basta -`fastkit addroute` añade un recurso por ti, pero necesita paquetes donde colocar los nuevos módulos. En el proyecto `hello` se niega a hacerlo y te explica por qué: +`fastkit addroute` añade un recurso por ti, pero necesita paquetes donde colocar los nuevos módulos. En el proyecto `hello` se niega a añadir el recurso y te explica por qué: ```console $ fastkit addroute users . diff --git a/docs/es/learn/generate.md b/docs/es/learn/generate.md index bcf29d0b..d6663c09 100644 --- a/docs/es/learn/generate.md +++ b/docs/es/learn/generate.md @@ -117,7 +117,7 @@ async def read_root( FastAPI no escucha los requests por sí mismo. El servidor es uvicorn: acepta las conexiones HTTP y pasa cada request a `app` mediante ASGI, la interfaz estándar entre los servidores web de Python y las aplicaciones. `fastkit runserver` inicia uvicorn con `main:app`, que significa «el objeto `app` de `main.py`». -A partir de los paths, las anotaciones de tipos y los tipos de retorno, FastAPI escribe una descripción OpenAPI de tu API: un documento JSON en `/openapi.json` que enumera cada endpoint, sus parámetros y sus responses. Las páginas de `/docs` y `/redoc` se construyen a partir de ese documento. Muestran lo que FastAPI puede leer del código: los paths, los parámetros, los modelos y los códigos de estado que declaras. Un response que solo lanzas dentro de una función, como el 404 de `read_item`, no aparece a menos que lo declares. +A partir de los paths, las anotaciones de tipos y los tipos de retorno, FastAPI escribe una descripción OpenAPI de tu API: un documento JSON en `/openapi.json` que enumera cada endpoint, sus parámetros y sus responses. Las páginas de `/docs` y `/redoc` se construyen a partir de ese documento. Muestran lo que FastAPI puede leer del código: los paths, los parámetros, los modelos y los códigos de estado que declaras. Un response que solo produces al lanzar una excepción dentro de una función, como el 404 de `read_item`, no aparece a menos que lo declares. ## Documentación de FastAPI diff --git a/docs/es/learn/test.md b/docs/es/learn/test.md index 896b69b1..59c9c9f9 100644 --- a/docs/es/learn/test.md +++ b/docs/es/learn/test.md @@ -1,6 +1,6 @@ # Prueba la aplicación -En esta página ejecutas las pruebas del proyecto `shop` por capas de [Amplía la aplicación](extend.md), lees cómo están construidas y escribes una propia. Aprendes cómo el `TestClient` de FastAPI llama a tu aplicación sin un servidor, cómo los fixtures de pytest preparan cada prueba, cómo `app.dependency_overrides` sustituye una dependencia por una versión de prueba y cómo comprobar la validación y los responses de error. También ves qué pruebas incluye fastkit y cómo las mide la opción de pruebas Coverage. +En esta página ejecutas las pruebas del proyecto `shop` por capas de [Amplía la aplicación](extend.md), lees cómo están construidas y escribes una propia. Aprendes cómo el `TestClient` de FastAPI llama a tu aplicación sin un servidor, cómo los fixtures de pytest preparan cada prueba, cómo `app.dependency_overrides` sustituye una dependencia por una versión de prueba y cómo comprobar la validación y los responses de error. También ves qué pruebas incluye fastkit y cómo la opción de pruebas Coverage mide cuánto código cubren. ## Ejecuta las pruebas diff --git a/docs/es/learn/understand.md b/docs/es/learn/understand.md index d97c9a2a..bdd27950 100644 --- a/docs/es/learn/understand.md +++ b/docs/es/learn/understand.md @@ -125,7 +125,7 @@ HTTP/1.1 422 Unprocessable Entity ## async def o def -Todos los endpoints de `main.py` son funciones `async def`. Dentro de `async def` puedes usar `await` con otro código asíncrono, como un driver de base de datos asíncrono o un cliente HTTP asíncrono, y el servidor atiende otros requests mientras uno espera. Estos endpoints solo leen y escriben en un diccionario, así que nunca esperan. Usa un `def` normal cuando un endpoint llama a una biblioteca que bloquea (uno que no se usa con `await`): FastAPI lo ejecuta entonces en un pool de hilos, de modo que no retiene los demás requests. +Todos los endpoints de `main.py` son funciones `async def`. Dentro de `async def` puedes usar `await` con otro código asíncrono, como un driver de base de datos asíncrono o un cliente HTTP asíncrono, y el servidor atiende otros requests mientras uno espera. Estos endpoints solo leen y escriben en un diccionario, así que nunca esperan. Usa un `def` normal cuando un endpoint llama a una biblioteca que bloquea (una que no se usa con `await`): FastAPI lo ejecuta entonces en un pool de hilos, de modo que no retiene los demás requests. ## Documentación de FastAPI diff --git a/docs/fr/contributing/template-creation-guide.md b/docs/fr/contributing/template-creation-guide.md index d62f0892..4b4c2032 100644 --- a/docs/fr/contributing/template-creation-guide.md +++ b/docs/fr/contributing/template-creation-guide.md @@ -103,7 +103,7 @@ app = FastAPI( ``` - La première ligne est une seule phrase et ne nomme pas fastkit ; la seconde ligne contient l'URL seule, qui doit être l'URL d'une entrée `[[concepts]]` du catalogue. Les deux lignes tiennent en 88 colonnes. -- Un template renvoie vers chaque concept au plus une fois. Les identifiants des commentaires d'un template `level` doivent être exactement ceux de sa liste `concepts` dans le catalogue ; les commentaires d'un template `example` doivent figurer dans sa liste. +- Un template renvoie vers chaque concept au plus une fois. Les identifiants des commentaires d'un template `level` doivent être exactement ceux de sa liste `concepts` dans le catalogue ; les identifiants des commentaires d'un template `example` doivent figurer dans sa liste. - Le bloc se place juste au-dessus du code : ni à l'intérieur d'un bloc d'imports, ni entre un décorateur et sa fonction. - Les fichiers sous `modules/` ne portent aucun commentaire de concept. diff --git a/docs/fr/learn/migrate.md b/docs/fr/learn/migrate.md index 954ec00a..04027eca 100644 --- a/docs/fr/learn/migrate.md +++ b/docs/fr/learn/migrate.md @@ -50,7 +50,7 @@ Un paquet de domaine regroupe dans un même dossier tout ce qui concerne une res ## La session de base de données -Le moteur de SQLAlchemy maintient un pool de connexions à la base de données. Une session emprunte une connexion le temps d'une unité de travail. `src/app/core/database.py` crée l'un et l'autre et remet une session à chaque requête : +Le moteur de SQLAlchemy maintient un pool de connexions à la base de données. Une session emprunte une connexion le temps d'une unité de travail. `src/app/core/database.py` crée le moteur et les sessions, et remet une session à chaque requête : ```python title="src/app/core/database.py" # A dependency with `yield` gives the endpoint a session and closes it afterwards. diff --git a/docs/fr/learn/understand.md b/docs/fr/learn/understand.md index 8a5b7060..e6dc1e11 100644 --- a/docs/fr/learn/understand.md +++ b/docs/fr/learn/understand.md @@ -6,7 +6,7 @@ Cette page parcourt le fichier `main.py` du projet `shop` créé dans [Générer Lisez `main.py` de haut en bas. La première fois que le fichier utilise une notion de FastAPI, un commentaire d'une ou deux lignes l'explique et se termine par le lien vers la page du tutoriel FastAPI qui la traite. Chaque notion n'est commentée qu'une seule fois : un endpoint plus loin qui fait la même chose n'a donc pas de commentaire. -Pour suivre, démarrez le serveur dans le dossier du projet avec `fastkit runserver` et envoyez les requêtes ci-dessous depuis un second terminal. Les articles sont gardés en mémoire : si vous avez déjà créé des articles dans `/docs`, redémarrez d'abord le serveur. Sinon, vos identifiants différeront de ceux de cette page : utilisez alors l'identifiant renvoyé par votre requête POST. Vous pouvez aussi envoyer les mêmes requêtes depuis avec « Try it out ». +Pour suivre, démarrez le serveur dans le dossier du projet avec `fastkit runserver` et envoyez les requêtes ci-dessous depuis un second terminal. Les articles sont gardés en mémoire : si vous avez déjà créé des articles dans `/docs`, redémarrez d'abord le serveur. Si vous ne le redémarrez pas, vos identifiants différeront de ceux de cette page : utilisez alors l'identifiant renvoyé par votre requête POST. Vous pouvez aussi envoyer les mêmes requêtes depuis avec « Try it out ». ## L'application et les modèles diff --git a/docs/ja/contributing/template-creation-guide.md b/docs/ja/contributing/template-creation-guide.md index 45795cab..373000b7 100644 --- a/docs/ja/contributing/template-creation-guide.md +++ b/docs/ja/contributing/template-creation-guide.md @@ -6,7 +6,7 @@ 各テンプレートは `src/fastapi_fastkit/fastapi_project_template/` の下にあるフォルダーで、テンプレート id(`fastapi-`、たとえば `fastapi-auth-jwt`)がフォルダー名になります。同じ場所にある `modules/` はテンプレートではありません。このフォルダーには `fastkit addroute` が書き出すファイルが入っています。 -名前が `-tpl` で終わるファイルは、fastkit がテンプレートをコピーするときにこの接尾辞が取り除かれます。`src/main.py-tpl` は `src/main.py` に、`.env.example-tpl` は `.env.example` になります。Python のファイルはすべて `.py-tpl` で終わる必要があり、ただの `.py` ファイルがあると検査は失敗します。生成時には、コピーしたファイルの中の 4 つのプレースホルダー、``、``、``、`` が置き換えられます。 +名前が `-tpl` で終わるファイルは、fastkit がテンプレートをコピーするときにこの接尾辞が取り除かれます。`src/main.py-tpl` は `src/main.py` に、`.env.example-tpl` は `.env.example` になります。Python のファイルはすべて `.py-tpl` で終わる必要があり、`-tpl` の付かない `.py` ファイルがあると検査は失敗します。生成時には、コピーしたファイルの中の 4 つのプレースホルダー、``、``、``、`` が置き換えられます。 テンプレートには、少なくとも次のものが必要です。 diff --git a/docs/ja/how-to/example-projects.md b/docs/ja/how-to/example-projects.md index bcbdc596..22180307 100644 --- a/docs/ja/how-to/example-projects.md +++ b/docs/ja/how-to/example-projects.md @@ -14,7 +14,7 @@ fastkit には、5 つのレベルのほかに 5 つのサンプルプロジェ -エンドポイントの一覧は、各プロジェクトで `uv sync` を実行した直後に `uv run uvicorn` で起動し、その `/openapi.json` から取得したものです。どのサンプルも `GET /health` に `{"status":"ok"}` で応答しますが、表には載せていません。 +エンドポイントの一覧は、各プロジェクトを `uv sync` の直後に `uv run uvicorn` で起動し、その `/openapi.json` から取得したものです。どのサンプルも `GET /health` に `{"status":"ok"}` で応答しますが、表には載せていません。 ## fastapi-custom-response {#fastapi-custom-response} @@ -146,7 +146,7 @@ $ curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8000/mcp 401 ``` -準備として、ユーザーストアは独自のものを組み込むまで(`src/auth/users.py` の `get_users_db()`)空のままです。ローカルで試す場合は、`.env` で `ENABLE_DEMO_USERS=true` にすると、パスワードが公開されている 3 つのデモアカウントが有効になります(`development` 以外の環境では拒否されます)。MCP のエンドポイントは、ユーザーの JWT か、`.env` の `MCP_API_KEY` に設定したキーを受け付けます。両方の使い方は README の "MCP Authentication" セクションにあります。 +準備として、ユーザーストアは独自のものを組み込むまで(`src/auth/users.py` の `get_users_db()`)空のままです。ローカルで試す場合は、`.env` で `ENABLE_DEMO_USERS=true` にすると、パスワードが公開されている 3 つのデモアカウントが有効になります(`development` 以外の環境では、デモアカウントの有効化は拒否されます)。MCP のエンドポイントは、ユーザーの JWT か、`.env` の `MCP_API_KEY` に設定したキーを受け付けます。両方の使い方は README の "MCP Authentication" セクションにあります。 diff --git a/docs/ja/learn/generate.md b/docs/ja/learn/generate.md index 2d4a4b16..8ea4dc39 100644 --- a/docs/ja/learn/generate.md +++ b/docs/ja/learn/generate.md @@ -56,7 +56,7 @@ Create the project? [Y/n]: ╰──────────────────────────────────────────────────────────────────────────────╯ ``` -Author 行の値は `git config` から取得されます(この例では git に名前が設定されていませんでした)。fastkit は `shop/.venv` に仮想環境を作成し、そこにパッケージをインストールしました。Next steps パネルは、これから行う作業のリストです。プロジェクトの `README.md` にも同じ内容が書かれています。`fastkit init --no-venv` を使うと、fastkit はファイルだけを書き出します。その場合は、git からプロジェクトをクローンしたときと同じように、あとからプロジェクトのフォルダーで `uv sync` を実行して `.venv` を作成します。 +Author 行の値は `git config` から取得されます(この例では git に作成者の名前が設定されていませんでした)。fastkit は `shop/.venv` に仮想環境を作成し、そこにパッケージをインストールしました。Next steps パネルは、これから行う作業のリストです。プロジェクトの `README.md` にも同じ内容が書かれています。`fastkit init --no-venv` を使うと、fastkit はファイルだけを書き出します。その場合は、git からプロジェクトをクローンしたときと同じように、あとからプロジェクトのフォルダーで `uv sync` を実行して `.venv` を作成します。 ## fastkit が作成したもの @@ -117,7 +117,7 @@ async def read_root( FastAPI 自身はリクエストを待ち受けません。サーバーの役割を担うのは uvicorn です。uvicorn は HTTP 接続を受け付け、各リクエストを ASGI 経由で `app` に渡します。ASGI は、Python の Web サーバーとアプリケーションをつなぐ標準のインターフェースです。`fastkit runserver` は uvicorn を `main:app` で起動します。これは「`main.py` の中の `app` オブジェクト」という意味です。 -FastAPI は、パス、型ヒント、戻り値の型から、API の OpenAPI 定義を書き出します。これは `/openapi.json` で提供される JSON ドキュメントで、各エンドポイントとそのパラメータ、レスポンスが記載されています。`/docs` と `/redoc` のページは、このドキュメントをもとに作られています。これらのページに表示されるのは、FastAPI がコードから読み取れる内容、つまり宣言したパス、パラメータ、モデル、ステータスコードです。`read_item` の 404 のように、関数の中で例外を発生させるだけのレスポンスは、宣言しない限り記載されません。 +FastAPI は、パス、型ヒント、戻り値の型から、API の OpenAPI 定義を書き出します。これは `/openapi.json` で提供される JSON ドキュメントで、各エンドポイントとそのパラメータ、レスポンスが記載されています。`/docs` と `/redoc` のページは、このドキュメントをもとに作られています。これらのページに表示されるのは、FastAPI がコードから読み取れる内容、つまり宣言したパス、パラメータ、モデル、ステータスコードです。`read_item` の 404 のように、関数の中で例外として発生させるだけのレスポンスは、宣言しない限り記載されません。 ## FastAPI のドキュメント diff --git a/docs/ja/learn/migrate.md b/docs/ja/learn/migrate.md index 3795334b..da31be5b 100644 --- a/docs/ja/learn/migrate.md +++ b/docs/ja/learn/migrate.md @@ -36,7 +36,7 @@ src/app/main.py ## items というドメイン -ドメインパッケージは、1 つのリソースに関するものをすべて 1 つのフォルダーにまとめます。`src/app/domains/items/` では、`router.py` が HTTP を扱い、`service.py` がルールを持ち、`repository.py` が SQL を実行し、`models.py` がテーブルを、`schemas.py` が JSON を定義します。ルーターは依存関係 `get_item_service(session: SessionDep)` からサービスを受け取ります。この依存関係は、リクエストのデータベースセッションを `ItemRepository` で包み、さらにそれを `ItemService` で包みます。アイテムが見つからないとき、サービスは独自のエラーを発生させ、ルーターがそれを 404 に変換します。ハンドラーは `async def` で、データベースの処理を `await` します。あるリクエストがデータベースを待っている間、サーバーはほかのリクエストを処理します。SQL を書く場所はリポジトリだけです。 +ドメインパッケージは、1 つのリソースに関するものをすべて 1 つのフォルダーにまとめます。`src/app/domains/items/` では、`router.py` が HTTP を扱い、`service.py` がルールを持ち、`repository.py` が SQL を実行し、`models.py` がテーブルを、`schemas.py` が JSON を定義します。ルーターは依存関係 `get_item_service(session: SessionDep)` からサービスを受け取ります。この依存関係は、リクエストのデータベースセッションを `ItemRepository` で包み、さらにそのリポジトリを `ItemService` で包みます。アイテムが見つからないとき、サービスは独自のエラーを発生させ、ルーターがそれを 404 に変換します。ハンドラーは `async def` で、データベースの処理を `await` します。あるリクエストがデータベースを待っている間、サーバーはほかのリクエストを処理します。SQL を書く場所はリポジトリだけです。 ```python title="src/app/domains/items/repository.py" async def add(self, name: str, price: float, in_stock: bool = True) -> Item: diff --git a/docs/ja/learn/test.md b/docs/ja/learn/test.md index 5a790096..bba2bc92 100644 --- a/docs/ja/learn/test.md +++ b/docs/ja/learn/test.md @@ -43,7 +43,7 @@ def client(store: ItemStore) -> Generator[TestClient, None, None]: app.dependency_overrides.clear() ``` -エンドポイントは、依存関係 `get_item_store` からアイテムストアを受け取ります([アプリを拡張する](extend.md)を参照)。`app.dependency_overrides` はアプリケーションが持つ辞書で、キーは依存関係の関数、値は FastAPI がその代わりに呼び出す関数です。ここでは、テスト中のすべてのリクエストが、初期データとして 2 つのアイテムを入れた一時ファイル上のストアを受け取ります。そのため、テストが `src/mocks/mock_items.json` を変更することはありません。`tmp_path` は pytest に組み込まれたフィクスチャで、テストごとに新しい一時ディレクトリを用意します。テストの後、`clear()` がオーバーライドを解除します。この手法は、FastAPI のガイド [Testing dependencies with overrides](https://fastapi.tiangolo.com/advanced/testing-dependencies/) で説明されています。 +エンドポイントは、依存関係 `get_item_store` からアイテムストアを受け取ります([アプリを拡張する](extend.md)を参照)。`app.dependency_overrides` はアプリケーションが持つ辞書で、キーは依存関係の関数、値は FastAPI がその代わりに呼び出す関数です。ここでは、テスト中のすべてのリクエストが、初期データとして 2 つのアイテムを入れ、一時ファイルにデータを保存するストアを受け取ります。そのため、テストが `src/mocks/mock_items.json` を変更することはありません。`tmp_path` は pytest に組み込まれたフィクスチャで、テストごとに新しい一時ディレクトリを用意します。テストの後、`clear()` がオーバーライドを解除します。この手法は、FastAPI のガイド [Testing dependencies with overrides](https://fastapi.tiangolo.com/advanced/testing-dependencies/) で説明されています。 ## テストを 1 つ読む diff --git a/docs/js/custom.js b/docs/js/custom.js deleted file mode 100644 index 0a02f4e7..00000000 --- a/docs/js/custom.js +++ /dev/null @@ -1,123 +0,0 @@ -function setupTermynal() { - document.querySelectorAll(".use-termynal").forEach(node => { - node.style.display = "block"; - new Termynal(node, { - lineDelay: 500 - }); - }); - const progressLiteralStart = "---> 100%"; - const promptLiteralStart = "$ "; - const customPromptLiteralStart = "# "; - const termynalActivateClass = "termy"; - let termynals = []; - - function createTermynals() { - document - .querySelectorAll(`.${termynalActivateClass} .highlight code`) - .forEach(node => { - const text = node.textContent; - const lines = text.split("\n"); - const useLines = []; - let buffer = []; - function saveBuffer() { - if (buffer.length) { - let isBlankSpace = true; - buffer.forEach(line => { - if (line) { - isBlankSpace = false; - } - }); - dataValue = {}; - if (isBlankSpace) { - dataValue["delay"] = 0; - } - if (buffer[buffer.length - 1] === "") { - // A last single
won't have effect - // so put an additional one - buffer.push(""); - } - const bufferValue = buffer.join("
"); - dataValue["value"] = bufferValue; - useLines.push(dataValue); - buffer = []; - } - } - for (let line of lines) { - if (line === progressLiteralStart) { - saveBuffer(); - useLines.push({ - type: "progress" - }); - } else if (line.startsWith(promptLiteralStart)) { - saveBuffer(); - const value = line.replace(promptLiteralStart, "").trimEnd(); - useLines.push({ - type: "input", - value: value - }); - } else if (line.startsWith("// ")) { - saveBuffer(); - const value = "💬 " + line.replace("// ", "").trimEnd(); - useLines.push({ - value: value, - class: "termynal-comment", - delay: 0 - }); - } else if (line.startsWith(customPromptLiteralStart)) { - saveBuffer(); - const promptStart = line.indexOf(promptLiteralStart); - if (promptStart === -1) { - const value = "💬 " + line.replace(customPromptLiteralStart, "").trimEnd(); - useLines.push({ - value: value, - class: "termynal-comment", - delay: 0 - }); - } else { - const prompt = line - .slice(0, promptStart) - .replace(customPromptLiteralStart, ""); - const value = line.slice(promptStart + promptLiteralStart.length); - useLines.push({ - type: "input", - value: value, - prompt: prompt - }); - } - } else { - buffer.push(line); - } - } - saveBuffer(); - const div = document.createElement("div"); - node.replaceWith(div); - const termynal = new Termynal(div, { - lineData: useLines, - noInit: true, - lineDelay: 500 - }); - termynals.push(termynal); - }); - } - - function loadVisibleTermynals() { - termynals = termynals.filter(termynal => { - if (termynal.container.getBoundingClientRect().top - innerHeight <= 0) { - termynal.init(); - return false; - } - return true; - }); - } - window.addEventListener("scroll", loadVisibleTermynals); - createTermynals(); - loadVisibleTermynals(); -} - -async function main() { - setupTermynal() -} - -document$.subscribe(() => { - main() -}) diff --git a/docs/js/termynal.js b/docs/js/termynal.js deleted file mode 100644 index 45bb371c..00000000 --- a/docs/js/termynal.js +++ /dev/null @@ -1,263 +0,0 @@ -/** - * termynal.js - * A lightweight, modern and extensible animated terminal window, using - * async/await. - * - * @author Ines Montani - * @version 0.0.1 - * @license MIT - */ - -'use strict'; - -/** Generate a terminal widget. */ -class Termynal { - /** - * Construct the widget's settings. - * @param {(string|Node)=} container - Query selector or container element. - * @param {Object=} options - Custom settings. - * @param {string} options.prefix - Prefix to use for data attributes. - * @param {number} options.startDelay - Delay before animation, in ms. - * @param {number} options.typeDelay - Delay between each typed character, in ms. - * @param {number} options.lineDelay - Delay between each line, in ms. - * @param {number} options.progressLength - Number of characters displayed as progress bar. - * @param {string} options.progressChar – Character to use for progress bar, defaults to █. - * @param {number} options.progressPercent - Max percent of progress. - * @param {string} options.cursor – Character to use for cursor, defaults to ▋. - * @param {Object[]} lineData - Dynamically loaded line data objects. - * @param {boolean} options.noInit - Don't initialise the animation. - */ - constructor(container = '#termynal', options = {}) { - this.container = (typeof container === 'string') ? document.querySelector(container) : container; - this.pfx = `data-${options.prefix || 'ty'}`; - this.originalStartDelay = this.startDelay = options.startDelay - || parseFloat(this.container.getAttribute(`${this.pfx}-startDelay`)) || 600; - this.originalTypeDelay = this.typeDelay = options.typeDelay - || parseFloat(this.container.getAttribute(`${this.pfx}-typeDelay`)) || 90; - this.originalLineDelay = this.lineDelay = options.lineDelay - || parseFloat(this.container.getAttribute(`${this.pfx}-lineDelay`)) || 1500; - this.progressLength = options.progressLength - || parseFloat(this.container.getAttribute(`${this.pfx}-progressLength`)) || 40; - this.progressChar = options.progressChar - || this.container.getAttribute(`${this.pfx}-progressChar`) || '█'; - this.progressPercent = options.progressPercent - || parseFloat(this.container.getAttribute(`${this.pfx}-progressPercent`)) || 100; - this.cursor = options.cursor - || this.container.getAttribute(`${this.pfx}-cursor`) || '▋'; - this.lineData = this.lineDataToElements(options.lineData || []); - this.loadLines() - if (!options.noInit) this.init() - } - - loadLines() { - // Load all the lines and create the container so that the size is fixed - // Otherwise it would be changing and the user viewport would be constantly - // moving as she/he scrolls - const finish = this.generateFinish() - finish.style.visibility = 'hidden' - this.container.appendChild(finish) - // Appends dynamically loaded lines to existing line elements. - this.lines = [...this.container.querySelectorAll(`[${this.pfx}]`)].concat(this.lineData); - for (let line of this.lines) { - line.style.visibility = 'hidden' - this.container.appendChild(line) - } - const restart = this.generateRestart() - restart.style.visibility = 'hidden' - this.container.appendChild(restart) - this.container.setAttribute('data-termynal', ''); - } - - /** - * Initialise the widget, get lines, clear container and start animation. - */ - init() { - /** - * Calculates width and height of Termynal container. - * If container is empty and lines are dynamically loaded, defaults to browser `auto` or CSS. - */ - const containerStyle = getComputedStyle(this.container); - this.container.style.width = containerStyle.width !== '0px' ? - containerStyle.width : undefined; - this.container.style.minHeight = containerStyle.height !== '0px' ? - containerStyle.height : undefined; - - this.container.setAttribute('data-termynal', ''); - this.container.innerHTML = ''; - for (let line of this.lines) { - line.style.visibility = 'visible' - } - this.start(); - } - - /** - * Start the animation and rener the lines depending on their data attributes. - */ - async start() { - this.addFinish() - await this._wait(this.startDelay); - - for (let line of this.lines) { - const type = line.getAttribute(this.pfx); - const delay = line.getAttribute(`${this.pfx}-delay`) || this.lineDelay; - - if (type == 'input') { - line.setAttribute(`${this.pfx}-cursor`, this.cursor); - await this.type(line); - await this._wait(delay); - } - - else if (type == 'progress') { - await this.progress(line); - await this._wait(delay); - } - - else { - this.container.appendChild(line); - await this._wait(delay); - } - - line.removeAttribute(`${this.pfx}-cursor`); - } - this.addRestart() - this.finishElement.style.visibility = 'hidden' - this.lineDelay = this.originalLineDelay - this.typeDelay = this.originalTypeDelay - this.startDelay = this.originalStartDelay - } - - generateRestart() { - const restart = document.createElement('a') - restart.onclick = (e) => { - e.preventDefault() - this.container.innerHTML = '' - this.init() - } - restart.href = '#' - restart.setAttribute('data-terminal-control', '') - restart.innerHTML = "restart ↻" - return restart - } - - generateFinish() { - const finish = document.createElement('a') - finish.onclick = (e) => { - e.preventDefault() - this.lineDelay = 0 - this.typeDelay = 0 - this.startDelay = 0 - } - finish.href = '#' - finish.setAttribute('data-terminal-control', '') - finish.innerHTML = "fast →" - this.finishElement = finish - return finish - } - - addRestart() { - const restart = this.generateRestart() - this.container.appendChild(restart) - } - - addFinish() { - const finish = this.generateFinish() - this.container.appendChild(finish) - } - - /** - * Animate a typed line. - * @param {Node} line - The line element to render. - */ - async type(line) { - const chars = [...line.textContent]; - line.textContent = ''; - this.container.appendChild(line); - - for (let char of chars) { - const delay = line.getAttribute(`${this.pfx}-typeDelay`) || this.typeDelay; - await this._wait(delay); - line.textContent += char; - } - } - - /** - * Animate a progress bar. - * @param {Node} line - The line element to render. - */ - async progress(line) { - const progressLength = line.getAttribute(`${this.pfx}-progressLength`) - || this.progressLength; - const progressChar = line.getAttribute(`${this.pfx}-progressChar`) - || this.progressChar; - const chars = progressChar.repeat(progressLength); - const progressPercent = line.getAttribute(`${this.pfx}-progressPercent`) - || this.progressPercent; - line.textContent = ''; - this.container.appendChild(line); - - for (let i = 1; i < chars.length + 1; i++) { - await this._wait(this.typeDelay); - const percent = Math.round(i / chars.length * 100); - line.textContent = `${chars.slice(0, i)} ${percent}%`; - if (percent>progressPercent) { - break; - } - } - } - - /** - * Helper function for animation delays, called with `await`. - * @param {number} time - Timeout, in ms. - */ - _wait(time) { - return new Promise(resolve => setTimeout(resolve, time)); - } - - /** - * Converts line data objects into line elements. - * - * @param {Object[]} lineData - Dynamically loaded lines. - * @param {Object} line - Line data object. - * @returns {Element[]} - Array of line elements. - */ - lineDataToElements(lineData) { - return lineData.map(line => { - let div = document.createElement('div'); - div.innerHTML = `${line.value || ''}`; - - return div.firstElementChild; - }); - } - - /** - * Helper function for generating attributes string. - * - * @param {Object} line - Line data object. - * @returns {string} - String of attributes. - */ - _attributes(line) { - let attrs = ''; - for (let prop in line) { - // Custom add class - if (prop === 'class') { - attrs += ` class=${line[prop]} ` - continue - } - if (prop === 'type') { - attrs += `${this.pfx}="${line[prop]}" ` - } else if (prop !== 'value') { - attrs += `${this.pfx}-${prop}="${line[prop]}" ` - } - } - return attrs; - } -} - -/** -* HTML API: If current script has container(s) specified, initialise Termynal. -*/ -if (document.currentScript.hasAttribute('data-termynal-container')) { - const containers = document.currentScript.getAttribute('data-termynal-container'); - containers.split('|') - .forEach(container => new Termynal(container)) -} diff --git a/docs/ko/contributing/development-setup.md b/docs/ko/contributing/development-setup.md index 0bfec99d..846b0950 100644 --- a/docs/ko/contributing/development-setup.md +++ b/docs/ko/contributing/development-setup.md @@ -6,7 +6,7 @@ - Python 3.12 이상(`requires-python = ">=3.12"`)이 필요합니다. - git이 필요합니다. -- CI 워크플로가 사용하는 PDM이나 uv가 필요합니다. pip로도 작업할 수 있습니다. +- PDM이나 uv가 필요합니다(CI 워크플로는 PDM을 사용합니다). pip로도 작업할 수 있습니다. - Node.js(CI는 22 버전을 사용합니다)는 웹 생성기의 결과를 명령줄의 결과와 비교할 때만 필요합니다. ## 설치 diff --git a/docs/ko/contributing/template-creation-guide.md b/docs/ko/contributing/template-creation-guide.md index 24d943b1..bfc9dfa4 100644 --- a/docs/ko/contributing/template-creation-guide.md +++ b/docs/ko/contributing/template-creation-guide.md @@ -6,7 +6,7 @@ 각 템플릿은 `src/fastapi_fastkit/fastapi_project_template/` 아래의 폴더 하나이며, 폴더 이름은 템플릿 id(`fastapi-` 형식, 예: `fastapi-auth-jwt`)와 같습니다. 같은 폴더에 있는 `modules/`는 템플릿이 아닙니다. 이 폴더에는 `fastkit addroute`가 쓰는 파일이 들어 있습니다. -이름이 `-tpl`로 끝나는 파일은 fastkit이 템플릿을 복사할 때 이 접미사가 빠집니다. 예를 들어 `src/main.py-tpl`은 `src/main.py`가 되고, `.env.example-tpl`은 `.env.example`이 됩니다. 모든 Python 파일은 이름이 `.py-tpl`로 끝나야 하며, 일반 `.py` 파일이 있으면 템플릿 검사가 실패합니다. 프로젝트를 생성할 때는 복사된 파일에서 ``, ``, ``, `` 플레이스홀더 네 개를 실제 값으로 바꿉니다. +이름이 `-tpl`로 끝나는 파일은 fastkit이 템플릿을 복사할 때 이 접미사가 빠집니다. 예를 들어 `src/main.py-tpl`은 `src/main.py`가 되고, `.env.example-tpl`은 `.env.example`이 됩니다. 모든 Python 파일은 이름이 `.py-tpl`로 끝나야 하며, `-tpl` 접미사가 없는 `.py` 파일이 있으면 템플릿 검사가 실패합니다. 프로젝트를 생성할 때는 복사된 파일에서 ``, ``, ``, `` 플레이스홀더 네 개를 실제 값으로 바꿉니다. 템플릿에는 최소한 다음 파일이 있어야 합니다. @@ -67,7 +67,7 @@ addroute = false ### HTTP API -비즈니스 라우트가 있는 템플릿은 [생성된 프로젝트](../reference/generated-projects.md#http-api)에서 설명하는 API를 따릅니다. 라우트는 `settings.API_V1_PREFIX` 아래에 두고, 루트의 `GET /health`는 `{"status": "ok"}`를 반환합니다. 목록 조회는 `limit`과 `offset`을 받아 `Page[XRead]`를 반환하고, 생성은 201과 `Location`을, 삭제는 204를 반환합니다. `PUT`은 리소스를 교체하고 `PATCH`는 일부를 수정하며, 리소스가 없으면 404와 `{"detail": " not found"}`를 반환합니다. 스키마 이름은 `XCreate`, `XUpdate`, `XRead`를 사용합니다. 라우터에는 자신의 리소스 접두사만 지정합니다(`APIRouter(prefix="/items", tags=["items"])`). +비즈니스 라우트가 있는 템플릿은 [생성된 프로젝트](../reference/generated-projects.md#http-api)에서 설명하는 API를 따릅니다. 라우트는 `settings.API_V1_PREFIX` 아래에 두고, 루트의 `GET /health`는 `{"status": "ok"}`를 반환합니다. 목록 조회는 `limit`과 `offset`을 받아 `Page[XRead]`를 반환하고, 생성은 201과 `Location`을, 삭제는 204를 반환합니다. `PUT`은 리소스를 교체하고 `PATCH`는 리소스를 수정하며, 리소스가 없으면 404와 `{"detail": " not found"}`를 반환합니다. 스키마 이름은 `XCreate`, `XUpdate`, `XRead`를 사용합니다. 라우터에는 자신의 리소스 접두사만 지정합니다(`APIRouter(prefix="/items", tags=["items"])`). 템플릿에 `core/pagination.py-tpl`과 `core/responses.py-tpl`이 있다면, 이 파일들은 `fastapi_project_template/modules/core/`에 있는 파일과 완전히 같아야 합니다. 저장소의 테스트가 모든 사본을 비교합니다. diff --git a/docs/ko/how-to/choose-a-level.md b/docs/ko/how-to/choose-a-level.md index cd1939c1..f70a47f4 100644 --- a/docs/ko/how-to/choose-a-level.md +++ b/docs/ko/how-to/choose-a-level.md @@ -1,6 +1,6 @@ # 레벨 또는 예제 고르기 -`fastkit init`은 `main.py` 파일 하나짜리부터 프로덕션 구조까지, 다섯 가지 레벨 중 하나로 프로젝트를 만듭니다. 레벨 대신 `fastkit init --template`을 사용하면 다섯 가지 예제 프로젝트 중 하나를 복사합니다. 이 페이지는 둘 중 무엇을 고를지 정하는 데 도움을 줍니다. +`fastkit init`은 `main.py` 파일 하나짜리부터 프로덕션 구조까지, 다섯 가지 레벨 중 하나로 프로젝트를 만듭니다. 레벨 대신 `fastkit init --template`을 사용하면 다섯 가지 예제 프로젝트 중 하나를 복사합니다. 이 페이지는 레벨이나 예제 중 하나를 고르는 데 도움을 줍니다. ## 필요한 것에 따라 고르기 diff --git a/docs/ko/how-to/example-projects.md b/docs/ko/how-to/example-projects.md index f1761a45..5aee8859 100644 --- a/docs/ko/how-to/example-projects.md +++ b/docs/ko/how-to/example-projects.md @@ -18,7 +18,7 @@ fastkit은 다섯 가지 레벨 외에 다섯 가지 예제 프로젝트도 제 ## fastapi-custom-response {#fastapi-custom-response} -이 예제는 오류를 포함한 모든 JSON 응답을 하나의 응답 envelope로 감쌉니다. envelope에는 `timestamp`, `status`, `code`, `path`, `message`가 들어 있습니다. 예외 핸들러가 `HTTPException`, 유효성 검사 오류, 처리되지 않은 예외를 모두 같은 envelope로 감쌉니다. 아이템 데이터는 JSON 파일(`src/mocks/mock_items.json`)에 저장되며, 비동기로 읽고 씁니다. `uv sync` 외에는 따로 준비할 것이 없습니다. 표 아래의 요청은 envelope에 담긴 404 응답을 보여 줍니다. +이 예제는 오류를 포함한 모든 JSON 응답을 하나의 응답 envelope로 감쌉니다. envelope에는 `timestamp`, `status`, `code`, `path`, `message`가 들어 있습니다. 예외 핸들러가 `HTTPException`, 검증 오류, 처리되지 않은 예외를 모두 같은 envelope로 감쌉니다. 아이템 데이터는 JSON 파일(`src/mocks/mock_items.json`)에 저장되며, 비동기로 읽고 씁니다. `uv sync` 외에는 따로 준비할 것이 없습니다. 표 아래의 요청은 envelope에 담긴 404 응답을 보여 줍니다. ```console $ fastkit init --template fastapi-custom-response --project-name items_api @@ -146,7 +146,7 @@ $ curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8000/mcp 401 ``` -준비 사항: 직접 사용자 저장소를 연결하기 전까지(`src/auth/users.py`의 `get_users_db()`) 사용자 저장소는 비어 있습니다. 로컬에서 실험할 때는 `.env`에 `ENABLE_DEMO_USERS=true`를 설정하면, 비밀번호가 공개된 데모 계정 세 개가 활성화됩니다(`development` 이외의 환경에서는 거부됩니다). MCP 엔드포인트는 사용자의 JWT를 받거나, `.env`의 `MCP_API_KEY`에 설정한 키를 받습니다. 두 방법 모두 README의 "MCP Authentication" 섹션에서 설명합니다. +준비 사항: 직접 사용자 저장소를 연결하기 전까지(`src/auth/users.py`의 `get_users_db()`) 사용자 저장소는 비어 있습니다. 로컬에서 실험할 때는 `.env`에 `ENABLE_DEMO_USERS=true`를 설정하면, 비밀번호가 공개된 데모 계정 세 개가 활성화됩니다(`development` 이외의 환경에서는 데모 계정 활성화가 거부됩니다). MCP 엔드포인트는 사용자의 JWT를 받거나, `.env`의 `MCP_API_KEY`에 설정한 키를 받습니다. 두 방법 모두 README의 "MCP Authentication" 섹션에서 설명합니다. diff --git a/docs/ko/learn/deploy.md b/docs/ko/learn/deploy.md index 10ccf332..1a0d9e78 100644 --- a/docs/ko/learn/deploy.md +++ b/docs/ko/learn/deploy.md @@ -153,7 +153,7 @@ shop-app-1 | {"timestamp": "2026-12-03T17:03:16+0000", "level": "INFO", "logger shop-app-1 | {"timestamp": "2026-12-03T17:03:16+0000", "level": "INFO", "logger": "app.access", "message": "GET /api/v1/users/me 200", "request_id": "ada-1", "method": "GET", "path": "/api/v1/users/me", "status_code": 200, "duration_ms": 3.51, "client": "192.168.176.1"} ``` -미들웨어는 `call_next`를 호출하기 전에 ID를 설정하고, 액세스 로그를 기록한 뒤에 ID를 지웁니다. 그 사이에 엔드포인트와 의존성이 남긴 로그 줄에는 이 ID가 들어가고, 액세스 로그에도 같은 ID가 들어갑니다. 따라서 클라이언트가 알려 준 `X-Request-ID`로 한 요청에 해당하는 로그 줄을 모두 찾을 수 있습니다. 처리되지 않은 예외가 발생했을 때 uvicorn이 출력하는 트레이스백은 그 이후에 기록되므로 `"request_id": "-"`로 표시됩니다. 이 경우에도 해당 요청의 액세스 로그(상태 코드 500)에는 ID가 들어 있습니다. +미들웨어는 `call_next`를 호출하기 전에 ID를 설정하고, 액세스 로그를 기록한 뒤에 ID를 지웁니다. 그 사이에 엔드포인트와 의존성이 남긴 로그 줄에는 이 ID가 들어가고, 액세스 로그에도 같은 ID가 들어갑니다. 따라서 클라이언트가 알려 준 `X-Request-ID`로 한 요청에 해당하는 로그 줄을 찾을 수 있습니다. 처리되지 않은 예외가 발생했을 때 uvicorn이 출력하는 트레이스백은 그 이후에 기록되므로 `"request_id": "-"`로 표시됩니다. 이 경우에도 해당 요청의 액세스 로그(상태 코드 500)에는 ID가 들어 있습니다. ## 지속적 통합 diff --git a/docs/ko/learn/extend.md b/docs/ko/learn/extend.md index 8245fc65..81c845b6 100644 --- a/docs/ko/learn/extend.md +++ b/docs/ko/learn/extend.md @@ -59,7 +59,7 @@ $ uv run pytest -q ## 파일 하나로 부족해질 때 -`fastkit addroute`는 리소스를 대신 추가해 주지만, 새 모듈을 넣을 패키지가 있어야 동작합니다. `hello` 프로젝트에서는 이 명령이 실행을 거부하고 그 이유를 알려 줍니다. +`fastkit addroute`는 리소스를 대신 추가해 주지만, 새 모듈을 넣을 패키지가 있어야 동작합니다. `hello` 프로젝트에서는 이 명령이 리소스 추가를 거부하고 그 이유를 알려 줍니다. ```console $ fastkit addroute users . @@ -151,7 +151,7 @@ Files to modify (2): ... ``` -`--dry-run` 없이 다시 실행하고 확인합니다. 새 리소스에는 `/api/v1/users` 아래에 페이지네이션이 적용된 목록 조회, 생성(201), 단건 조회, 교체(PUT), 수정(PATCH), 삭제(204) 엔드포인트가 있으며, 각 엔드포인트의 테스트도 함께 생성됩니다. 스키마에는 처음에 `name`과 `description` 필드만 있으므로, 원하는 필드를 넣으려면 `src/schemas/users.py`를 수정하세요. `src/api/api.py`에는 두 표시 주석 아래에 라우터의 import 문과 `include_router` 줄이 추가되고, `src/api/deps.py`에는 새 의존성 별칭이 추가됩니다. 이 별칭은 `src/api/routes/users.py`가 import해서 사용합니다. +`--dry-run` 없이 다시 실행하고 확인합니다. 새 리소스에는 `/api/v1/users` 아래에 페이지네이션이 적용된 목록 조회, 생성(201), 단건 조회, 교체(PUT), 수정(PATCH), 삭제(204) 엔드포인트가 있으며, 각 엔드포인트의 테스트도 함께 생성됩니다. 스키마에는 처음부터 `name`과 `description` 필드가 들어 있습니다. 원하는 필드를 넣으려면 `src/schemas/users.py`를 수정하세요. `src/api/api.py`에는 두 표시 주석 아래에 라우터의 import 문과 `include_router` 줄이 추가되고, `src/api/deps.py`에는 새 의존성 별칭이 추가됩니다. 이 별칭은 `src/api/routes/users.py`가 import해서 사용합니다. ```python title="src/api/deps.py" from src.crud.users import UserRepository, get_user_repository diff --git a/docs/ko/learn/generate.md b/docs/ko/learn/generate.md index c9c0c2a1..ac17d4f2 100644 --- a/docs/ko/learn/generate.md +++ b/docs/ko/learn/generate.md @@ -56,7 +56,7 @@ Create the project? [Y/n]: ╰──────────────────────────────────────────────────────────────────────────────╯ ``` -Author 행의 값은 `git config`에서 가져옵니다(이 예시에서는 git에 이름이 설정되어 있지 않았습니다). fastkit은 `shop/.venv`에 가상 환경을 만들고 그 안에 패키지를 설치했습니다. Next steps 패널은 앞으로 할 일을 정리한 목록이며, 프로젝트의 `README.md`에도 같은 내용이 들어 있습니다. `fastkit init --no-venv`로 실행하면 fastkit은 파일만 만듭니다. 이 경우에는 git에서 프로젝트를 클론했을 때와 마찬가지로 프로젝트 폴더에서 `uv sync`를 실행해 `.venv`를 나중에 만듭니다. +Author 행의 값은 `git config`에서 가져옵니다(이 예시에서는 git에 작성자 이름이 설정되어 있지 않았습니다). fastkit은 `shop/.venv`에 가상 환경을 만들고 그 안에 패키지를 설치했습니다. Next steps 패널은 앞으로 할 일을 정리한 목록이며, 프로젝트의 `README.md`에도 같은 내용이 들어 있습니다. `fastkit init --no-venv`로 실행하면 fastkit은 파일만 만듭니다. 이 경우에는 git에서 프로젝트를 클론했을 때와 마찬가지로 프로젝트 폴더에서 `uv sync`를 실행해 `.venv`를 나중에 만듭니다. ## fastkit이 만든 파일 diff --git a/docs/ko/learn/understand.md b/docs/ko/learn/understand.md index 9be6032f..1e992331 100644 --- a/docs/ko/learn/understand.md +++ b/docs/ko/learn/understand.md @@ -6,7 +6,7 @@ `main.py`는 위에서 아래로 읽습니다. 파일에서 FastAPI의 개념이 처음 사용되는 곳에는 그 개념을 설명하는 한두 줄짜리 주석이 있고, 주석의 마지막 줄에는 해당 개념을 다루는 FastAPI 튜토리얼 페이지의 링크가 있습니다. 각 개념에는 주석을 한 번만 달기 때문에, 뒤에 나오는 엔드포인트가 같은 일을 하더라도 그곳에는 주석이 없습니다. -직접 따라 해 보려면 프로젝트 폴더에서 `fastkit runserver`로 서버를 실행하고, 두 번째 터미널에서 아래 요청을 보냅니다. 아이템은 메모리에만 저장되므로, `/docs`에서 이미 아이템을 만들었다면 먼저 서버를 다시 시작하세요. 그렇지 않으면 ID가 아래 예시와 달라지므로, POST 요청이 반환한 ID를 대신 사용해야 합니다. 같은 요청을 에서 "Try it out"으로 보낼 수도 있습니다. +직접 따라 해 보려면 프로젝트 폴더에서 `fastkit runserver`로 서버를 실행하고, 두 번째 터미널에서 아래 요청을 보냅니다. 아이템은 메모리에만 저장되므로, `/docs`에서 이미 아이템을 만들었다면 먼저 서버를 다시 시작하세요. 서버를 다시 시작하지 않으면 ID가 아래 예시와 달라지므로, POST 요청이 반환한 ID를 대신 사용해야 합니다. 같은 요청을 에서 "Try it out"으로 보낼 수도 있습니다. ## 앱과 모델 diff --git a/docs/ko/reference/cli.md b/docs/ko/reference/cli.md index d49feb0a..db8e39dd 100644 --- a/docs/ko/reference/cli.md +++ b/docs/ko/reference/cli.md @@ -46,7 +46,7 @@ Commands: ## fastkit init -레벨이나 번들 템플릿(`--template`), 저장해 둔 구성(`--config`)으로 프로젝트를 만듭니다. 프로젝트 이름이 그 프로젝트가 사용하는 의존성의 이름과 같으면 생성을 거부합니다. 예를 들어 `--template fastapi-sqlmodel`로 만드는 프로젝트의 이름을 `sqlmodel`로 지으면, 패키지 관리자가 그 패키지를 설치하지 않기 때문입니다. 옵션을 실제로 사용하는 방법은 [레벨 고르기](../how-to/choose-a-level.md)와 [기능 커스터마이즈하기](../how-to/customise-features.md)에서 설명합니다. +레벨이나 번들 템플릿(`--template`), 저장해 둔 설정 파일(`--config`)로 프로젝트를 만듭니다. `--template fastapi-sqlmodel`로 만드는 프로젝트의 이름이 `sqlmodel`인 경우처럼, 프로젝트 이름이 그 프로젝트가 사용하는 의존성의 이름과 같으면 생성을 거부합니다. 이름이 같으면 패키지 관리자가 그 패키지를 설치하지 않기 때문입니다. 옵션을 실제로 사용하는 방법은 [레벨 고르기](../how-to/choose-a-level.md)와 [기능 커스터마이즈하기](../how-to/customise-features.md)에서 설명합니다. @@ -177,7 +177,7 @@ Packages ## fastkit addroute -프로젝트에 리소스(라우트, 스키마, 데이터 계층, 테스트)를 추가하고 그 라우터를 등록합니다. `single-file` 프로젝트에서는 라우트에 필요한 `src/api`, `src/crud`, `src/schemas`, `src/core` 패키지도 함께 만듭니다. `hello` 프로젝트에는 라우트를 추가하지 않으며, 대신 `main.py`에 엔드포인트를 직접 추가하라고 안내합니다. 자세한 과정은 [앱 확장하기](../learn/extend.md)에서 단계별로 설명합니다. +프로젝트에 리소스(라우트, 스키마, 데이터 계층, 테스트)를 추가하고 그 라우터를 등록합니다. `single-file` 프로젝트에서는 라우트에 필요한 `src/api`, `src/crud`, `src/schemas`, `src/core` 패키지도 함께 만듭니다. `hello` 프로젝트에는 리소스를 추가하지 않으며, 대신 `main.py`에 엔드포인트를 직접 추가하라고 안내합니다. 자세한 과정은 [앱 확장하기](../learn/extend.md)에서 단계별로 설명합니다. diff --git a/docs/ko/reference/levels-and-features.md b/docs/ko/reference/levels-and-features.md index 35f280d3..4dd2929a 100644 --- a/docs/ko/reference/levels-and-features.md +++ b/docs/ko/reference/levels-and-features.md @@ -16,7 +16,7 @@ -`hello`는 `fastapi-hello`를 그대로 복사하며 기능 옵션을 받지 않습니다. 나머지 레벨은 각각 프리셋 하나를 지정하고, 그 프리셋이 프로젝트의 출발점이 되는 템플릿을 지정합니다. `production`은 `domain-starter` 프리셋 위에 PostgreSQL, Alembic, JWT, Coverage, 구조화된 로깅, ruff, GitHub Actions, Docker, docker-compose를 고정으로 선택한 구성입니다. 이 선택은 기능 커스터마이즈 단계에서 바꾸거나 `--feature`로 바꿀 수 있습니다. fastkit 1.x에서 저장한 구성 파일에 `minimal` 프리셋이 지정되어 있어도 그대로 불러올 수 있습니다. 이제 `minimal`은 `single-module`을 뜻합니다. +`hello`는 `fastapi-hello`를 그대로 복사하며 기능 옵션을 받지 않습니다. 나머지 레벨은 각각 프리셋 하나를 지정하고, 그 프리셋이 프로젝트의 출발점이 되는 템플릿을 지정합니다. `production`은 `domain-starter` 프리셋에 PostgreSQL, Alembic, JWT, Coverage, 구조화된 로깅, ruff, GitHub Actions, Docker, docker-compose를 미리 선택해 둔 구성입니다. 이 선택은 기능 커스터마이즈 단계에서 바꾸거나 `--feature`로 바꿀 수 있습니다. fastkit 1.x에서 저장한 설정 파일에 `minimal` 프리셋이 지정되어 있어도 그대로 불러올 수 있습니다. 이제 `minimal`은 `single-module`을 뜻합니다. ## 생성된 파일이 놓이는 위치 @@ -30,7 +30,7 @@ | 준비 상태 프로브(데이터베이스나 Redis 캐시를 사용할 때) | `src/features/readiness.py` | `src/features/readiness.py` | `src/app/features/readiness.py` | | 페이지네이션 | 기능을 선택한 경우 `src/core/pagination.py` | `src/core/pagination.py` | `src/app/core/pagination.py` | -생성된 모듈은 설정 모듈에서 구성을 읽고, 설정 모듈은 `.env`를 불러옵니다. `layered`, `domain`, `production` 레벨에서 PostgreSQL, MySQL, SQLite 중 하나를 선택하면 예제 `/items` API가 아이템을 그 데이터베이스에 저장합니다. MongoDB나 Redis를 선택하면 예제 API는 자체 저장소를 계속 사용하며, fastkit은 이 사실을 안내 메시지와 `README.md`에 적어 둡니다. +생성된 모듈은 설정 모듈에서 설정값을 읽고, 설정 모듈은 `.env`를 불러옵니다. `layered`, `domain`, `production` 레벨에서 PostgreSQL, MySQL, SQLite 중 하나를 선택하면 예제 `/items` API가 아이템을 그 데이터베이스에 저장합니다. MongoDB나 Redis를 선택하면 예제 API는 자체 저장소를 계속 사용하며, fastkit은 이 사실을 안내 메시지와 `README.md`에 적어 둡니다. ## 테스트 도구와 린트 도구 diff --git a/docs/zh/contributing/template-creation-guide.md b/docs/zh/contributing/template-creation-guide.md index a760a527..23099f03 100644 --- a/docs/zh/contributing/template-creation-guide.md +++ b/docs/zh/contributing/template-creation-guide.md @@ -6,7 +6,7 @@ 每个模板都是 `src/fastapi_fastkit/fastapi_project_template/` 下的一个文件夹,以模板 id 命名(`fastapi-`,例如 `fastapi-auth-jwt`)。同一目录下的 `modules/` 不是模板:其中存放的是 `fastkit addroute` 写入的文件。 -fastkit 复制模板时,以 `-tpl` 结尾的文件会去掉这个后缀:`src/main.py-tpl` 变成 `src/main.py`,`.env.example-tpl` 变成 `.env.example`。每个 Python 文件都必须以 `.py-tpl` 结尾;只要有一个普通的 `.py` 文件,检查就会失败。生成项目时,会替换复制后文件中的四个占位符:``、``、`` 和 ``。 +fastkit 复制模板时,以 `-tpl` 结尾的文件会去掉这个后缀:`src/main.py-tpl` 变成 `src/main.py`,`.env.example-tpl` 变成 `.env.example`。每个 Python 文件都必须以 `.py-tpl` 结尾;只要有一个不带 `-tpl` 后缀的 `.py` 文件,检查就会失败。生成项目时,会替换复制后文件中的四个占位符:``、``、`` 和 ``。 一个模板至少需要: @@ -103,7 +103,7 @@ app = FastAPI( ``` - 第一行是一句话,并且不提及 fastkit;第二行只有 URL,并且必须是 catalog 中某个 `[[concepts]]` 条目的 URL。两行都不超过 88 列。 -- 一个模板中每个概念最多链接一次。`level` 模板中注释的 id 必须与它在 catalog 中的 `concepts` 列表完全一致;`example` 模板中的注释必须包含在它的列表中。 +- 一个模板中每个概念最多链接一次。`level` 模板中注释的 id 必须与它在 catalog 中的 `concepts` 列表完全一致;`example` 模板中注释的 id 必须包含在它的列表中。 - 该注释块紧贴在代码上方:不能放在 import 块内部,也不能放在装饰器和它所装饰的函数之间。 - `modules/` 下的文件不带概念注释。 diff --git a/docs/zh/how-to/example-projects.md b/docs/zh/how-to/example-projects.md index 30e1f5a7..ea07d068 100644 --- a/docs/zh/how-to/example-projects.md +++ b/docs/zh/how-to/example-projects.md @@ -146,7 +146,7 @@ $ curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8000/mcp 401 ``` -准备工作:在你接入自己的用户存储(`src/auth/users.py` 中的 `get_users_db()`)之前,用户存储是空的。在本地试验时,可以在 `.env` 中设置 `ENABLE_DEMO_USERS=true`,启用三个密码公开的演示账号(在 `development` 以外的环境中会被拒绝)。MCP 端点接受用户的 JWT,或者你在 `.env` 中设置为 `MCP_API_KEY` 的密钥;README 中的“MCP Authentication”一节演示了这两种方式。 +准备工作:在你接入自己的用户存储(`src/auth/users.py` 中的 `get_users_db()`)之前,用户存储是空的。在本地试验时,可以在 `.env` 中设置 `ENABLE_DEMO_USERS=true`,启用三个密码公开的演示账号(在 `development` 以外的环境中会拒绝启用演示账号)。MCP 端点接受用户的 JWT,或者你在 `.env` 中设置为 `MCP_API_KEY` 的密钥;README 中的“MCP Authentication”一节演示了这两种方式。 diff --git a/docs/zh/learn/extend.md b/docs/zh/learn/extend.md index 119a1658..30c7cbf9 100644 --- a/docs/zh/learn/extend.md +++ b/docs/zh/learn/extend.md @@ -59,7 +59,7 @@ $ uv run pytest -q ## 一个文件不够用的时候 -`fastkit addroute` 可以替你添加资源,但它需要有包来存放新的模块。在 `hello` 项目中,它会拒绝执行并说明原因: +`fastkit addroute` 可以替你添加资源,但它需要有包来存放新的模块。在 `hello` 项目中,它会拒绝添加资源并说明原因: ```console $ fastkit addroute users . diff --git a/docs/zh/learn/generate.md b/docs/zh/learn/generate.md index faea06e2..d24efacf 100644 --- a/docs/zh/learn/generate.md +++ b/docs/zh/learn/generate.md @@ -117,7 +117,7 @@ async def read_root( FastAPI 本身并不监听请求。负责这件事的服务器是 uvicorn:它接受 HTTP 连接,并通过 ASGI 把每个请求交给 `app`。ASGI 是 Python Web 服务器与应用之间的标准接口。`fastkit runserver` 会以 `main:app` 启动 uvicorn,意思是“`main.py` 中的 `app` 对象”。 -FastAPI 会根据路径、类型提示和返回类型,为你的 API 编写一份 OpenAPI 描述。它是位于 `/openapi.json` 的 JSON 文档,列出每个端点及其参数和响应。`/docs` 和 `/redoc` 两个页面就是根据这份文档生成的。它们展示的是 FastAPI 能从代码中读到的内容,也就是你声明的路径、参数、模型和状态码。如果某个响应只是在函数内部抛出,例如 `read_item` 的 404,那么除非你声明它,否则它不会出现在文档中。 +FastAPI 会根据路径、类型提示和返回类型,为你的 API 编写一份 OpenAPI 描述。它是位于 `/openapi.json` 的 JSON 文档,列出每个端点及其参数和响应。`/docs` 和 `/redoc` 两个页面就是根据这份文档生成的。它们展示的是 FastAPI 能从代码中读到的内容,也就是你声明的路径、参数、模型和状态码。如果某个响应只来自函数内部抛出的异常,例如 `read_item` 的 404,那么除非你声明它,否则它不会出现在文档中。 ## FastAPI 文档 diff --git a/docs/zh/learn/test.md b/docs/zh/learn/test.md index 61e7a78b..d301235f 100644 --- a/docs/zh/learn/test.md +++ b/docs/zh/learn/test.md @@ -1,6 +1,6 @@ # 测试应用 -在本页中,你将运行[扩展应用](extend.md)中 `layered` 级别 `shop` 项目的测试,阅读这些测试的构建方式,并编写一个自己的测试。你将了解 FastAPI 的 `TestClient` 如何在不启动服务器的情况下调用应用,pytest fixture 如何为每个测试做准备,`app.dependency_overrides` 如何把依赖项替换成测试用的版本,以及如何检查校验和错误响应。你还会看到 fastkit 自带哪些测试,以及 Coverage 测试选项如何衡量它们。 +在本页中,你将运行[扩展应用](extend.md)中 `layered` 级别 `shop` 项目的测试,阅读这些测试的构建方式,并编写一个自己的测试。你将了解 FastAPI 的 `TestClient` 如何在不启动服务器的情况下调用应用,pytest fixture 如何为每个测试做准备,`app.dependency_overrides` 如何把依赖项替换成测试用的版本,以及如何检查校验和错误响应。你还会看到 fastkit 自带哪些测试,以及 Coverage 测试选项如何衡量这些测试覆盖了多少代码。 ## 运行测试 diff --git a/docs/zh/learn/understand.md b/docs/zh/learn/understand.md index bd823385..92a07da3 100644 --- a/docs/zh/learn/understand.md +++ b/docs/zh/learn/understand.md @@ -6,7 +6,7 @@ 请从上到下阅读 `main.py`。文件第一次用到某个 FastAPI 概念时,会有一到两行注释解释它,注释末尾附有讲解该概念的 FastAPI 教程页面链接。每个概念只注释一次,所以后面做同样事情的端点就不再带注释。 -如果想边读边动手,请在项目文件夹中用 `fastkit runserver` 启动服务器,然后在第二个终端中发送下面的请求。条目保存在内存中,所以如果你已经在 `/docs` 中创建过条目,请先重启服务器;否则你得到的 id 会与下面的不同,这时请使用你的 POST 请求返回的 id。你也可以在 中通过“Try it out”发送同样的请求。 +如果想边读边动手,请在项目文件夹中用 `fastkit runserver` 启动服务器,然后在第二个终端中发送下面的请求。条目保存在内存中,所以如果你已经在 `/docs` 中创建过条目,请先重启服务器;如果不重启,你得到的 id 会与下面的不同,这时请使用你的 POST 请求返回的 id。你也可以在 中通过“Try it out”发送同样的请求。 ## 应用和模型 diff --git a/mkdocs.yml b/mkdocs.yml index 9b75e232..64d9b4e2 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -292,19 +292,14 @@ markdown_extensions: - admonition - pymdownx.details # PyMdown Extensions - - pymdownx.highlight: # necessary for code blocks & termynal + - pymdownx.highlight: # necessary for code blocks anchor_linenums: true line_spans: __span pygments_lang_class: true - - pymdownx.inlinehilite # necessary for code blocks & termynal - - pymdownx.snippets # necessary for code blocks & termynal - - pymdownx.superfences # necessary for code blocks & termynal + - pymdownx.inlinehilite # necessary for code blocks + - pymdownx.snippets + - pymdownx.superfences # necessary for code blocks extra_css: - - css/termynal.css - css/custom.css - css/web-generator.css - -extra_javascript: - - js/termynal.js - - js/custom.js diff --git a/scripts/setup-i18n-structure.sh b/scripts/setup-i18n-structure.sh deleted file mode 100755 index c91742d0..00000000 --- a/scripts/setup-i18n-structure.sh +++ /dev/null @@ -1,135 +0,0 @@ -#!/bin/bash - -# Setup i18n directory structure for FastAPI-fastkit documentation (created for legacy development environment users) -# This script moves existing English documentation to the en/ directory -# and sets up the structure for multi-language support - -set -e - -# Colors for output -RED='\033[0;31m' -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -NC='\033[0m' # No Color - -# Get script directory and project root -SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -PROJECT_ROOT="$(dirname "$SCRIPT_DIR")" -DOCS_DIR="$PROJECT_ROOT/docs" - -echo -e "${GREEN}FastAPI-fastkit i18n Structure Setup${NC}" -echo "================================================" -echo "" - -# Check if docs directory exists -if [ ! -d "$DOCS_DIR" ]; then - echo -e "${RED}Error: docs directory not found at $DOCS_DIR${NC}" - exit 1 -fi - -# Create en directory if it doesn't exist -echo -e "${YELLOW}Creating en/ directory...${NC}" -mkdir -p "$DOCS_DIR/en" - -# Function to move files/directories -move_to_en() { - local item="$1" - local item_name=$(basename "$item") - - # Skip if already in en/ or if it's a special directory - if [[ "$item" == *"/en/"* ]] || [[ "$item_name" == "en" ]] || \ - [[ "$item_name" == "ko" ]] || [[ "$item_name" == "ja" ]] || \ - [[ "$item_name" == "zh" ]] || [[ "$item_name" == "es" ]] || \ - [[ "$item_name" == "fr" ]] || [[ "$item_name" == "de" ]] || \ - [[ "$item_name" == "css" ]] || [[ "$item_name" == "js" ]] || \ - [[ "$item_name" == "img" ]]; then - return - fi - - # Move markdown files and directories - if [[ -f "$item" && "$item" == *.md ]] || [[ -d "$item" ]]; then - local target="$DOCS_DIR/en/$item_name" - - if [ ! -e "$target" ]; then - echo " Moving: $item_name" - mv "$item" "$target" - else - echo " Skipping (already exists): $item_name" - fi - fi -} - -# Move markdown files from docs root -echo "" -echo -e "${YELLOW}Moving English documentation to en/...${NC}" - -for item in "$DOCS_DIR"/*; do - move_to_en "$item" -done - -# Create symbolic links for shared assets in en/ directory -echo "" -echo -e "${YELLOW}Creating symbolic links for shared assets...${NC}" - -if [ -d "$DOCS_DIR/css" ]; then - ln -sf ../css "$DOCS_DIR/en/css" - echo " Created: en/css -> ../css" -fi - -if [ -d "$DOCS_DIR/js" ]; then - ln -sf ../js "$DOCS_DIR/en/js" - echo " Created: en/js -> ../js" -fi - -if [ -d "$DOCS_DIR/img" ]; then - ln -sf ../img "$DOCS_DIR/en/img" - echo " Created: en/img -> ../img" -fi - -# Create placeholder directories for other languages -echo "" -echo -e "${YELLOW}Creating placeholder directories for other languages...${NC}" - -languages=("ko" "ja" "zh" "es" "fr" "de") - -for lang in "${languages[@]}"; do - mkdir -p "$DOCS_DIR/$lang" - echo " Created: $lang/" - - # Create symbolic links for assets - if [ -d "$DOCS_DIR/css" ]; then - ln -sf ../css "$DOCS_DIR/$lang/css" - fi - if [ -d "$DOCS_DIR/js" ]; then - ln -sf ../js "$DOCS_DIR/$lang/js" - fi - if [ -d "$DOCS_DIR/img" ]; then - ln -sf ../img "$DOCS_DIR/$lang/img" - fi -done - -# Create a .gitkeep file in each language directory -echo "" -echo -e "${YELLOW}Creating .gitkeep files...${NC}" - -for lang in en "${languages[@]}"; do - touch "$DOCS_DIR/$lang/.gitkeep" - echo " Created: $lang/.gitkeep" -done - -# Print final structure -echo "" -echo -e "${GREEN}Setup Complete!${NC}" -echo "" -echo "Current documentation structure:" -tree -L 2 -d "$DOCS_DIR" 2>/dev/null || ls -la "$DOCS_DIR" - -echo "" -echo -e "${GREEN}Next steps:${NC}" -echo "1. Review the new structure in docs/" -echo "2. Update any internal links if necessary" -echo "3. Run 'mkdocs build' to test the site" -echo "4. Run 'python scripts/translate.py --target-lang ko' to create translations" -echo "" -echo -e "${YELLOW}Note: The English documentation is now in docs/en/${NC}" -echo -e "${YELLOW} All language directories share the same css/, js/, and img/ directories${NC}" diff --git a/scripts/translate.py b/scripts/translate.py index ce67d8de..ebe96bb8 100755 --- a/scripts/translate.py +++ b/scripts/translate.py @@ -216,13 +216,14 @@ def get_translation_prompt( class OpenAITranslator(TranslationAPI): """OpenAI API translator (any OpenAI-compatible endpoint via base_url).""" - # Approximate token limits for different models (conservative estimates) + # Tokens of source text sent per request, which sets the chunk size. These + # are this script's own conservative choices, not the models' limits. A + # model not listed uses the default; max_chunk_chars overrides both. MODEL_TOKEN_LIMITS = { - "gpt-5": 3000, "gpt-4o": 12000, "gpt-4o-mini": 12000, } - DEFAULT_TOKEN_LIMIT = 3000 # Conservative default + DEFAULT_TOKEN_LIMIT = 3000 def __init__( self, @@ -241,7 +242,7 @@ def __init__( self.retry_delay = retry_delay self.request_delay = request_delay self._client = None - # Estimate max chars based on token limit (roughly 4 chars per token for English) + # English averages about 4 characters per token; count 3 to stay below. token_limit = self.MODEL_TOKEN_LIMITS.get(model_name, self.DEFAULT_TOKEN_LIMIT) self.max_chunk_chars = max_chunk_chars or ( token_limit * 3 diff --git a/scripts/update_nav_translations.py b/scripts/update_nav_translations.py deleted file mode 100755 index ed3184bc..00000000 --- a/scripts/update_nav_translations.py +++ /dev/null @@ -1,360 +0,0 @@ -#!/usr/bin/env python3 -# -------------------------------------------------------------------------- -# Update navigation translations in mkdocs.yml automatically. -# -# This script reads navigation items from mkdocs.yml and generates translations -# for all configured languages using AI translation APIs. -# -# @author bnbong bbbong9@gmail.com -# -------------------------------------------------------------------------- -import argparse -import logging -import os -import sys -from pathlib import Path -from typing import Any, List - -import yaml - -sys.path.insert(0, str(Path(__file__).parent.parent / "src")) - -logging.basicConfig( - level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" -) -logger = logging.getLogger(__name__) - - -def extract_nav_items(nav_config: List[Any]) -> List[str]: - """Extract all navigation item titles from nav configuration.""" - items = [] - - def extract_recursive(nav_item: Any) -> None: - if isinstance(nav_item, dict): - for key, value in nav_item.items(): - items.append(key) - if isinstance(value, list): - for sub_item in value: - extract_recursive(sub_item) - elif isinstance(nav_item, str): - items.append(nav_item) - - for item in nav_config: - extract_recursive(item) - - return items - - -def translate_nav_item( - text: str, target_lang: str, api_key: str = "", provider: str = "openai" -) -> str: - """Translate a navigation item to target language.""" - # The labels mkdocs.yml already translates (the same words as its - # nav_translations). A translated language lists every section and page - # label of the nav; a label missing from both falls back to the API, or - # to the English text without an API key. - translations = { - "ko": { - "Home": "홈", - "Start": "시작하기", - "Web Generator": "웹 생성기", - "Learn": "배우기", - "How-to": "실전 가이드", - "Reference": "레퍼런스", - "Contributing": "기여하기", - "Changelog": "변경 로그", - "Installation": "설치", - "Generate": "생성하기", - "Understand": "이해하기", - "Extend": "확장하기", - "Test": "테스트하기", - "Migrate": "도메인 구조로 옮기기", - "Deploy": "배포하기", - "Choose a Level": "레벨 고르기", - "Customise Features": "기능 커스터마이즈하기", - "Scripts and Config Files": "스크립트와 설정 파일", - "Example Projects": "예제 프로젝트", - "Check a Project": "프로젝트 검사하기", - "Upgrade from 1.x": "1.x에서 업그레이드하기", - "Troubleshooting": "문제 해결", - "CLI": "CLI", - "Levels and Features": "레벨과 기능", - "Generated Projects": "생성된 프로젝트", - "Development Setup": "개발 환경 설정", - "Template Guide": "템플릿 가이드", - "Translation Guide": "번역 가이드", - }, - "ja": { - "Home": "ホーム", - "Start": "はじめに", - "Web Generator": "Web ジェネレーター", - "Learn": "学ぶ", - "How-to": "ハウツーガイド", - "Reference": "リファレンス", - "Contributing": "コントリビューション", - "Changelog": "変更履歴", - "Installation": "インストール", - "Generate": "アプリを生成する", - "Understand": "コードを理解する", - "Extend": "アプリを拡張する", - "Test": "アプリをテストする", - "Migrate": "ドメイン構成へ移行する", - "Deploy": "本番環境にデプロイする", - "Choose a Level": "レベルを選ぶ", - "Customise Features": "機能をカスタマイズする", - "Scripts and Config Files": "スクリプトと設定ファイル", - "Example Projects": "サンプルプロジェクト", - "Check a Project": "プロジェクトを検査する", - "Upgrade from 1.x": "1.x からアップグレードする", - "Troubleshooting": "トラブルシューティング", - "CLI": "CLI", - "Levels and Features": "レベルと機能", - "Generated Projects": "生成されるプロジェクト", - "Development Setup": "開発環境のセットアップ", - "Template Guide": "テンプレートガイド", - "Translation Guide": "翻訳ガイド", - }, - "zh": { - "Home": "首页", - "Start": "开始使用", - "Web Generator": "网页生成器", - "Learn": "学习", - "How-to": "操作指南", - "Reference": "参考", - "Contributing": "参与贡献", - "Changelog": "更新日志", - "Installation": "安装", - "Generate": "生成应用", - "Understand": "理解代码", - "Extend": "扩展应用", - "Test": "测试应用", - "Migrate": "迁移到领域结构", - "Deploy": "部署到生产环境", - "Choose a Level": "选择级别", - "Customise Features": "自定义功能", - "Scripts and Config Files": "脚本和配置文件", - "Example Projects": "示例项目", - "Check a Project": "检查项目", - "Upgrade from 1.x": "从 1.x 升级", - "Troubleshooting": "故障排除", - "CLI": "CLI", - "Levels and Features": "级别和功能", - "Generated Projects": "生成的项目", - "Development Setup": "开发环境搭建", - "Template Guide": "模板指南", - "Translation Guide": "翻译指南", - }, - "es": { - "Home": "Inicio", - "Start": "Empezar", - "Web Generator": "Generador web", - "Learn": "Aprender", - "How-to": "Guías prácticas", - "Reference": "Referencia", - "Contributing": "Contribuir", - "Changelog": "Registro de cambios", - "Installation": "Instalación", - "Generate": "Genera la aplicación", - "Understand": "Entiende el código", - "Extend": "Amplía la aplicación", - "Test": "Prueba la aplicación", - "Migrate": "Pasa a una estructura por dominios", - "Deploy": "Despliega en producción", - "Choose a Level": "Elige un nivel", - "Customise Features": "Personaliza las funcionalidades", - "Scripts and Config Files": "Scripts y archivos de configuración", - "Example Projects": "Proyectos de ejemplo", - "Check a Project": "Revisa un proyecto", - "Upgrade from 1.x": "Actualiza desde 1.x", - "Troubleshooting": "Solución de problemas", - "CLI": "CLI", - "Levels and Features": "Niveles y funcionalidades", - "Generated Projects": "Proyectos generados", - "Development Setup": "Entorno de desarrollo", - "Template Guide": "Guía de plantillas", - "Translation Guide": "Guía de traducción", - }, - "fr": { - "Home": "Accueil", - "Start": "Démarrer", - "Web Generator": "Générateur web", - "Learn": "Apprendre", - "How-to": "Guides pratiques", - "Reference": "Référence", - "Contributing": "Contribuer", - "Changelog": "Journal des modifications", - "Installation": "Installation", - "Generate": "Générer l'application", - "Understand": "Comprendre le code", - "Extend": "Étendre l'application", - "Test": "Tester l'application", - "Migrate": "Passer à une structure par domaines", - "Deploy": "Déployer en production", - "Choose a Level": "Choisir un niveau", - "Customise Features": "Personnaliser les fonctionnalités", - "Scripts and Config Files": "Scripts et fichiers de configuration", - "Example Projects": "Projets d'exemple", - "Check a Project": "Vérifier un projet", - "Upgrade from 1.x": "Mettre à niveau depuis 1.x", - "Troubleshooting": "Dépannage", - "CLI": "CLI", - "Levels and Features": "Niveaux et fonctionnalités", - "Generated Projects": "Projets générés", - "Development Setup": "Environnement de développement", - "Template Guide": "Guide des templates", - "Translation Guide": "Guide de traduction", - }, - "de": { - "Home": "Startseite", - "Start": "Start", - "Web Generator": "Web-Generator", - "Learn": "Lernen", - "How-to": "Anleitungen", - "Reference": "Referenz", - "Contributing": "Mitwirken", - "Changelog": "Änderungsprotokoll", - "Installation": "Installation", - "Generate": "Anwendung erzeugen", - "Understand": "Code verstehen", - "Extend": "Anwendung erweitern", - "Test": "Anwendung testen", - "Migrate": "Zur Domänenstruktur wechseln", - "Deploy": "In Produktion deployen", - "Choose a Level": "Stufe wählen", - "Customise Features": "Features anpassen", - "Scripts and Config Files": "Skripte und Konfigurationsdateien", - "Example Projects": "Beispielprojekte", - "Check a Project": "Projekt prüfen", - "Upgrade from 1.x": "Von 1.x aktualisieren", - "Troubleshooting": "Fehlerbehebung", - "CLI": "CLI", - "Levels and Features": "Stufen und Features", - "Generated Projects": "Erzeugte Projekte", - "Development Setup": "Entwicklungsumgebung", - "Template Guide": "Template-Leitfaden", - "Translation Guide": "Übersetzungsleitfaden", - }, - } - - # Return pre-defined translation if available - if target_lang in translations and text in translations[target_lang]: - return translations[target_lang][text] - - # If API key is provided, use AI translation - if api_key: - # TODO: add another AI provider - try: - if provider == "openai": - import openai - - client_openai = openai.OpenAI(api_key=api_key) - response = client_openai.chat.completions.create( - model="gpt-5.6-sol", - messages=[ - { - "role": "system", - "content": "You are a translator. Translate only the text, no explanations.", - }, - { - "role": "user", - "content": f"Translate '{text}' to {target_lang}", - }, - ], - max_completion_tokens=1000, - ) - response_content = response.choices[0].message.content - if response_content is None: - return text - return response_content.strip() - except Exception as e: - logger.warning(f"AI translation failed for '{text}': {e}") - - # Return original text if no translation available - return text - - -def update_mkdocs_nav_translations( - mkdocs_path: Path, api_key: str = "", provider: str = "openai" -) -> None: - """Update nav_translations in mkdocs.yml file.""" - logger.info(f"Reading {mkdocs_path}") - - with open(mkdocs_path, "r", encoding="utf-8") as f: - config = yaml.safe_load(f) - - # Extract navigation items - nav_items = extract_nav_items(config.get("nav", [])) - logger.info(f"Found {len(nav_items)} navigation items") - - # Get languages from i18n plugin config - i18n_config = None - for plugin in config.get("plugins", []): - if isinstance(plugin, dict) and "i18n" in plugin: - i18n_config = plugin["i18n"] - break - - if not i18n_config: - logger.error("i18n plugin not found in mkdocs.yml") - return - - # Update translations for each language - for lang_config in i18n_config["languages"]: - locale = lang_config.get("locale") - if locale == "en": - continue # Skip English - - logger.info(f"Updating translations for {locale}") - - if "nav_translations" not in lang_config: - lang_config["nav_translations"] = {} - - # Translate each nav item - for item in nav_items: - if item not in lang_config["nav_translations"]: - translated = translate_nav_item(item, locale, api_key, provider) - lang_config["nav_translations"][item] = translated - logger.info(f" {item} -> {translated}") - - # Write updated config - logger.info(f"Writing updated config to {mkdocs_path}") - with open(mkdocs_path, "w", encoding="utf-8") as f: - yaml.dump( - config, f, allow_unicode=True, default_flow_style=False, sort_keys=False - ) - - logger.info("Navigation translations updated successfully") - - -def main() -> None: - """Main entry point.""" - parser = argparse.ArgumentParser( - description="Update navigation translations in mkdocs.yml" - ) - parser.add_argument( - "--mkdocs-file", type=str, default="mkdocs.yml", help="Path to mkdocs.yml file" - ) - parser.add_argument( - "--api-key", type=str, help="API key for AI translation (optional)" - ) - parser.add_argument( - "--api-provider", - type=str, - choices=["openai", "anthropic"], - default="openai", - help="AI API provider", - ) - - args = parser.parse_args() - - mkdocs_path = Path(args.mkdocs_file) - if not mkdocs_path.exists(): - logger.error(f"File not found: {mkdocs_path}") - sys.exit(1) - - # Get API key from args or environment - api_key = args.api_key or os.getenv("TRANSLATION_API_KEY") - - update_mkdocs_nav_translations(mkdocs_path, api_key or "", args.api_provider) - - -if __name__ == "__main__": - main() diff --git a/tests/test_docs/test_site_structure.py b/tests/test_docs/test_site_structure.py index cd9c1596..b77b4782 100644 --- a/tests/test_docs/test_site_structure.py +++ b/tests/test_docs/test_site_structure.py @@ -1,7 +1,8 @@ # -------------------------------------------------------------------------- # Test cases for the structure of the English documentation: the nav and the # pages agree, the Learn pages link the FastAPI documentation through -# generated blocks, and pages hold no termy blocks or PR references. +# generated blocks, and pages hold no PR references. No page in any +# language uses termy blocks, whose assets were removed. # # @author bnbong bbbong9@gmail.com # -------------------------------------------------------------------------- @@ -11,10 +12,12 @@ import pytest from .docs_support import ( + DOCS, EN, ROOT, docs_blocks, english_pages, + locales, nav, nav_pages, read, @@ -113,10 +116,24 @@ def test_fastapi_links_come_from_the_catalog() -> None: def test_no_termy_blocks() -> None: - found = [page for page in english_pages() if 'class="termy"' in read(EN / page)] + # The terminal animation assets are gone, so a termy block in any + # language would render as a plain code block. + found = [ + f"{lang}/{page}" + for lang in ("en",) + locales() + for page in english_pages() + if (DOCS / lang / page).is_file() and "termy" in read(DOCS / lang / page) + ] assert not found, found +def test_no_terminal_animation_assets() -> None: + mkdocs = read(ROOT / "mkdocs.yml") + assert "termynal" not in mkdocs + for name in ("css/termynal.css", "js/termynal.js", "js/custom.js"): + assert not (DOCS / name).exists(), name + + def _pr_references(text: str) -> List[str]: links = [link for link in PULL_LINK.findall(text) if link not in ALLOWED_PULL_LINKS] return links + PR_NUMBER.findall(text) diff --git a/tests/test_docs/test_web_generator_page.py b/tests/test_docs/test_web_generator_page.py index d7eb68f2..18a68255 100644 --- a/tests/test_docs/test_web_generator_page.py +++ b/tests/test_docs/test_web_generator_page.py @@ -254,7 +254,9 @@ def test_stylesheet_is_in_extra_css_and_script_is_not_global() -> None: assert " - css/web-generator.css" in [ line.rstrip() for line in extra_css.splitlines() ] - extra_js = text.split("extra_javascript:", 1)[1] + extra_js = ( + text.split("extra_javascript:", 1)[1] if "extra_javascript:" in text else "" + ) assert "web-generator" not in extra_js