diff --git a/CHANGELOG.md b/CHANGELOG.md index b0504f97..27007391 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,9 +2,24 @@ ## v2.0.0 +### Highlights + +- **Web generator:** a page on the documentation site creates a project in your browser and downloads it as a zip with the same files as `fastkit init ... --no-venv`. It shows the matching command line and the next steps, works in all seven documentation languages, and uploads nothing you enter. +- **Levels and one `fastkit init`:** `init` is the single way to create a project. It asks for a name and a level, from a single `main.py` to a production layout: `hello`, `single-file`, `layered`, `domain` and `production` (PostgreSQL, Alembic, JWT, coverage, structured logging, ruff, GitHub Actions, Docker). `init --template ` copies a bundled template and replaces `startdemo`. +- **Features you can read:** each selected feature gets a section in the project's `README.md`, generated code explains a FastAPI concept at its first use with a link to the FastAPI documentation, and at the `layered` level and above with a SQL database the example `/items` API stores its items in that database. +- **Next steps:** after creating a project, fastkit prints the commands that apply to it (environment, `.env`, database, server, tests, `addroute`, the next level) and writes the steps for a fresh checkout into the project's `README.md`. +- **`fastkit doctor`** checks an existing project for problems that newer templates fixed; with `--fix` it applies the safe fixes after showing them. +- **Documentation** is rebuilt around a Learn track that follows one project from `hello` to `production`, and is available in English, Korean, Japanese, Chinese, Spanish, French and German. +- **New `fastapi-hello` template:** one `main.py` and its tests, for people who have never written a FastAPI app. + ### Breaking changes -Every template except `fastapi-hello`, the code `fastkit init` generates for its options, and `fastkit addroute` output now share one HTTP contract: +[Upgrade from fastkit 1.x](https://bnbong.github.io/FastAPI-fastkit/how-to/upgrade-from-1x/) explains what to change in commands, scripts and saved configurations. Projects generated with 1.x keep working. + +- **Commands:** `init` asks no stack question (`minimal` / `standard` / `full`); levels and features generate the code for what they add. Without a terminal `init` asks nothing and needs `--project-name` (or `--config`); answers piped to stdin are no longer read, and `--interactive` is accepted and has no effect. `startdemo` keeps working as an alias of `init --template` and prints a one-line note. +- **Removed templates:** instead of `fastapi-async-crud` and `fastapi-psql-orm` use `fastapi-sqlmodel` (async; SQLite, PostgreSQL or MySQL) or a level with `--database`; instead of `fastapi-dockerized` use `fastapi-default` or `--feature deployment=Docker`; instead of `fastapi-empty` use `--level single-file`. +- **Saved configurations** still load, but a `minimal` preset, or no preset, now creates a `single-file` project (`fastapi-single-module`). The CORS and Pagination options are no longer offered, because every project includes them, and `fastapi-pagination` is no longer installed. +- **One HTTP contract** for every template except `fastapi-hello`, the code `init` generates for its options and the routes `addroute` writes: | | v1.5.2 | v2.0.0 | |---|---|---| @@ -19,119 +34,74 @@ Every template except `fastapi-hello`, the code `fastkit init` generates for its | 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`. - -- **`fastkit init` is guided by default:** it asks for a project name and a level (`hello`, `single-file`, `layered`, `domain`, `production`), the database where the level has one, and whether to customise features. The stack question (`minimal` / `standard` / `full`) is gone; `--interactive` is accepted and has no effect, and `-y` uses the defaults without asking. -- **Without a terminal `init` asks nothing:** pass `--project-name` and options such as `--level`, `--database` and `--feature`, or `--config`. Answers piped to stdin are no longer read. -- **`fastkit init --template ` replaces `startdemo`**, which keeps working as an alias and prints a one-line note. -- **Removed templates:** `fastapi-async-crud`, `fastapi-dockerized`, `fastapi-psql-orm` and `fastapi-empty` are gone, together with the tutorials of the first three; use `fastapi-sqlmodel` (async; SQLite, PostgreSQL or MySQL) or `fastapi-default` for new projects, or `--level single-file` instead of `fastapi-empty`. Projects generated from them keep working, and `fastkit doctor` still recognises their example secrets. -- **`minimal` preset:** it now means `single-module`, so saved configs that name `minimal` or no preset create a `fastapi-single-module` project. -- **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:** `init` and `startdemo` exit with status 1 when they refuse to run or fail, including an in-place overwrite without a terminal or `--yes`; invalid options exit with status 2. `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:** CORS and Pagination are no longer offered, because every project includes them, and `fastapi-pagination` is no longer installed. Rate-Limiting and WebSocket remain; saved configs that list the removed ones still load. +- **Settings and secrets:** every project except `hello` reads its configuration from one settings module that loads `.env`, and outside `development` it refuses to start with a missing, example or shorter than 32-byte `SECRET_KEY` (in `development` an example key only warns). Every 401 carries `WWW-Authenticate`. +- **`fastapi-mcp`:** `API_V1_STR` is renamed `API_V1_PREFIX` and the OpenAPI schema moves to `/openapi.json`. `POST /api/v1/auth/login` is removed (use `POST /api/v1/auth/token`), `/auth/me` becomes `GET /api/v1/users/me`, `/auth/users` becomes `GET /api/v1/users` (superusers only), and `/mcp-routes/*` is replaced by `GET /api/v1/mcp-server`. Only the six item operations are MCP tools. Send the MCP key as `X-MCP-API-Key` (`Authorization: Bearer ` still works), so that `Authorization` can carry a user token. +- **`fastapi-auth-jwt`:** a rejected refresh token answers 400 `{"error": "invalid_grant"}` instead of 401, token responses add `expires_in`, and `GET /api/v1/users` returns the page envelope. +- **`fastapi-sqlmodel`:** `ItemPublic` is renamed `ItemRead`, and the schema is left to Alembic by default (`CREATE_TABLES_ON_STARTUP=false`): run `alembic upgrade head` before the first start. +- **`fastapi-llm-agent`:** the server generates conversation ids; send `conversation_id` only to continue a conversation, and an unknown id answers 404. +- **`fastapi-custom-response`:** errors, including validation errors and unhandled exceptions, use the response envelope, and 500 responses no longer contain exception text. +- **`init` options:** with Session-based or OAuth2 authentication `GET /auth/me` moves to `GET /api/v1/users/me` and logout answers 204; FastAPI-Users needs PostgreSQL, MySQL or SQLite; the WebSocket connection list moves from `/api/v1/ws/connections` to `/api/v1/connections` (`/ws` is unchanged). +- **Exit statuses:** `init` and `startdemo` exit with 1 when they refuse to run or fail (including an in-place overwrite without a terminal or `--yes`) and with 2 on invalid options. `addroute` exits with 1 on errors and refuses route names that are not lower-case ASCII. `deleteproject` exits with 1 when the project does not exist, is not a fastkit project or cannot be deleted. `runserver` in a project without `.venv` exits with 1 unless you choose to continue with the current Python. + +### Upgrade notes for existing projects + +Upgrading fastkit does not change an existing project. Run `fastkit doctor` in it to see what can be checked and fixed automatically, then: + +1. **Clients of a regenerated project:** apply the contract changes above (paths under `/api/v1`, `/health`, the list envelope, 204 on delete). +2. **Docker:** images built from the new Dockerfiles set `ENVIRONMENT=production` and do not contain `.env`; pass the settings at run time, including a `SECRET_KEY` of at least 32 bytes, as the comment at the end of the project's `Dockerfile` shows. For a project created from a level that is `docker run -p 8000:8000 --env-file .env -e ENVIRONMENT=production ` (the generated `.env` sets `ENVIRONMENT=development`); `fastapi-sqlmodel` and `fastapi-auth-jwt` pass `SECRET_KEY` with `-e` instead, because the `DATABASE_URL` in their `.env` would replace the image's SQLite path. +3. **`fastapi-auth-jwt` and `fastapi-sqlmodel` projects that adopt the new template code:** run `alembic upgrade head` for the new migration (timezone-aware timestamps). +4. **Projects from the removed templates** need no change and keep working with `addroute`, `doctor` and `runserver`; `doctor` still recognises their example secrets. To move to PostgreSQL or MySQL with `fastapi-sqlmodel`, set `DATABASE_URL` and install the matching driver extra. +5. **Scripts:** replace piped answers with options, e.g. `fastkit init --project-name api --level layered --database SQLite -y`, or with `--config`. To move from `startdemo`, use `fastkit init --template --project-name ` and pass `--author`, `--author-email` and `--description`, or let `git config` fill author and email. +6. **The old stacks:** the closest replacements are `--level single-file` for `minimal`, and a level with `--database` and `--feature migrations=Alembic` or `--feature async_tasks=Celery` for `standard` and `full`. +7. **`single-file` projects generated with features** now keep the template's `/health`, so its OpenAPI operation id is `health_health_get` instead of `health_check_health_get`; regenerate API clients that use operation ids. ### CLI -- New `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. -- New `init` options: `--level`, `--database`, `--feature AXIS=VALUE`, `--extra-package`, `--template`, `--in-place`, and `--name` for `--project-name`. `--database` matches its choices in any case. -- Author and email default to `git config user.name` / `user.email`, and the package manager to uv when it is installed, otherwise pip. An empty author is left out of `pyproject.toml` for every package manager (Poetry also leaves out an email without a name). -- `--save-config` works for every `init` run except `--dry-run` and records the level or template; `project_name` is the only required config key, a config can name a `level` or a `template`, and `--project-name`, `--author`, `--author-email` and `--description` override the file's values. -- A config file may set `version` (a PEP 440 version such as `1.2.0`, quoted in YAML) to give the generated project that version instead of `0.1.0`; an invalid value is reported and nothing is written. -- 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. -- `list-features` shows the utility, tooling and deployment options that `init` offers, with package extras such as `pyjwt[crypto]`, 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. -- `init --template` and `startdemo` show the template's runtime dependencies in the summary and the `--dry-run` list, without comment lines or test tools, and the `--dry-run` file list matches the files that are written. Shell scripts in generated projects (`scripts/*.sh`) are executable. -- With `--no-venv`, `init` output no longer depends on which package managers are installed. If the requested package manager is not installed and an environment is being created, fastkit prints a warning and sets the project up for an available one; the project's metadata records the one actually used. -- `addroute` sorts generated and inserted imports the way isort (black profile) does, for any route name, including names that differ only by a number, and wraps an over-long inserted import. -- `startdemo` and `init` refuse to write through a symbolic link in the target directory and list the links before writing anything. -- When `startdemo` or `init` fails or is interrupted after overwriting files in an existing directory, those files get their original content back and the files the run created are removed; a file that cannot be restored keeps its original copy in a backup directory whose path is printed. An existing `.env` is kept even when a custom template ships one. -- `addroute` no longer treats a router registration or import under `if TYPE_CHECKING:` or `if False:` as present, and inserts imports below `from __future__` imports when the import anchor sits above them. -- `init` prints the summary, the files it created and the next steps; its internal steps are shown only with `fastkit --debug init`. -- `init` refuses a project name that is also the name of one of the project's dependencies (such as `sqlmodel` for `fastapi-sqlmodel`), because the package manager would then not install that dependency; the web generator refuses it too. -- `runserver` exits with the server's own exit status and a one-line message when the server stops with an error. Error tracebacks no longer show local variables, which could print environment variables and the secrets in them. -- In layered projects `addroute` adds the new resource's dependency to `src/api/deps.py`, and the routes it writes follow the example `items` routes: the return annotation is the response model and the 404 answer is documented. - -### Web generator - -- A web generator page on the documentation site, in all seven languages, creates a project in your browser and downloads it as a zip with the same files as `fastkit init ... --no-venv`; it shows the matching command line and the next steps, and nothing you enter is uploaded. -- Level, feature and next-step texts are translated for the documentation languages; the CLI and the generated files stay English. - -### `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. -- **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. -- The `single-file`, `layered`, `domain` and `production` levels (presets `single-module`, `classic-layered` and `domain-starter`) wire every selected feature into the template's `main.py`. -- **`single-file`** keeps its `src/main.py` when you add features. When a generated module reads the settings (database, authentication, tasks, cache, rate limiting, logging, telemetry), the settings move from `src/main.py` to `src/core/config.py` and the summary says so; with tooling-only selections `src/main.py` is unchanged. -- **Docker Compose with Alembic:** the generated compose file migrates the database in a one-shot step before the app (and worker) start, so `docker compose up --build` gives a working API with its tables. With SQLite and Docker Compose the database file is kept in a volume. -- **Selected features** each get a section in the project's `README.md` with the files and settings they add and a link to the FastAPI documentation. -- **Example `/items` with a database:** at the `layered`, `domain` and `production` levels with PostgreSQL, MySQL or SQLite, the example `/items` API stores its items in that database, and its tests run on in-memory SQLite; with MongoDB or Redis the items stay in their existing store and the README says so. `addroute` in such a project still adds an in-memory resource and prints a note that points to the database-backed items example. -- **Dependency versions:** a project generated from a feature selection keeps the minimum versions its template sets (for example `fastapi>=0.141.1`); a version you pin for the same package wins. Projects with PostgreSQL or MySQL list `aiosqlite` among the dev dependencies, because their tests run on in-memory SQLite, and MySQL projects install `aiomysql[rsa]`, which MySQL 8's default authentication needs. -- 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. -- **Docker Compose:** the containers always reach the compose database at its service name (a `DATABASE_URL` or `MONGODB_URL` in `.env` or the shell no longer redirects them), and the app, `migrate` and worker services share one image built once. -- **Dev tools:** test and lint tools (pytest and its plugins, ruff, pre-commit) stay out of runtime dependencies. They go to the dev dependency group and to a new `requirements-dev.txt` that includes `requirements.txt`. Generated Dockerfiles install runtime dependencies only; the Makefile, GitHub Actions workflow and devcontainer install `requirements-dev.txt`. -- **ruff:** projects created with the ruff option pass their own `ruff check`; generic classes use the Python 3.12 type parameter syntax. -- **Testing:** pytest and coverage settings go to `pyproject.toml`; no `pytest.ini` is generated. -- **Structured logging** writes one JSON access line per request (logger `app.access`) with the request id, method, path, status code and duration, and turns off uvicorn's own access log. -- **Docker Compose:** a comment in `docker-compose.yml` and a sentence in the README explain that `.env` runs the containers in development mode and how to switch. +- New `init` options: `--level`, `--database`, `--feature AXIS=VALUE`, `--extra-package`, `--template`, `--in-place`, and `--name` for `--project-name`. Author and email default to `git config` (an empty author is left out of `pyproject.toml`), and the package manager to uv when it is installed, otherwise pip (choose another in the customise step or with `--package-manager`). `-y` uses the defaults without asking. +- `init` prints a summary, the files it created and the next steps; its internal steps appear only with `fastkit --debug init`. It refuses a project name that is also the name of one of the project's dependencies (such as `sqlmodel`), because the package manager would not install that dependency. +- `--save-config` works for every `init` run except `--dry-run` and records the level or template. In a config file `project_name` is the only required key, `version` (a PEP 440 version, quoted in YAML) sets the project's version, and `--project-name`, `--author`, `--author-email` and `--description` override the file's values. +- `init --template` and `startdemo` check the template name before asking anything, suggest close matches and point to `fastkit list-templates`. Their summary and `--dry-run` list show only runtime dependencies, and the `--dry-run` file list matches the files that are written. +- `doctor [PATH]` checks for a committed or unignored `.env`, a missing `.env.example`, example secrets, an MCP server without authentication, CORS `*` with credentials, plain `sqlalchemy` without `greenlet`, CRLF scripts and more, and never prints secret values. `--fix` shows the diff of the safe fixes and asks once (`--yes` without a terminal), `--dry-run` / `--diff` only previews, `--format json` is for CI and `--force` checks projects generated before 1.4.0; it exits with 0 when no problem is left, 1 when problems remain and 2 when it could not run. +- `addroute` generates a typed CRUD resource with tests in both layouts (schemas, 201 with `Location`, 204, 404, paginated list) that follows the example `items` routes; in layered projects it adds the dependency to `src/api/deps.py`. New options: `--entity`, `--dry-run` and `--diff`; in a project from an older fastkit it also adds the `core/pagination.py` and `core/responses.py` the routes import. It refuses a route whose files exist, explains how to extend a single-file project such as `fastapi-hello` by hand, and sorts the imports it writes the way isort (black profile) does. +- `addroute` no longer counts a router registration under `if TYPE_CHECKING:` or `if False:` as present, and inserts imports below `from __future__` imports. +- `runserver` without `.venv` prints the commands that create it for the project's package manager before offering to continue. It exits with the server's exit status, and error tracebacks no longer show local variables, which could print secrets from the environment. +- `startdemo` and `init` refuse to write through a symbolic link in the target directory. When they fail or are interrupted after overwriting files in an existing directory, those files get their original content back; a file that cannot be restored keeps a backup whose path is printed. An existing `.env` is kept even when a custom template ships one. +- Poetry projects install with `poetry install` (`package-mode = false`); Poetry 2 or later is required, and fastkit stops before creating anything with an older one. PDM projects get their `.venv` inside the project even with `venv.in_project = false`. +- With `--no-venv` the output no longer depends on which package managers are installed. When an environment is being created and the requested package manager is missing, fastkit warns and sets the project up for an available one. +- `list-templates` lists templates from the simplest to the most involved, `list-features` shows every option `init` offers with package extras, and `fastkit --help` has a "Start here" section. A prompt that gets 10 invalid answers, or whose input ends, exits with status 1. `startdemo -y` asks only for the project name, and `runserver` rejects an invalid `app_module` in `[tool.fastapi-fastkit]`. +- fastkit requires click 8.2.0 or later. The minimum it declared before was too low: with click 8.1 the CLI did not start. + +### Generated projects + +- The levels after `hello` wire every selected feature into the template's own `main.py`. In `single-file`, the settings move to `src/core/config.py` only when a generated module reads them, and the summary says so. +- At the `layered`, `domain` and `production` levels with PostgreSQL, MySQL or SQLite, the example `/items` API uses that database and its tests run on in-memory SQLite. With MongoDB or Redis the items keep their own store and the README says so; `addroute` still adds an in-memory resource. +- JWT generates an OAuth2 password flow (`POST /api/v1/auth/register`, `POST /api/v1/auth/token`, `GET /api/v1/users/me`) with users in the selected SQL database or MongoDB (in memory otherwise). FastAPI-Users generates working routes with tests. +- Session-based logout invalidates the session, sessions have an absolute lifetime (`SESSION_ABSOLUTE_MAX_AGE`), and the demo account needs `ENABLE_DEMO_USERS=true`. OAuth2 requires `OAUTH_REDIRECT_BASE_URL` outside development. +- Rate-Limiting applies `RATE_LIMIT_DEFAULT` to every route and `RATE_LIMIT_AUTH` to the auth endpoints, using `limits` instead of slowapi. MongoDB uses PyMongo's async client instead of Motor, and the SQL session dependency no longer commits. +- Docker images run as a non-root user with a healthcheck and a `.dockerignore`, and get `.env` at run time. Docker Compose runs Alembic migrations in a one-shot `migrate` step before the app starts, keeps a SQLite file in a volume, always points the containers at the compose services (a `DATABASE_URL` in `.env` or the shell no longer redirects them), builds one image for the app, `migrate` and worker, and explains in its comments that `.env` runs the app in development mode. +- Test and lint tools stay out of runtime dependencies: they go to the dev group and to `requirements-dev.txt`, and Dockerfiles install runtime dependencies only. pytest and coverage settings live in `pyproject.toml`; projects with the ruff option pass their own `ruff check`. +- Structured logging writes one JSON access line per request with the request id, and Loguru is configured at startup. MySQL projects install `aiomysql[rsa]`, which MySQL 8's default authentication needs. +- A project generated from a feature selection keeps the minimum versions its template sets; a version you pin for the same package wins. ### Templates -- New `fastapi-hello`, the `hello` level: 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`. -- Generated code carries short comments that explain a FastAPI concept at its first use, each ending with a link to the matching FastAPI documentation page; a concept is explained once per project. -- Every template ships a `requirements-dev.txt` for test and lint tools and keeps them out of `requirements.txt`, so the Docker images of `fastapi-sqlmodel`, `fastapi-auth-jwt` and `fastapi-llm-agent` no longer contain them. -- `fastapi-single-module`, `fastapi-default` and `fastapi-domain-starter` ship pytest-cov with coverage settings and ruff in their dev dependencies, and keep their pytest settings in `pyproject.toml`. The `scripts/lint.sh` of `fastapi-default` and `fastapi-domain-starter` runs black, isort, mypy and ruff. -- `fastapi-sqlmodel` leaves the schema to Alembic by default (`CREATE_TABLES_ON_STARTUP=false`), so run `alembic upgrade head` before the first start. -- Every template except `fastapi-hello` ships the ruff configuration that `init`'s ruff option writes; the example templates also install ruff and run it from their lint scripts. `fastapi-single-module` projects pass isort and `mypy src`, and `fastapi-custom-response` uses Python 3.12 generic syntax for its response envelope. +- `fastapi-sqlmodel` runs on SQLite, PostgreSQL or MySQL, selected by `DATABASE_URL`, with driver extras, a docker compose file for a local server and migrations that work on all three. Its timestamps are timezone-aware and PUT is added. +- `fastapi-auth-jwt`: login, register and refresh are rate limited (`AUTH_RATE_LIMIT_*`), timestamps are timezone-aware, and `GET /api/v1/users/{user_id}` (superusers only) is added. +- `fastapi-mcp`: item reads are public, and PUT and PATCH work as specified. `fastapi-llm-agent`: the SSE stream is declared in OpenAPI, the conversation store is bounded (`MAX_CONVERSATIONS`, `MAX_MESSAGES_PER_CONVERSATION`), and there are hook points for authentication and rate limiting. +- Templates that store items in a JSON file no longer reuse ids and write atomically. Unused dependencies and `setup.cfg` files are removed, and Dockerfiles run as a non-root user. +- Every template ships a `requirements-dev.txt`, and every template except `fastapi-hello` ships a ruff configuration. `fastapi-single-module`, `fastapi-default` and `fastapi-domain-starter` include pytest-cov with coverage settings. ### Documentation -- 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. - -### Upgrade notes for existing projects +- Start, Learn, How-to, Reference and Contributing sections, with the same pages, menus and generated tables in all seven languages. Old page addresses redirect to their new pages. +- The CLI reference is generated from the CLI itself, and sections that described configuration files and environment variables fastkit never read are removed. -Upgrading fastkit does not change an existing project. Run `fastkit doctor` in it to see what can be checked and fixed automatically, then: +### For contributors -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**, including `fastapi-empty` projects, need no change and keep working with `addroute`, `doctor` and `runserver`. To move to PostgreSQL or MySQL with `fastapi-sqlmodel`, set `DATABASE_URL` and install the matching driver extra. -5. **Saved `--config` files** keep working: the CORS and Pagination options are accepted, and a `minimal` preset (or none) creates a `fastapi-single-module` project. -6. **Scripts that pipe answers into `fastkit init`** (or use `--interactive`) need options instead: `fastkit init --project-name api --level layered --database SQLite -y`, or `--config`. -7. **`startdemo` scripts** keep working. To switch, use `fastkit init --template --project-name `; `init` does not ask for author, email or description, so pass `--author`, `--author-email` and `--description`, or let git config fill author and email. -8. **`single-file` projects generated with features** now keep the template's `/health`, so in the OpenAPI schema its operation id is `health_health_get` and its summary is "Health" instead of `health_check_health_get` and "Health Check"; regenerate API clients that use operation ids. `tests/test_main.py` is the template's own. -9. **The old stacks** added packages without code. The closest replacements are `--level single-file` for `minimal`, and a level with `--database` and `--feature migrations=Alembic` or `--feature async_tasks=Celery` for `standard` and `full`, which generate the code for those packages. +- `init` options, levels, templates and their translated texts are registered in `src/fastapi_fastkit/catalog/catalog.toml` and its `i18n/.toml` overlays; a new template needs an entry there (see the template creation guide). +- CI builds the web generator from the wheel and compares its output with the CLI for every case; the docs deploy does the same before publishing. Reference tables in the docs are generated with `scripts/docs_blocks.py`. +- Install the `test-runtime` dependency group (`pdm install -G dev -G test-runtime`) so the tests that start generated applications run. ruff joins the dev dependencies. +- The translation script leaves code and generated blocks untouched and supports OpenAI only; `scripts/update_nav_translations.py`, `scripts/setup-i18n-structure.sh` and the termynal assets are removed. ## v1.5.2 (2026-12-01) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 86b54e06..87967d93 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -21,17 +21,29 @@ This document will also be a good indicator for you to gain insight into the dir FastAPI-fastkit uses following stacks: - Python 3.12+ -- click 8.1.7+ +- click 8.2.0+ - rich 13.9.2+ +- Jinja2 3.1+ - pre-commit - pytest for testing - black for code formatting - isort for import sorting - mypy for static type checking -### Current Source Structure (Version 1.X.X+) +### Current Source Structure (Version 2.X.X+) -![fastkit diagram](docs/img/fastkit_diagram.png) +``` +src/fastapi_fastkit/ +├── cli.py # `fastkit` command group and the smaller commands +├── commands/ # init and startdemo +├── backend/ # interactive prompts, package managers, addroute, doctor, inspection +├── catalog/ # catalog.toml (levels, features, templates) and i18n overlays +├── generation/ # prompt-free generate() used by the CLI and the web generator +├── core/ # settings and exceptions +├── utils/ # file I/O, platform and output helpers +├── fragments/ # Jinja2 fragments for init features +└── fastapi_project_template/ # bundled templates; modules/ holds the files addroute writes +``` ### Quick Setup with Makefile @@ -55,7 +67,8 @@ This single command will: - Install the package in development mode with all dev dependencies - Install documentation dependencies - Set up pre-commit hooks -- Create a ready-to-use development environment + +The tests that start generated applications also need the `test-runtime` dependency group; without it they are skipped. Install it with `pip install --group test-runtime` (pip 25.1 or later). [Development setup](docs/en/contributing/development-setup.md) shows the same setup with pdm or uv. ### Manual Setup (Alternative) @@ -234,6 +247,8 @@ When adding a new FastAPI template project, follow these guidelines: 1. Directory Structure: +A template needs at least `README.md-tpl`, `pyproject.toml-tpl` (with `fastapi` in `[project].dependencies`), a `main.py-tpl` that creates the `FastAPI` application (at the template root, in `src/` or in `src/app/`) and a `tests/` folder with a `test_*.py-tpl` module. Most templates also ship the files below (`fastapi-hello` deliberately ships only `main.py-tpl`, its tests, the requirements files, `README.md-tpl` and `.gitignore-tpl`): + ``` template-name/ ├── src/ @@ -256,7 +271,7 @@ template-name/ 2. File Extensions: - All Python source files must use `.py-tpl` extension - - Template files must include proper configuration files (`.env.example-tpl`, `.gitignore-tpl`, `.gitattributes-tpl`, etc.), never `.env-tpl` (fastkit generates `.env`) + - A template that reads settings ships `.env.example-tpl` (and `.gitattributes-tpl`), never `.env-tpl` (fastkit generates `.env`) - `.gitignore-tpl` must ignore `.env` and `.env.*` and keep `!.env.example` 3. Dependencies: @@ -269,18 +284,21 @@ template-name/ - `core/pagination.py-tpl` and `core/responses.py-tpl` identical to `fastapi_project_template/modules/core/` - Every `ENVIRONMENT` except `development` (`staging`, `production`) refuses a missing, example, or shorter than 32-byte `SECRET_KEY` +5. Catalog registration: + - Add a `[[templates]]` entry to `src/fastapi_fastkit/catalog/catalog.toml` and its translations to every `catalog/i18n/.toml` overlay (see the Template Creation Guide) + See [Template Creation Guide](docs/en/contributing/template-creation-guide.md) for the full rules and the conventions checklist. ### Security Requirements -1. Implementation Requirements: +1. Implementation Requirements (for templates with settings, that is every template except `fastapi-hello`): - Environment variables management (`.env.example` committed, `.env` git-ignored) - - Basic authentication system - - CORS configuration + - Authentication where the template's purpose needs it + - CORS origins only from `BACKEND_CORS_ORIGINS`, with credentials off for `*` - Exception handling and logging 2. Security Checks: - - All template code must pass `inspector.py` validation + - The template must pass the template inspection: `make inspect-template TEMPLATES="your-template-name"` - Include security middleware configurations - Follow security guidelines in SECURITY.md @@ -320,12 +338,12 @@ Additionally, a **Weekly Template Inspection** runs every Wednesday to validate - ⚡ No manual test file creation needed - 🛡️ Consistent quality standards applied -**Comprehensive Test Coverage:** -- ✅ **Project Creation**: Template copying and metadata injection -- ✅ **Package Manager Support**: UV, PDM, Poetry, and PIP compatibility -- ✅ **Virtual Environment**: Creation and dependency installation -- ✅ **Project Structure**: File and directory validation -- ✅ **FastAPI Integration**: Project identification and functionality +**What the tests check:** +- ✅ **Project Creation**: Every template is generated with `--no-venv`; metadata is injected and no placeholder is left +- ✅ **Project Structure**: `README.md-tpl` and `pyproject.toml-tpl` exist, no `setup.py-tpl`, and the expected files and folders are generated +- ✅ **Project Identification**: The generated project is recognised as a fastkit project + +These tests do not create a virtual environment or install anything. The template inspection (`make inspect-template`) installs the dependencies and runs the template's own tests. **Test Execution:** ```bash @@ -392,11 +410,12 @@ $ fastkit startdemo your-template-name --package-manager pip ```bash make dev-check # Must pass all checks ``` - - [ ] All files use .py-tpl extension - - [ ] FastAPI-fastkit dependency included + - [ ] All Python files use the `.py-tpl` extension + - [ ] No FastAPI-fastkit dependency + - [ ] Template registered in `catalog.toml` and the `i18n/.toml` overlays - [ ] Security requirements met - [ ] Documentation complete - - [ ] inspector.py validation passes + - [ ] `make inspect-template TEMPLATES="your-template-name"` passes - [ ] All make dev-check tests pass - [ ] **Automatic template tests pass** (new templates tested automatically) - [ ] **Package manager compatibility verified** (tested with UV, PDM, Poetry, PIP) diff --git a/README.md b/README.md index 95960883..952a8d0a 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@

- FastAPI-fastkit + FastAPI-fastkit

FastAPI-fastkit: Fast, easy-to-use starter kit for new users of Python and FastAPI @@ -12,7 +12,7 @@ GitHub Release - + Code coverage PyPI Downloads @@ -21,90 +21,108 @@ --- -This project was created to speed up the configuration of the development environment needed to develop Python-based web apps for new users of Python and [FastAPI](https://github.com/fastapi/fastapi). +FastAPI-fastkit creates [FastAPI](https://github.com/fastapi/fastapi) projects with working code and tests. Five levels lead from a single `main.py` of three endpoints to a production layout with a database, authentication, CI and Docker, each building on the one before. The code of every level explains itself: comments link the FastAPI documentation page behind each concept, and every project ends with a list of next steps. -This project was inspired by the `SpringBoot initializer` & Python Django's `django-admin` CLI operation. +**Documentation:** (English, 한국어, 日本語, 中文, Español, Français, Deutsch) -## Installation +## Try it in your browser -Install `FastAPI-fastkit` in a Python 3.12+ environment: +The [web generator](https://bnbong.github.io/FastAPI-fastkit/start/web-generator/) works like Spring Initializr: choose a level, a database and features, watch the file list change, and download the project as a zip file. It runs the fastkit generator itself in your browser through [Pyodide](https://pyodide.org/), so nothing you enter is sent anywhere. The zip holds the same files as the `fastkit init ... --no-venv` command that the page shows next to the form. + +![The web generator with the domain level, SQLite and JWT authentication chosen: the customise form on the left; on the right the file list of 52 files with the auth package open, the matching fastkit init command and the Generate and download button](https://raw.githubusercontent.com/bnbong/FastAPI-fastkit/main/docs/img/2.0/web-generator-customise.png) + +After the download, the page lists the next steps for this project and what each selected feature added: its files, its settings and a link to the documentation. + +![The web generator after the download: shop.zip downloaded with 52 files, the numbered Next steps from cd shop to fastkit init --level production, and the Selected features section for the SQLite database](https://raw.githubusercontent.com/bnbong/FastAPI-fastkit/main/docs/img/2.0/web-generator-result.png) + +You still need Python on your machine to run the project. [Web generator](https://bnbong.github.io/FastAPI-fastkit/start/web-generator/) in the documentation describes every choice on the page. + +## Install + +fastkit needs Python 3.12 or later. Install it with pip into a virtual environment, or with uv as a tool of its own: ```console $ pip install fastapi-fastkit +$ uv tool install fastapi-fastkit ``` -To try fastkit without installing anything, use the [web generator](https://bnbong.github.io/FastAPI-fastkit/start/web-generator/) in your browser. [Installation](https://bnbong.github.io/FastAPI-fastkit/start/installation/) covers uv and the other options. +When uv is installed, fastkit uses it for the projects it creates; otherwise it uses pip. pdm and Poetry are also supported. [Installation](https://bnbong.github.io/FastAPI-fastkit/start/installation/) covers each option. -## Quick start +## Create a project -`fastkit init` asks for a project name and a level, creates the project and installs its dependencies. Press Enter at every question to get the `hello` level: one `main.py` with three endpoints and their tests. The run ends with the next steps: +`fastkit init` asks for a project name and a level, shows a summary, creates the project and installs its dependencies. Type a project name and press Enter at every other question to get the `hello` level: one `main.py` with three endpoints and a test for each. The run ends with a Next steps panel, and the project's `README.md` lists the steps for a fresh checkout. + +![Terminal running fastkit init: the project name shop, the Levels table, the Project summary and the Next steps panel](https://raw.githubusercontent.com/bnbong/FastAPI-fastkit/main/docs/img/2.0/generate-init-dialogue.svg) + +In scripts and CI, pass every choice as an option and nothing is asked: ```console -$ fastkit init - -⚡ Create a FastAPI project - -Project name: shop -... -╭───────────────────────────────── Next steps ─────────────────────────────────╮ -│ 1. Go to the project folder. │ -│ cd shop │ -│ 2. Start the development server and open http://127.0.0.1:8000/docs. │ -│ fastkit runserver │ -│ 3. Run the tests. │ -│ uv run pytest │ -│ 4. Add a resource by imitation: copy the `Item` models, `create_item`, │ -│ `read_item` and their tests, and rename them for `/users`. │ -│ 5. Read `main.py` from top to bottom: each comment links the FastAPI │ -│ tutorial page that explains it. │ -│ 6. When you want more structure, create a project at the next level. │ -│ fastkit init --level single-file │ -│ README.md lists the steps for a fresh checkout of the project. │ -╰──────────────────────────────────────────────────────────────────────────────╯ +$ fastkit init --project-name shop --level domain --database SQLite --feature authentication=JWT -y ``` -The [Learn track](https://bnbong.github.io/FastAPI-fastkit/learn/generate/) starts from this project and follows it up to the production level. +In the project folder, `fastkit runserver` starts the app, and FastAPI's interactive documentation opens at . For the `hello` project from the guided run above: -## Levels +![Swagger UI at /docs of the shop app listing GET /, POST /items and GET /items/{item_id}, with the Schemas section below](https://raw.githubusercontent.com/bnbong/FastAPI-fastkit/main/docs/img/2.0/generate-swagger-ui.png) -Each level adds structure to the one above it. At every level after `hello` you can choose a database and features (authentication, background tasks, caching, monitoring, migrations, tooling, Docker and more), and fastkit writes their code and tests. +## Learn FastAPI from the generated code -| Level | Description | Template | -|---|---|---| -| `hello` | One main.py: 3 endpoints, in-memory data, tests. | [`fastapi-hello`](src/fastapi_fastkit/fastapi_project_template/fastapi-hello/README.md-tpl) | -| `single-file` | The whole app in one module, with settings and tests. | [`fastapi-single-module`](src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/README.md-tpl) | -| `layered` | Separate layers: routes, CRUD, schemas, core config. | [`fastapi-default`](src/fastapi_fastkit/fastapi_project_template/fastapi-default/README.md-tpl) | -| `domain` | One package per domain: router, service, repository. | [`fastapi-domain-starter`](src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/README.md-tpl) | -| `production` | domain plus PostgreSQL, Alembic, JWT, CI and Docker. | [`fastapi-domain-starter`](src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/README.md-tpl) | +At every level, each FastAPI concept is explained where it first appears in the project, in a comment of at most two lines that ends with the link to the official tutorial page. The start of `main.py` at the `hello` level: -```console -$ fastkit init --project-name api --level domain --database SQLite --feature authentication=JWT +```python +# `app` is the application object that uvicorn serves. +# https://fastapi.tiangolo.com/tutorial/first-steps/ +app = FastAPI(title="shop") + + +# An argument typed with a pydantic model (`item: Item`) is the validated JSON body. +# https://fastapi.tiangolo.com/tutorial/body/ +class Item(BaseModel): + name: str = Field(min_length=1, max_length=100) + price: float = Field(gt=0) + description: str | None = None ``` -See [Choose a level or an example](https://bnbong.github.io/FastAPI-fastkit/how-to/choose-a-level/) and [Customise features](https://bnbong.github.io/FastAPI-fastkit/how-to/customise-features/). +The [Learn track](https://bnbong.github.io/FastAPI-fastkit/learn/generate/) follows one project, `shop`, through six pages: generate it, understand the code, extend it with routers and dependencies, test it, move it to a domain layout with a SQL database, and deploy it at the production level with Docker. + +## Levels + +Each level adds structure to the one above it. fastkit does not convert a project to another level; the Learn track shows how to move your code to the next one: + +| Level | What you get | +|---|---| +| `hello` | One `main.py`: three endpoints, data in memory, tests. | +| `single-file` | The whole app in one module, with settings and tests. | +| `layered` | Separate layers: routes, CRUD, schemas, core config. | +| `domain` | One package per domain: router, service, repository. | +| `production` | `domain` plus PostgreSQL, Alembic migrations, JWT authentication, coverage, structured logging, ruff, GitHub Actions, Docker and Docker Compose. | + +At every level after `hello` you can choose a database (PostgreSQL, MySQL or SQLite through async SQLAlchemy, MongoDB or Redis) and features: authentication, background tasks, caching, monitoring, rate limiting, WebSocket, migrations, logging, developer tooling and container deployment. fastkit writes the code and configuration for each choice, with tests where they apply, and the generated README gets one section per selected feature. [Choose a level or an example](https://bnbong.github.io/FastAPI-fastkit/how-to/choose-a-level/) compares the levels, and [Levels and features](https://bnbong.github.io/FastAPI-fastkit/reference/levels-and-features/) lists every option with its packages. ## Example projects -`fastkit init --template ` copies an example project as it is: +`fastkit init --template ` copies a complete example project as it is: -| Template | Description | +| Template | Shows | |---|---| -| [`fastapi-custom-response`](src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/README.md-tpl) | Async Item Management API with Custom Response System | -| [`fastapi-auth-jwt`](src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/README.md-tpl) | FastAPI JWT Authentication | -| [`fastapi-sqlmodel`](src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/README.md-tpl) | FastAPI SQLModel | -| [`fastapi-mcp`](src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/README.md-tpl) | FastAPI MCP Project | -| [`fastapi-llm-agent`](src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/README.md-tpl) | FastAPI LLM Agent | +| `fastapi-custom-response` | One response envelope for every answer, errors included | +| `fastapi-auth-jwt` | Accounts with access and refresh tokens | +| `fastapi-sqlmodel` | SQLModel and Alembic, with SQLite, PostgreSQL or MySQL | +| `fastapi-mcp` | Your API exposed to AI clients as MCP tools | +| `fastapi-llm-agent` | A streamed Claude chat reply with a tool-call loop | + +[Start from an example project](https://bnbong.github.io/FastAPI-fastkit/how-to/example-projects/) describes what each one needs. + +## Keep working on the project + +- `fastkit addroute orders` adds a resource to a generated project at any level except `hello`: its routes, schemas, data layer and tests, in the project's own layout, with the router registered. `--diff` previews the change. +- `fastkit runserver` starts the development server. +- `fastkit doctor` checks a project for problems that newer templates fix, such as a committed `.env`, an example secret still in use or shell scripts with CRLF line endings, and `fastkit doctor --fix` repairs the safe ones. [Check and fix a project](https://bnbong.github.io/FastAPI-fastkit/how-to/doctor/) explains the checks. -[Start from an example project](https://bnbong.github.io/FastAPI-fastkit/how-to/example-projects/) describes what each one shows and what it needs. +[CLI reference](https://bnbong.github.io/FastAPI-fastkit/reference/cli/) describes every command and option. -## Documentation +## Upgrading from fastkit 1.x -- [Start](https://bnbong.github.io/FastAPI-fastkit/start/installation/): installation and the web generator -- [Learn](https://bnbong.github.io/FastAPI-fastkit/learn/generate/): learn FastAPI with one project, from `hello` to `production` -- [How-to](https://bnbong.github.io/FastAPI-fastkit/how-to/choose-a-level/): levels, features, config files, example projects, `fastkit doctor`, upgrading from 1.x, troubleshooting -- [Reference](https://bnbong.github.io/FastAPI-fastkit/reference/cli/): every command and option, levels and features, generated projects -- [Contributing](https://bnbong.github.io/FastAPI-fastkit/contributing/development-setup/): development setup, templates, translations -- [Changelog](https://bnbong.github.io/FastAPI-fastkit/changelog/) +Projects you already have keep working. `fastkit startdemo` is now `fastkit init --template` (the old command still works), the stack question is gone, and the templates `fastapi-async-crud`, `fastapi-dockerized`, `fastapi-psql-orm` and `fastapi-empty` were removed. [Upgrade from fastkit 1.x](https://bnbong.github.io/FastAPI-fastkit/how-to/upgrade-from-1x/) lists what to change in your commands and scripts. ## Contributing @@ -117,7 +135,7 @@ $ make dev-setup $ make dev-check ``` -Read [CONTRIBUTING.md](CONTRIBUTING.md), the [Code of Conduct](CODE_OF_CONDUCT.md) and the [security policy](SECURITY.md) before you open a pull request. [Development setup](https://bnbong.github.io/FastAPI-fastkit/contributing/development-setup/) explains the tests and checks. +Read [CONTRIBUTING.md](https://github.com/bnbong/FastAPI-fastkit/blob/main/CONTRIBUTING.md), the [Code of Conduct](https://github.com/bnbong/FastAPI-fastkit/blob/main/CODE_OF_CONDUCT.md) and the [security policy](https://github.com/bnbong/FastAPI-fastkit/blob/main/SECURITY.md) before you open a pull request. [Development setup](https://bnbong.github.io/FastAPI-fastkit/contributing/development-setup/) explains the tests and checks. ## Significance of FastAPI-fastkit diff --git a/docs/de/contributing/template-creation-guide.md b/docs/de/contributing/template-creation-guide.md index dda6c856..955dc6f6 100644 --- a/docs/de/contributing/template-creation-guide.md +++ b/docs/de/contributing/template-creation-guide.md @@ -10,7 +10,7 @@ Dateien, die auf `-tpl` enden, verlieren dieses Suffix, wenn fastkit das Templat Ein Template braucht mindestens: -- `README.md-tpl`. +- `README.md-tpl` und eine `main.py-tpl`, die die `FastAPI`-Anwendung erstellt, auf der obersten Ebene des Templates, in `src/` oder in `src/app/`. - `pyproject.toml-tpl` mit `fastapi` in `[project].dependencies`. - Einen Ordner `tests/` mit mindestens einem Modul `test_*.py-tpl`. @@ -123,7 +123,7 @@ app = FastAPI( | Junk files | Kein `.DS_Store`, `__pycache__`, `.venv`, `.pyc` und Ähnliches. | | Dependencies | `fastapi` ist deklariert. | | Configuration consistency | Die Festlegungen auf Python 3.12, kein Paket aus `[project].dependencies`, das in `requirements.txt-tpl` fehlt, keine Abhängigkeit von `FastAPI-fastkit`. | -| FastAPI implementation | Das erzeugte Projekt erstellt eine Anwendung `FastAPI(...)`. | +| FastAPI implementation | Das erzeugte Projekt hat eine `main.py` auf der obersten Ebene, in `src/` oder in `src/app/`, und diese erstellt eine Anwendung `FastAPI(...)`. | | Placeholder substitution | Im erzeugten Projekt ist kein `` übrig. | | Compile check | Jede Python-Datei lässt sich kompilieren. | | Template tests | Erstellt eine virtuelle Umgebung, installiert die Abhängigkeiten und führt `scripts/test.sh` aus, oder `pytest tests/ -v`, wenn es dieses Skript nicht gibt. | diff --git a/docs/de/index.md b/docs/de/index.md index 8228ec61..c3f85398 100644 --- a/docs/de/index.md +++ b/docs/de/index.md @@ -16,19 +16,43 @@

-FastAPI-fastkit erstellt [FastAPI](https://github.com/fastapi/fastapi)-Projekte, von einer einzelnen `main.py` bis zu einem Produktionsaufbau mit Datenbank, Authentifizierung, Tests und Docker. Mit demselben Befehl `fastkit` startest du das Projekt anschließend, fügst ihm Routen hinzu und prüfst es auf bekannte Probleme. +FastAPI-fastkit erstellt [FastAPI](https://github.com/fastapi/fastapi)-Projekte mit lauffähigem Code und Tests. Fünf Stufen führen von einer einzelnen `main.py` mit drei Endpunkten bis zu einem Produktionsaufbau mit Datenbank, Authentifizierung, CI und Docker, und jede Stufe baut auf der vorherigen auf. Der Code jeder Stufe erklärt sich selbst: Kommentare verlinken zu jedem Konzept die Seite der FastAPI-Dokumentation, die es erklärt, und am Ende jedes Projekts steht eine Liste der nächsten Schritte. -## Hier anfangen +## Wo anfangen {#where-to-start} -- **fastkit installieren**: Folge den Schritten unter [Installation](start/installation.md) und führe danach `fastkit init` aus. -- **Ohne Installation ausprobieren**: Der [Web-Generator](start/web-generator.md) erstellt ein Projekt in deinem Browser und gibt es dir als Zip-Datei. -- **Neu bei FastAPI**: Der Lernpfad beginnt mit [Deine erste FastAPI-Anwendung erzeugen](learn/generate.md) und begleitet ein einziges Projekt von einer einzelnen Datei bis in die Produktion. +- **Im Browser ausprobieren**: Der [Web-Generator](start/web-generator.md) erstellt ein Projekt, ohne dass du etwas installieren musst, und gibt es dir als Zip-Datei. +- **fastkit installieren und ein Projekt erstellen**: Folge den Schritten unter [Installation](start/installation.md) und führe danach `fastkit init` aus. +- **FastAPI Schritt für Schritt lernen**: Der Lernpfad beginnt mit [Deine erste FastAPI-Anwendung erzeugen](learn/generate.md) und begleitet ein einziges Projekt bis in die Produktion. +- **Etwas nachschlagen**: Jede Seite der [Anleitungen](how-to/choose-a-level.md) löst eine einzelne Aufgabe, und die [Referenz](reference/cli.md) beschreibt jeden Befehl, jede Option, jede Stufe und jedes Feature. +- **Von fastkit 1.x aktualisieren**: Die Seite [Von fastkit 1.x aktualisieren](how-to/upgrade-from-1x.md) listet auf, was du in deinen Befehlen und Skripten ändern musst. Projekte, die du bereits hast, funktionieren weiterhin. + +## Im Browser {#in-your-browser} + +Der [Web-Generator](start/web-generator.md) funktioniert wie Spring Initializr: Du wählst eine Stufe, eine Datenbank und Features, siehst zu, wie sich die Dateiliste ändert, und lädst das Projekt als Zip-Datei herunter. Der Web-Generator führt den fastkit-Generator selbst über [Pyodide](https://pyodide.org/) in deinem Browser aus, daher wird nichts, was du eingibst, irgendwohin gesendet. Das Zip enthält dieselben Dateien wie der Befehl `fastkit init ... --no-venv`, den die Seite neben dem Formular anzeigt. ![Die Seite des Web-Generators mit ausgewählter Stufe layered und SQLite: das Formular, die Dateiliste, der passende Befehl fastkit init und die Schaltfläche „Generate and download“](img/2.0/index-web-generator.png) -## Stufen +Nach dem Download listet die Seite die nächsten Schritte für dieses Projekt auf und zeigt, was jedes ausgewählte Feature hinzugefügt hat: seine Dateien, seine Einstellungen und einen Link zur Dokumentation. + +![Der Web-Generator nach dem Download: shop.zip mit 52 Dateien heruntergeladen, die nummerierten „Next steps“ von cd shop bis fastkit init --level production und der Abschnitt „Selected features“ für die SQLite-Datenbank](img/2.0/web-generator-result.png) + +## Im Terminal {#in-your-terminal} + +`fastkit init` fragt nach einem Projektnamen und einer Stufe, zeigt eine Zusammenfassung, erstellt das Projekt und installiert seine Abhängigkeiten. Wenn du einen Projektnamen eingibst und bei jeder weiteren Frage die Eingabetaste drückst, erhältst du die Stufe `hello`. Am Ende zeigt der Befehl das Panel „Next steps“, und die `README.md` des Projekts listet die Schritte für ein frisch geklontes Projekt auf. + +![Terminal mit fastkit init: der Projektname shop, die Tabelle „Levels“, die Zusammenfassung „Project summary“ und das Panel „Next steps“](img/2.0/generate-init-dialogue.svg) + +In Skripten und in der CI übergibst du jede Auswahl als Option, dann wird nichts abgefragt: -`fastkit init` fragt nach einer Stufe. Jede Stufe baut auf der darüberstehenden auf und bringt mehr Struktur mit; `hello` ist die Vorgabe. +```console +$ fastkit init --project-name shop --level domain --database SQLite --feature authentication=JWT -y +``` + +Im Projekt startet `fastkit runserver` die Anwendung, `fastkit addroute` fügt eine Ressource mit ihren Routen, Schemas, ihrer Datenschicht und ihren Tests hinzu (auf jeder Stufe außer `hello`), und `fastkit doctor` prüft das Projekt auf bekannte Probleme. fastkit benötigt Python 3.12 oder neuer und funktioniert mit uv, pip, pdm und Poetry. + +## Stufen {#levels} + +Jede Stufe baut auf der darüberstehenden auf und bringt mehr Struktur mit. fastkit wandelt ein Projekt nicht in eine andere Stufe um; der Lernpfad zeigt, wie du deinen Code in die nächste Stufe überführst. Auf jeder Stufe außer `hello` kannst du eine Datenbank und Features wie Authentifizierung, Hintergrundtasks, Caching, Migrationen, Entwicklerwerkzeuge und Docker wählen: siehe [Features anpassen](how-to/customise-features.md). @@ -42,7 +66,18 @@ FastAPI-fastkit erstellt [FastAPI](https://github.com/fastapi/fastapi)-Projekte, -## Beispielprojekte +## FastAPI mit einem einzigen Projekt lernen {#learn-fastapi} + +Auf jeder Stufe wird jedes FastAPI-Konzept dort erklärt, wo es im erzeugten Code zum ersten Mal vorkommt, und zwar in einem kurzen Kommentar, der mit dem Link zur passenden Seite des offiziellen FastAPI-Tutorials endet. Der Lernpfad begleitet ein einziges Projekt namens `shop` von der Stufe `hello` bis zur Stufe `production`: + +1. [Deine erste FastAPI-Anwendung erzeugen](learn/generate.md) +2. [Den Code verstehen](learn/understand.md) +3. [Die Anwendung erweitern](learn/extend.md) +4. [Die Anwendung testen](learn/test.md) +5. [Zu einer Domänenstruktur und einer Datenbank wechseln](learn/migrate.md) +6. [In Produktion deployen](learn/deploy.md) + +## Beispielprojekte {#example-projects} `fastkit init --template ` kopiert statt einer Stufe ein vollständiges Beispielprojekt. Die Seite [Mit einem Beispielprojekt starten](how-to/example-projects.md) beschreibt jedes einzelne. @@ -58,11 +93,12 @@ FastAPI-fastkit erstellt [FastAPI](https://github.com/fastapi/fastapi)-Projekte, -## Aufbau der Dokumentation +## Aufbau der Dokumentation {#documentation-map} - [Anleitungen](how-to/choose-a-level.md): Seiten zu einzelnen Aufgaben, etwa eine Stufe wählen, Features anpassen, `fastkit init` per Skript aufrufen, ein Projekt prüfen und von fastkit 1.x aktualisieren. - [Referenz](reference/cli.md): alle Befehle und Optionen, die Stufen und Features und der Inhalt eines erzeugten Projekts. - [Mitwirken](contributing/development-setup.md): das Repository einrichten, ein Template schreiben und die Dokumentation übersetzen. +- Die Dokumentation gibt es auf English, 한국어, 日本語, 中文, Español, Français und Deutsch: Über das Sprachmenü oben auf der Seite wechselst du die Sprache. ## Bedeutung von FastAPI-fastkit diff --git a/docs/de/learn/generate.md b/docs/de/learn/generate.md index 2d2f08cb..45826d82 100644 --- a/docs/de/learn/generate.md +++ b/docs/de/learn/generate.md @@ -2,7 +2,7 @@ Auf dieser Seite erstellst du mit `fastkit init` eine kleine FastAPI-Anwendung, startest sie mit `fastkit runserver` und sendest ihr Requests. Dabei lernst du das Anwendungsobjekt von FastAPI kennen, außerdem Pfadoperationen, den Server uvicorn und die interaktive API-Dokumentation, die FastAPI für dich erzeugt. -Die Stufe `hello` erstellt ein Projekt namens `shop` mit einer einzigen `main.py` (drei Endpunkte, Items im Arbeitsspeicher) und einem Test für jeden Endpunkt. Der restliche Lernpfad baut dieses Projekt weiter aus, behalte also den Namen `shop` bei. Du brauchst fastkit ([Installation](../start/installation.md)) und für die Befehle auf dieser Seite [uv](https://docs.astral.sh/uv/). +Die Stufe `hello` erstellt ein Projekt namens `shop` mit einer einzigen `main.py` (drei Endpunkte, Items im Arbeitsspeicher) und einem Test für jeden Endpunkt. Der restliche Lernpfad begleitet dieses Projekt, behalte also den Namen `shop` bei. Du brauchst fastkit ([Installation](../start/installation.md)) und für die Befehle auf dieser Seite [uv](https://docs.astral.sh/uv/). ## Das Projekt erstellen ![Terminal mit fastkit init: der Projektname shop, die Tabelle „Levels“, die Zusammenfassung „Project summary“ und das Panel „Next steps“](../img/2.0/generate-init-dialogue.svg) @@ -56,7 +56,7 @@ Create the project? [Y/n]: ╰──────────────────────────────────────────────────────────────────────────────╯ ``` -Die Zeile „Author“ stammt aus `git config` (hier war in Git kein Autorenname eingetragen). fastkit hat in `shop/.venv` eine virtuelle Umgebung angelegt und die Pakete darin installiert. Das Panel „Next steps“ ist deine To-do-Liste; die `README.md` des Projekts wiederholt sie. Mit `fastkit init --no-venv` schreibt fastkit nur die Dateien, und `uv sync` im Projektordner legt `.venv` nachträglich an, so wie nach dem Klonen des Projekts aus Git. +Die Zeile „Author“ stammt aus `git config` (hier war in Git kein Autorenname eingetragen). fastkit hat in `shop/.venv` eine virtuelle Umgebung angelegt und die Pakete darin installiert. Das Panel „Next steps“ ist deine To-do-Liste; die `README.md` des Projekts listet die Schritte für ein frisch geklontes Projekt auf. Mit `fastkit init --no-venv` schreibt fastkit nur die Dateien, und `uv sync` im Projektordner legt `.venv` nachträglich an, so wie nach dem Klonen des Projekts aus Git. ## Was fastkit erstellt hat diff --git a/docs/de/reference/generated-projects.md b/docs/de/reference/generated-projects.md index 5c0fa1fc..2f15442f 100644 --- a/docs/de/reference/generated-projects.md +++ b/docs/de/reference/generated-projects.md @@ -103,7 +103,7 @@ Außerdem beginnt die `description` in `[project]` mit `[FastAPI-fastkit templat ## Die Liste „Next steps“ in der README.md -Jede erzeugte `README.md` enthält zwischen zwei Kommentarzeilen dieselbe Liste „Next steps“, die `fastkit init` am Ende ausgibt: +Jede erzeugte `README.md` enthält zwischen zwei Kommentarzeilen die „Next steps“, die `fastkit init` am Ende ausgibt, hier aber für ein frisch geklontes Projekt formuliert (kein `cd`, ein Schritt, der die Umgebung anlegt, und uvicorn zum Starten des Servers): ```markdown @@ -116,7 +116,7 @@ Wenn du Features auswählst, enthält der Block außerdem einen Abschnitt „Sel ## Konzeptkommentare -Erzeugter Code erklärt jedes FastAPI-Konstrukt dort, wo es zum ersten Mal vorkommt, mit einem zweizeiligen Kommentar: zuerst ein Satz, danach die Adresse der Seite der FastAPI-Dokumentation zu diesem Konstrukt. +In einem Projekt, das aus einer Stufe erstellt wurde, erklären der Code des Templates und der Code, den Features hinzufügen, jedes FastAPI-Konstrukt dort, wo es zum ersten Mal vorkommt, mit einem zweizeiligen Kommentar: zuerst ein Satz, danach die Adresse der Seite der FastAPI-Dokumentation zu diesem Konstrukt. Die Beispiel-Templates enthalten keine solchen Kommentare; die Anleitung zu den Beispielprojekten listet auf, welche Konzepte jedes einzelne zeigt. ```python title="src/main.py" # `app` is the FastAPI application that uvicorn serves: `uvicorn src.main:app`. diff --git a/docs/en/contributing/template-creation-guide.md b/docs/en/contributing/template-creation-guide.md index dc8578c1..1683060e 100644 --- a/docs/en/contributing/template-creation-guide.md +++ b/docs/en/contributing/template-creation-guide.md @@ -10,7 +10,7 @@ Files that end in `-tpl` lose the suffix when fastkit copies the template: `src/ A template needs at least: -- `README.md-tpl`. +- `README.md-tpl` and a `main.py-tpl` that creates the `FastAPI` application, at the template root, in `src/` or in `src/app/`. - `pyproject.toml-tpl` with `fastapi` in `[project].dependencies`. - A `tests/` folder with at least one `test_*.py-tpl` module. @@ -123,7 +123,7 @@ app = FastAPI( | Junk files | No `.DS_Store`, `__pycache__`, `.venv`, `.pyc` and the like. | | Dependencies | `fastapi` is declared. | | Configuration consistency | The Python 3.12 pins, no package of `[project].dependencies` missing from `requirements.txt-tpl`, no `FastAPI-fastkit` dependency. | -| FastAPI implementation | The generated project creates a `FastAPI(...)` application. | +| FastAPI implementation | The generated project has a `main.py` at the root, in `src/` or in `src/app/`, and it creates a `FastAPI(...)` application. | | Placeholder substitution | No `` is left in the generated project. | | Compile check | Every Python file compiles. | | Template tests | Creates a virtual environment, installs the dependencies and runs `scripts/test.sh`, or `pytest tests/ -v` when there is no such script. | diff --git a/docs/en/index.md b/docs/en/index.md index 06e76fdc..9cbcbce7 100644 --- a/docs/en/index.md +++ b/docs/en/index.md @@ -16,19 +16,43 @@

-FastAPI-fastkit creates [FastAPI](https://github.com/fastapi/fastapi) projects, from a single `main.py` to a production layout with a database, authentication, tests and Docker. The same `fastkit` command then runs the project, adds routes to it and checks it for known problems. +FastAPI-fastkit creates [FastAPI](https://github.com/fastapi/fastapi) projects with working code and tests. Five levels lead from a single `main.py` of three endpoints to a production layout with a database, authentication, CI and Docker, each building on the one before. The code of every level explains itself: comments link the FastAPI documentation page behind each concept, and every project ends with a list of next steps. -## Start here +## Where to start {#where-to-start} -- **Install fastkit**: follow [Installation](start/installation.md), then run `fastkit init`. -- **Try it without installing**: the [web generator](start/web-generator.md) creates a project in your browser and gives you a zip file. -- **New to FastAPI**: the Learn track starts with [Generate your first FastAPI app](learn/generate.md) and follows one project from a single file to production. +- **Try it in your browser**: the [web generator](start/web-generator.md) creates a project without installing anything and gives you a zip file. +- **Install fastkit and create a project**: follow [Installation](start/installation.md), then run `fastkit init`. +- **Learn FastAPI step by step**: the Learn track starts with [Generate your first FastAPI app](learn/generate.md) and follows one project up to production. +- **Look something up**: the [How-to](how-to/choose-a-level.md) pages solve one task each, and the [Reference](reference/cli.md) describes every command, option, level and feature. +- **Upgrade from fastkit 1.x**: [Upgrade from fastkit 1.x](how-to/upgrade-from-1x.md) lists what to change in your commands and scripts. Projects you already have keep working. + +## In your browser {#in-your-browser} + +The [web generator](start/web-generator.md) works like Spring Initializr: choose a level, a database and features, watch the file list change, and download the project as a zip file. It runs the fastkit generator itself in your browser through [Pyodide](https://pyodide.org/), so nothing you enter is sent anywhere. The zip holds the same files as the `fastkit init ... --no-venv` command that the page shows next to the form. ![The web generator page with the layered level and SQLite selected: the form, the file list, the matching fastkit init command and the Generate and download button](img/2.0/index-web-generator.png) -## Levels +After the download, the page lists the next steps for this project and what each selected feature added: its files, its settings and a link to the documentation. + +![The web generator after the download: shop.zip downloaded with 52 files, the numbered Next steps from cd shop to fastkit init --level production, and the Selected features section for the SQLite database](img/2.0/web-generator-result.png) + +## In your terminal {#in-your-terminal} + +`fastkit init` asks for a project name and a level, shows a summary, creates the project and installs its dependencies. Type a project name and press Enter at every other question to get the `hello` level. The run ends with a Next steps panel, and the project's `README.md` lists the steps for a fresh checkout. + +![Terminal running fastkit init: the project name shop, the Levels table, the Project summary and the Next steps panel](img/2.0/generate-init-dialogue.svg) + +In scripts and CI, pass every choice as an option and nothing is asked: -`fastkit init` asks for a level. Each level adds structure to the one above it, and `hello` is the default. +```console +$ fastkit init --project-name shop --level domain --database SQLite --feature authentication=JWT -y +``` + +In the project, `fastkit runserver` starts the app, `fastkit addroute` adds a resource with its routes, schemas, data layer and tests (at any level except `hello`), and `fastkit doctor` checks the project for known problems. fastkit needs Python 3.12 or later and works with uv, pip, pdm and Poetry. + +## Levels {#levels} + +Each level adds structure to the one above it. fastkit does not convert a project to another level; the Learn track shows how to move your code to the next one. At every level after `hello` you can choose a database and features such as authentication, background tasks, caching, migrations, developer tooling and Docker: see [Customise features](how-to/customise-features.md). @@ -42,7 +66,18 @@ FastAPI-fastkit creates [FastAPI](https://github.com/fastapi/fastapi) projects, -## Example projects +## Learn FastAPI with one project {#learn-fastapi} + +At every level, each FastAPI concept is explained where it first appears in the generated code, in a short comment that ends with the link to the official tutorial page. The Learn track follows one project, `shop`, from the `hello` level to `production`: + +1. [Generate your first FastAPI app](learn/generate.md) +2. [Understand the code](learn/understand.md) +3. [Extend the app](learn/extend.md) +4. [Test the app](learn/test.md) +5. [Move to a domain layout and a database](learn/migrate.md) +6. [Deploy to production](learn/deploy.md) + +## Example projects {#example-projects} `fastkit init --template ` copies a complete example project instead of a level. [Start from an example project](how-to/example-projects.md) describes each one. @@ -58,11 +93,12 @@ FastAPI-fastkit creates [FastAPI](https://github.com/fastapi/fastapi) projects, -## Documentation map +## Documentation map {#documentation-map} - [How-to](how-to/choose-a-level.md): task pages, such as choosing a level, customising features, scripting `fastkit init`, checking a project and upgrading from fastkit 1.x. - [Reference](reference/cli.md): every command and option, the levels and features, and what a generated project contains. - [Contributing](contributing/development-setup.md): set up the repository, write a template and translate the docs. +- The documentation is available in English, 한국어, 日本語, 中文, Español, Français and Deutsch: use the language menu at the top of the page. ## Significance of FastAPI-fastkit diff --git a/docs/en/learn/generate.md b/docs/en/learn/generate.md index a5399f57..5decd538 100644 --- a/docs/en/learn/generate.md +++ b/docs/en/learn/generate.md @@ -2,7 +2,7 @@ On this page you create a small FastAPI application with `fastkit init`, start it with `fastkit runserver` and send it requests. Along the way you meet the FastAPI application object, path operations, the uvicorn server and the interactive API documentation that FastAPI builds for you. -The `hello` level creates a project called `shop` with one `main.py`: three endpoints, items kept in memory, and a test for each endpoint. The rest of the Learn track grows this project, so keep the name `shop`. You need fastkit ([Installation](../start/installation.md)) and, for the commands on this page, [uv](https://docs.astral.sh/uv/). +The `hello` level creates a project called `shop` with one `main.py`: three endpoints, items kept in memory, and a test for each endpoint. The rest of the Learn track follows this project, so keep the name `shop`. You need fastkit ([Installation](../start/installation.md)) and, for the commands on this page, [uv](https://docs.astral.sh/uv/). ## Create the project ![Terminal running fastkit init: the project name shop, the Levels table, the Project summary and the Next steps panel](../img/2.0/generate-init-dialogue.svg) @@ -56,7 +56,7 @@ Create the project? [Y/n]: ╰──────────────────────────────────────────────────────────────────────────────╯ ``` -The Author row comes from `git config` (here git had no name set). fastkit created a virtual environment in `shop/.venv` and installed the packages into it. The Next steps panel is your to-do list; the project's `README.md` repeats it. With `fastkit init --no-venv`, fastkit writes the files only, and `uv sync` in the project folder creates `.venv` afterwards, as after cloning the project from git. +The Author row comes from `git config` (here git had no name set). fastkit created a virtual environment in `shop/.venv` and installed the packages into it. The Next steps panel is your to-do list; the project's `README.md` lists the steps for a fresh checkout of the project. With `fastkit init --no-venv`, fastkit writes the files only, and `uv sync` in the project folder creates `.venv` afterwards, as after cloning the project from git. ## What fastkit created diff --git a/docs/en/reference/generated-projects.md b/docs/en/reference/generated-projects.md index fc603414..ee446e77 100644 --- a/docs/en/reference/generated-projects.md +++ b/docs/en/reference/generated-projects.md @@ -103,7 +103,7 @@ The `description` in `[project]` also starts with `[FastAPI-fastkit templated]`. ## Next steps in README.md -Each generated `README.md` holds the same Next steps list that `fastkit init` prints at the end, between two comment lines: +Each generated `README.md` holds the Next steps that `fastkit init` prints at the end, written for a fresh checkout of the project (no `cd`, a step that creates the environment, uvicorn to start the server), between two comment lines: ```markdown @@ -116,7 +116,7 @@ When you select features, the block also has a "Selected features" section with ## Concept comments -Generated code explains each FastAPI construct where it first appears, with a two-line comment: one sentence, then the address of the FastAPI documentation page about it. +In a project created from a level, the template's code and the code that features add explain each FastAPI construct where it first appears, with a two-line comment: one sentence, then the address of the FastAPI documentation page about it. The example templates have no such comments; the How-to page on example projects lists the concepts each one shows. ```python title="src/main.py" # `app` is the FastAPI application that uvicorn serves: `uvicorn src.main:app`. diff --git a/docs/es/contributing/template-creation-guide.md b/docs/es/contributing/template-creation-guide.md index aada527c..6bc3a84f 100644 --- a/docs/es/contributing/template-creation-guide.md +++ b/docs/es/contributing/template-creation-guide.md @@ -10,7 +10,7 @@ Los archivos que terminan en `-tpl` pierden el sufijo cuando fastkit copia la pl Una plantilla necesita como mínimo: -- `README.md-tpl`. +- `README.md-tpl` y un `main.py-tpl` que crea la aplicación `FastAPI`, en la raíz de la plantilla, en `src/` o en `src/app/`. - `pyproject.toml-tpl` con `fastapi` en `[project].dependencies`. - Una carpeta `tests/` con al menos un módulo `test_*.py-tpl`. @@ -123,7 +123,7 @@ app = FastAPI( | Archivos basura | Nada de `.DS_Store`, `__pycache__`, `.venv`, `.pyc` ni archivos parecidos. | | Dependencias | `fastapi` está declarado. | | Coherencia de la configuración | Las versiones fijadas de Python 3.12, ningún paquete de `[project].dependencies` que falte en `requirements.txt-tpl` y ninguna dependencia de `FastAPI-fastkit`. | -| Implementación de FastAPI | El proyecto generado crea una aplicación `FastAPI(...)`. | +| Implementación de FastAPI | El proyecto generado tiene un `main.py` en la raíz, en `src/` o en `src/app/`, y crea una aplicación `FastAPI(...)`. | | Sustitución de marcadores | No queda ningún `` en el proyecto generado. | | Compilación | Todos los archivos de Python compilan. | | Pruebas de la plantilla | Crea un entorno virtual, instala las dependencias y ejecuta `scripts/test.sh`, o `pytest tests/ -v` cuando no existe ese script. | diff --git a/docs/es/index.md b/docs/es/index.md index f7c5e583..8620b48c 100644 --- a/docs/es/index.md +++ b/docs/es/index.md @@ -16,19 +16,43 @@

-FastAPI-fastkit crea proyectos [FastAPI](https://github.com/fastapi/fastapi), desde un único `main.py` hasta una estructura de producción con base de datos, autenticación, pruebas y Docker. Después, el mismo comando `fastkit` ejecuta el proyecto, le añade rutas y lo revisa en busca de problemas conocidos. +FastAPI-fastkit crea proyectos [FastAPI](https://github.com/fastapi/fastapi) con código que funciona y con pruebas. Cinco niveles llevan desde un único `main.py` de tres endpoints hasta una estructura de producción con base de datos, autenticación, CI y Docker, y cada uno se basa en el anterior. El código de cada nivel se explica a sí mismo: para cada concepto, los comentarios enlazan a la página de la documentación de FastAPI que lo explica, y cada proyecto se entrega con una lista de próximos pasos. -## Empieza aquí +## Por dónde empezar {#where-to-start} -- **Instala fastkit**: sigue la página [Instalación](start/installation.md) y después ejecuta `fastkit init`. -- **Pruébalo sin instalar nada**: el [generador web](start/web-generator.md) crea un proyecto en tu navegador y te lo entrega como archivo zip. -- **Si FastAPI es nuevo para ti**: la sección «Aprender» empieza con [Genera tu primera aplicación FastAPI](learn/generate.md) y sigue un mismo proyecto desde un solo archivo hasta producción. +- **Pruébalo en tu navegador**: el [generador web](start/web-generator.md) crea un proyecto sin que tengas que instalar nada y te lo entrega como archivo zip. +- **Instala fastkit y crea un proyecto**: sigue la página [Instalación](start/installation.md) y después ejecuta `fastkit init`. +- **Aprende FastAPI paso a paso**: la sección «Aprender» empieza con [Genera tu primera aplicación FastAPI](learn/generate.md) y sigue un mismo proyecto hasta producción. +- **Consulta algo concreto**: cada página de las [guías prácticas](how-to/choose-a-level.md) resuelve una tarea, y la [referencia](reference/cli.md) describe cada comando, opción, nivel y funcionalidad. +- **Actualiza desde fastkit 1.x**: la página [Actualiza desde fastkit 1.x](how-to/upgrade-from-1x.md) indica qué debes cambiar en tus comandos y scripts. Los proyectos que ya tienes siguen funcionando. + +## En el navegador {#in-your-browser} + +El [generador web](start/web-generator.md) funciona como Spring Initializr: eliges un nivel, una base de datos y funcionalidades, ves cómo cambia la lista de archivos y descargas el proyecto como archivo zip. La página ejecuta en tu navegador el propio generador de fastkit mediante [Pyodide](https://pyodide.org/), así que nada de lo que escribes se envía a ninguna parte. El zip contiene los mismos archivos que el comando `fastkit init ... --no-venv` que la página muestra junto al formulario. ![La página del generador web con el nivel layered y SQLite seleccionados: el formulario, la lista de archivos, el comando fastkit init equivalente y el botón «Generate and download»](img/2.0/index-web-generator.png) -## Niveles +Tras la descarga, la página muestra los próximos pasos para este proyecto y lo que ha añadido cada funcionalidad seleccionada: sus archivos, sus valores de configuración y un enlace a la documentación. + +![El generador web después de la descarga: shop.zip descargado con 52 archivos, los pasos numerados de «Next steps» desde cd shop hasta fastkit init --level production y la sección «Selected features» con la base de datos SQLite](img/2.0/web-generator-result.png) + +## En la terminal {#in-your-terminal} + +`fastkit init` te pide un nombre de proyecto y un nivel, muestra un resumen, crea el proyecto e instala sus dependencias. Escribe un nombre de proyecto y pulsa Enter en todas las demás preguntas para quedarte con el nivel `hello`. La ejecución termina con el panel «Next steps», y el `README.md` del proyecto indica los pasos para una copia recién clonada. + +![Terminal que ejecuta fastkit init: el nombre de proyecto shop, la tabla «Levels», el resumen «Project summary» y el panel «Next steps»](img/2.0/generate-init-dialogue.svg) + +En scripts y en CI, indica cada elección con una opción y fastkit no pregunta nada: -`fastkit init` te pide un nivel. Cada nivel añade estructura al anterior, y `hello` es el nivel por defecto. +```console +$ fastkit init --project-name shop --level domain --database SQLite --feature authentication=JWT -y +``` + +Dentro del proyecto, `fastkit runserver` inicia la aplicación, `fastkit addroute` añade un recurso con sus rutas, esquemas, capa de datos y pruebas (en cualquier nivel salvo `hello`), y `fastkit doctor` revisa el proyecto en busca de problemas conocidos. fastkit necesita Python 3.12 o posterior y funciona con uv, pip, pdm y Poetry. + +## Niveles {#levels} + +Cada nivel añade estructura al anterior. fastkit no convierte un proyecto a otro nivel; la sección «Aprender» muestra cómo trasladar tu código al siguiente. En todos los niveles posteriores a `hello` puedes elegir una base de datos y funcionalidades como autenticación, tareas en segundo plano, caché, migraciones, herramientas de desarrollo y Docker: consulta [Personaliza las funcionalidades](how-to/customise-features.md). @@ -42,7 +66,18 @@ FastAPI-fastkit crea proyectos [FastAPI](https://github.com/fastapi/fastapi), de -## Proyectos de ejemplo +## Aprende FastAPI con un solo proyecto {#learn-fastapi} + +En todos los niveles, cada concepto de FastAPI se explica donde aparece por primera vez en el código generado, en un comentario breve que termina con el enlace a la página del tutorial oficial. La sección «Aprender» sigue un único proyecto, `shop`, desde el nivel `hello` hasta el nivel `production`: + +1. [Genera tu primera aplicación FastAPI](learn/generate.md) +2. [Entiende el código](learn/understand.md) +3. [Amplía la aplicación](learn/extend.md) +4. [Prueba la aplicación](learn/test.md) +5. [Pasa a una estructura por dominios y a una base de datos](learn/migrate.md) +6. [Despliega en producción](learn/deploy.md) + +## Proyectos de ejemplo {#example-projects} `fastkit init --template ` copia un proyecto de ejemplo completo en lugar de usar un nivel. [Empieza con un proyecto de ejemplo](how-to/example-projects.md) describe cada uno. @@ -58,11 +93,12 @@ FastAPI-fastkit crea proyectos [FastAPI](https://github.com/fastapi/fastapi), de -## Mapa de la documentación +## Mapa de la documentación {#documentation-map} - [Guías prácticas](how-to/choose-a-level.md): páginas orientadas a tareas, como elegir un nivel, personalizar las funcionalidades, usar `fastkit init` desde scripts, revisar un proyecto y actualizar desde fastkit 1.x. - [Referencia](reference/cli.md): todos los comandos y sus opciones, los niveles y las funcionalidades, y lo que contiene un proyecto generado. - [Contribuir](contributing/development-setup.md): configura el repositorio, escribe una plantilla y traduce la documentación. +- La documentación está disponible en English, 한국어, 日本語, 中文, Español, Français y Deutsch: usa el menú de idiomas de la parte superior de la página. ## Por qué FastAPI-fastkit diff --git a/docs/es/learn/generate.md b/docs/es/learn/generate.md index d6663c09..2b00c3a9 100644 --- a/docs/es/learn/generate.md +++ b/docs/es/learn/generate.md @@ -2,7 +2,7 @@ En esta página creas una pequeña aplicación FastAPI con `fastkit init`, la inicias con `fastkit runserver` y le envías requests. Por el camino conoces el objeto de la aplicación de FastAPI, las *path operations*, el servidor uvicorn y la documentación interactiva de la API que FastAPI genera por ti. -El nivel `hello` crea un proyecto llamado `shop` con un solo `main.py`, que contiene tres endpoints y guarda los ítems en memoria; el proyecto incluye además una prueba para cada endpoint. El resto de la sección «Aprender» amplía este proyecto, así que conserva el nombre `shop`. Necesitas fastkit ([Instalación](../start/installation.md)) y, para los comandos de esta página, [uv](https://docs.astral.sh/uv/). +El nivel `hello` crea un proyecto llamado `shop` con un solo `main.py`, que contiene tres endpoints y guarda los ítems en memoria; el proyecto incluye además una prueba para cada endpoint. El resto de la sección «Aprender» sigue este proyecto, así que conserva el nombre `shop`. Necesitas fastkit ([Instalación](../start/installation.md)) y, para los comandos de esta página, [uv](https://docs.astral.sh/uv/). ## Crea el proyecto ![Terminal que ejecuta fastkit init: el nombre de proyecto shop, la tabla «Levels», el resumen «Project summary» y el panel «Next steps»](../img/2.0/generate-init-dialogue.svg) @@ -56,7 +56,7 @@ Create the project? [Y/n]: ╰──────────────────────────────────────────────────────────────────────────────╯ ``` -La fila «Author» se toma de `git config` (en este ejemplo, git no tenía configurado ningún nombre de autor). fastkit creó un entorno virtual en `shop/.venv` e instaló en él los paquetes. El panel «Next steps» es tu lista de tareas, y el `README.md` del proyecto la repite. Con `fastkit init --no-venv`, fastkit solo escribe los archivos; después, `uv sync` en la carpeta del proyecto crea `.venv`, igual que cuando clonas el proyecto desde git. +La fila «Author» se toma de `git config` (en este ejemplo, git no tenía configurado ningún nombre de autor). fastkit creó un entorno virtual en `shop/.venv` e instaló en él los paquetes. El panel «Next steps» es tu lista de tareas, y el `README.md` indica los pasos para una copia recién clonada del proyecto. Con `fastkit init --no-venv`, fastkit solo escribe los archivos; después, `uv sync` en la carpeta del proyecto crea `.venv`, igual que cuando clonas el proyecto desde git. ## Qué ha creado fastkit diff --git a/docs/es/reference/generated-projects.md b/docs/es/reference/generated-projects.md index 846706d1..2ba997b7 100644 --- a/docs/es/reference/generated-projects.md +++ b/docs/es/reference/generated-projects.md @@ -103,7 +103,7 @@ Además, la `description` de `[project]` empieza por `[FastAPI-fastkit templated ## Próximos pasos en README.md -Cada `README.md` generado contiene, entre dos líneas de comentario, la misma lista de próximos pasos (Next steps) que `fastkit init` imprime al final: +Cada `README.md` generado contiene, entre dos líneas de comentario, los próximos pasos (Next steps) que `fastkit init` imprime al final, redactados para una copia recién clonada del proyecto (sin `cd`, con un paso que crea el entorno y con uvicorn para iniciar el servidor): ```markdown @@ -116,7 +116,7 @@ Cuando seleccionas funcionalidades, el bloque también incluye una sección «Se ## Comentarios de conceptos -El código generado explica cada elemento de FastAPI en el lugar donde aparece por primera vez, con un comentario de dos líneas: una frase y, después, la dirección de la página de la documentación de FastAPI que trata sobre ese elemento. +En un proyecto creado a partir de un nivel, el código de la plantilla y el código que añaden las funcionalidades explican cada elemento de FastAPI en el lugar donde aparece por primera vez, con un comentario de dos líneas: una frase y, después, la dirección de la página de la documentación de FastAPI que trata sobre ese elemento. Las plantillas de ejemplo no tienen estos comentarios; la guía práctica sobre los proyectos de ejemplo enumera los conceptos que muestra cada una. ```python title="src/main.py" # `app` is the FastAPI application that uvicorn serves: `uvicorn src.main:app`. diff --git a/docs/fr/contributing/template-creation-guide.md b/docs/fr/contributing/template-creation-guide.md index 4b4c2032..292f4f67 100644 --- a/docs/fr/contributing/template-creation-guide.md +++ b/docs/fr/contributing/template-creation-guide.md @@ -10,7 +10,7 @@ Les fichiers qui se terminent par `-tpl` perdent ce suffixe quand fastkit copie Un template doit contenir au minimum : -- `README.md-tpl`. +- `README.md-tpl` et un `main.py-tpl` qui crée l'application `FastAPI`, à la racine du template, dans `src/` ou dans `src/app/`. - `pyproject.toml-tpl` avec `fastapi` dans `[project].dependencies`. - Un dossier `tests/` avec au moins un module `test_*.py-tpl`. @@ -123,7 +123,7 @@ app = FastAPI( | Junk files | Aucun `.DS_Store`, `__pycache__`, `.venv`, `.pyc` ni fichier semblable. | | Dependencies | `fastapi` est déclaré. | | Configuration consistency | Les versions fixées à Python 3.12, aucun paquet de `[project].dependencies` absent de `requirements.txt-tpl`, aucune dépendance à `FastAPI-fastkit`. | -| FastAPI implementation | Le projet généré crée une application `FastAPI(...)`. | +| FastAPI implementation | Le projet généré a un `main.py` à la racine, dans `src/` ou dans `src/app/`, et ce fichier crée une application `FastAPI(...)`. | | Placeholder substitution | Il ne reste aucun `` dans le projet généré. | | Compile check | Chaque fichier Python se compile. | | Template tests | Crée un environnement virtuel, installe les dépendances et lance `scripts/test.sh`, ou `pytest tests/ -v` si ce script n'existe pas. | diff --git a/docs/fr/index.md b/docs/fr/index.md index 1970c5f3..51e6b50a 100644 --- a/docs/fr/index.md +++ b/docs/fr/index.md @@ -16,19 +16,43 @@

-FastAPI-fastkit crée des projets [FastAPI](https://github.com/fastapi/fastapi), d'un simple `main.py` jusqu'à une structure de production avec base de données, authentification, tests et Docker. La même commande `fastkit` permet ensuite de lancer le projet, d'y ajouter des routes et d'y rechercher des problèmes connus. +FastAPI-fastkit crée des projets [FastAPI](https://github.com/fastapi/fastapi) avec du code fonctionnel et des tests. Cinq niveaux mènent d'un simple `main.py` de trois endpoints à une structure de production avec base de données, authentification, CI et Docker, chacun s'appuyant sur le précédent. Le code de chaque niveau s'explique de lui-même : pour chaque concept, des commentaires renvoient vers la page de la documentation FastAPI qui l'explique, et chaque projet se termine par une liste des étapes suivantes. -## Par où commencer +## Par où commencer {#where-to-start} -- **Installer fastkit** : suivez la page [Installation](start/installation.md), puis lancez `fastkit init`. -- **Essayer sans rien installer** : le [générateur web](start/web-generator.md) crée un projet dans votre navigateur et vous le fournit sous forme de fichier zip. -- **Vous découvrez FastAPI** : le parcours « Apprendre » commence par [Générer votre première application FastAPI](learn/generate.md) et suit un même projet, d'un fichier unique jusqu'à la production. +- **Essayer dans votre navigateur** : le [générateur web](start/web-generator.md) crée un projet sans rien installer et vous le fournit sous forme de fichier zip. +- **Installer fastkit et créer un projet** : suivez la page [Installation](start/installation.md), puis lancez `fastkit init`. +- **Apprendre FastAPI pas à pas** : le parcours « Apprendre » commence par [Générer votre première application FastAPI](learn/generate.md) et suit un même projet jusqu'à la production. +- **Chercher une information** : les [Guides pratiques](how-to/choose-a-level.md) traitent chacun une seule tâche, et la [Référence](reference/cli.md) décrit chaque commande, option, niveau et fonctionnalité. +- **Mettre à niveau depuis fastkit 1.x** : la page [Mettre à niveau depuis fastkit 1.x](how-to/upgrade-from-1x.md) liste ce qu'il faut modifier dans vos commandes et vos scripts. Les projets que vous avez déjà continuent de fonctionner. + +## Dans votre navigateur {#in-your-browser} + +Le [générateur web](start/web-generator.md) fonctionne comme Spring Initializr : choisissez un niveau, une base de données et des fonctionnalités, regardez la liste des fichiers évoluer, puis téléchargez le projet sous forme de fichier zip. Il exécute le générateur de fastkit lui-même dans votre navigateur grâce à [Pyodide](https://pyodide.org/), si bien que rien de ce que vous saisissez n'est envoyé nulle part. Le zip contient les mêmes fichiers que la commande `fastkit init ... --no-venv` que la page affiche à côté du formulaire. ![La page du générateur web avec le niveau layered et SQLite sélectionnés : le formulaire, la liste des fichiers, la commande fastkit init correspondante et le bouton « Generate and download »](img/2.0/index-web-generator.png) -## Niveaux +Après le téléchargement, la page affiche les étapes suivantes propres à ce projet et, pour chaque fonctionnalité sélectionnée, ce qu'elle a ajouté : ses fichiers, ses paramètres et un lien vers la documentation. + +![Le générateur web après le téléchargement : shop.zip téléchargé avec 52 fichiers, la liste numérotée « Next steps » de cd shop à fastkit init --level production, et la section « Selected features » consacrée à la base de données SQLite](img/2.0/web-generator-result.png) + +## Dans votre terminal {#in-your-terminal} + +`fastkit init` demande un nom de projet et un niveau, affiche un récapitulatif, crée le projet et installe ses dépendances. Saisissez un nom de projet et appuyez sur Entrée à chacune des autres questions pour obtenir le niveau `hello`. L'exécution se termine par le panneau « Next steps », et le fichier `README.md` du projet liste les étapes à suivre après avoir cloné le projet. + +![Terminal exécutant fastkit init : le nom de projet shop, le tableau « Levels », le récapitulatif « Project summary » et le panneau « Next steps »](img/2.0/generate-init-dialogue.svg) + +Dans les scripts et la CI, passez chaque choix sous forme d'option, et aucune question n'est posée : -`fastkit init` vous demande de choisir un niveau. Chaque niveau ajoute de la structure au précédent, et `hello` est le niveau par défaut. +```console +$ fastkit init --project-name shop --level domain --database SQLite --feature authentication=JWT -y +``` + +Dans le projet, `fastkit runserver` démarre l'application, `fastkit addroute` ajoute une ressource avec ses routes, ses schémas, sa couche de données et ses tests (à tous les niveaux sauf `hello`), et `fastkit doctor` recherche les problèmes connus dans le projet. fastkit nécessite Python 3.12 ou une version plus récente et fonctionne avec uv, pip, pdm et Poetry. + +## Niveaux {#levels} + +Chaque niveau ajoute de la structure au précédent. fastkit ne convertit pas un projet vers un autre niveau ; le parcours « Apprendre » montre comment faire passer votre code au niveau suivant. À chaque niveau après `hello`, vous pouvez choisir une base de données et des fonctionnalités comme l'authentification, les tâches d'arrière-plan, la mise en cache, les migrations, les outils de développement et Docker : consultez [Personnaliser les fonctionnalités](how-to/customise-features.md). @@ -42,7 +66,18 @@ FastAPI-fastkit crée des projets [FastAPI](https://github.com/fastapi/fastapi), -## Projets d'exemple +## Apprendre FastAPI avec un seul projet {#learn-fastapi} + +À tous les niveaux, chaque concept FastAPI est expliqué là où il apparaît pour la première fois dans le code généré, dans un court commentaire qui se termine par le lien vers la page du tutoriel officiel. Le parcours « Apprendre » suit un seul projet, `shop`, du niveau `hello` jusqu'au niveau `production` : + +1. [Générer votre première application FastAPI](learn/generate.md) +2. [Comprendre le code](learn/understand.md) +3. [Étendre l'application](learn/extend.md) +4. [Tester l'application](learn/test.md) +5. [Passer à une structure par domaines et à une base de données](learn/migrate.md) +6. [Déployer en production](learn/deploy.md) + +## Projets d'exemple {#example-projects} `fastkit init --template ` copie un projet d'exemple complet au lieu de partir d'un niveau. La page [Partir d'un projet d'exemple](how-to/example-projects.md) décrit chacun d'eux. @@ -58,11 +93,12 @@ FastAPI-fastkit crée des projets [FastAPI](https://github.com/fastapi/fastapi), -## Plan de la documentation +## Plan de la documentation {#documentation-map} - [Guides pratiques](how-to/choose-a-level.md) : des pages consacrées chacune à une tâche, comme choisir un niveau, personnaliser les fonctionnalités, lancer `fastkit init` depuis un script, vérifier un projet ou mettre à niveau depuis fastkit 1.x. - [Référence](reference/cli.md) : toutes les commandes et options, les niveaux et les fonctionnalités, et le contenu d'un projet généré. - [Contribuer](contributing/development-setup.md) : préparer le dépôt, écrire un template et traduire la documentation. +- La documentation est disponible en English, 한국어, 日本語, 中文, Español, Français et Deutsch : choisissez votre langue dans le menu en haut de la page. ## Pourquoi FastAPI-fastkit diff --git a/docs/fr/learn/generate.md b/docs/fr/learn/generate.md index 61525a38..b1738f56 100644 --- a/docs/fr/learn/generate.md +++ b/docs/fr/learn/generate.md @@ -2,7 +2,7 @@ Sur cette page, vous créez une petite application FastAPI avec `fastkit init`, vous la démarrez avec `fastkit runserver` et vous lui envoyez des requêtes. Vous découvrez au passage l'objet application de FastAPI, les chemins d'accès, le serveur uvicorn et la documentation interactive de l'API que FastAPI construit pour vous. -Le niveau `hello` crée un projet nommé `shop` avec un seul fichier `main.py`, qui contient trois endpoints et garde les articles en mémoire ; le projet fournit aussi un test pour chaque endpoint. La suite du parcours « Apprendre » fait grandir ce projet : gardez donc le nom `shop`. Il vous faut fastkit ([Installation](../start/installation.md)) et, pour les commandes de cette page, [uv](https://docs.astral.sh/uv/). +Le niveau `hello` crée un projet nommé `shop` avec un seul fichier `main.py`, qui contient trois endpoints et garde les articles en mémoire ; le projet fournit aussi un test pour chaque endpoint. La suite du parcours « Apprendre » reprend ce projet : gardez donc le nom `shop`. Il vous faut fastkit ([Installation](../start/installation.md)) et, pour les commandes de cette page, [uv](https://docs.astral.sh/uv/). ## Créer le projet ![Terminal exécutant fastkit init : le nom de projet shop, le tableau « Levels », le récapitulatif « Project summary » et le panneau « Next steps »](../img/2.0/generate-init-dialogue.svg) @@ -56,7 +56,7 @@ Create the project? [Y/n]: ╰──────────────────────────────────────────────────────────────────────────────╯ ``` -La ligne « Author » vient de `git config` (ici, aucun nom d'auteur n'était défini dans git). fastkit a créé un environnement virtuel dans `shop/.venv` et y a installé les paquets. Le panneau « Next steps » est votre liste de tâches ; le fichier `README.md` du projet la reprend. Avec `fastkit init --no-venv`, fastkit écrit seulement les fichiers, et `uv sync` lancé dans le dossier du projet crée `.venv` ensuite, comme après avoir cloné le projet depuis git. +La ligne « Author » vient de `git config` (ici, aucun nom d'auteur n'était défini dans git). fastkit a créé un environnement virtuel dans `shop/.venv` et y a installé les paquets. Le panneau « Next steps » est votre liste de tâches ; le fichier `README.md` du projet liste les étapes à suivre après avoir cloné le projet. Avec `fastkit init --no-venv`, fastkit écrit seulement les fichiers, et `uv sync` lancé dans le dossier du projet crée `.venv` ensuite, comme après avoir cloné le projet depuis git. ## Ce que fastkit a créé diff --git a/docs/fr/reference/generated-projects.md b/docs/fr/reference/generated-projects.md index 6fb8acec..67f9856d 100644 --- a/docs/fr/reference/generated-projects.md +++ b/docs/fr/reference/generated-projects.md @@ -103,7 +103,7 @@ La `description` de la section `[project]` commence elle aussi par `[FastAPI-fas ## La liste « Next steps » dans README.md -Chaque `README.md` généré contient, entre deux lignes de commentaire, la même liste « Next steps » que celle que `fastkit init` affiche à la fin : +Chaque `README.md` généré contient, entre deux lignes de commentaire, les étapes « Next steps » que `fastkit init` affiche à la fin, rédigées pour un projet que l'on vient de cloner (pas de `cd`, une étape qui crée l'environnement, uvicorn pour démarrer le serveur) : ```markdown @@ -116,7 +116,7 @@ Lorsque vous sélectionnez des fonctionnalités, le bloc contient aussi une sect ## Commentaires de concept -Le code généré explique chaque construction FastAPI à l'endroit où elle apparaît pour la première fois, avec un commentaire de deux lignes : une phrase, puis l'adresse de la page de la documentation FastAPI qui la traite. +Dans un projet créé à partir d'un niveau, le code du template et le code qu'ajoutent les fonctionnalités expliquent chaque construction FastAPI à l'endroit où elle apparaît pour la première fois, avec un commentaire de deux lignes : une phrase, puis l'adresse de la page de la documentation FastAPI qui la traite. Les templates d'exemple ne contiennent pas ces commentaires ; le guide pratique consacré aux projets d'exemple liste les concepts que chacun d'eux illustre. ```python title="src/main.py" # `app` is the FastAPI application that uvicorn serves: `uvicorn src.main:app`. diff --git a/docs/img/2.0/web-generator-customise.png b/docs/img/2.0/web-generator-customise.png new file mode 100644 index 00000000..30ebb893 Binary files /dev/null and b/docs/img/2.0/web-generator-customise.png differ diff --git a/docs/img/2.0/web-generator-result.png b/docs/img/2.0/web-generator-result.png new file mode 100644 index 00000000..73a5ddfb Binary files /dev/null and b/docs/img/2.0/web-generator-result.png differ diff --git a/docs/ja/contributing/template-creation-guide.md b/docs/ja/contributing/template-creation-guide.md index 373000b7..c9e504af 100644 --- a/docs/ja/contributing/template-creation-guide.md +++ b/docs/ja/contributing/template-creation-guide.md @@ -10,7 +10,7 @@ テンプレートには、少なくとも次のものが必要です。 -- `README.md-tpl`。 +- `README.md-tpl` と、`FastAPI` アプリケーションを作成する `main.py-tpl`(テンプレートのルート、`src/`、`src/app/` のいずれかに置きます)。 - `[project].dependencies` に `fastapi` を含む `pyproject.toml-tpl`。 - `test_*.py-tpl` のモジュールを 1 つ以上含む `tests/` フォルダー。 @@ -123,7 +123,7 @@ app = FastAPI( | Junk files | `.DS_Store`、`__pycache__`、`.venv`、`.pyc` などの不要なファイルがないこと。 | | Dependencies | `fastapi` が宣言されていること。 | | Configuration consistency | Python 3.12 への固定があること、`[project].dependencies` のパッケージが `requirements.txt-tpl` に欠けていないこと、`FastAPI-fastkit` への依存がないこと。 | -| FastAPI implementation | 生成されたプロジェクトが `FastAPI(...)` アプリケーションを作成すること。 | +| FastAPI implementation | 生成されたプロジェクトのルート、`src/`、`src/app/` のいずれかに `main.py` があり、それが `FastAPI(...)` アプリケーションを作成すること。 | | Placeholder substitution | 生成されたプロジェクトに `` が残っていないこと。 | | Compile check | すべての Python ファイルがコンパイルできること。 | | Template tests | 仮想環境を作成し、依存関係をインストールして `scripts/test.sh` を実行します。このスクリプトがない場合は `pytest tests/ -v` を実行します。 | diff --git a/docs/ja/index.md b/docs/ja/index.md index b84241a0..21cdcc08 100644 --- a/docs/ja/index.md +++ b/docs/ja/index.md @@ -16,19 +16,43 @@

-FastAPI-fastkit は、`main.py` 1 ファイルだけのプロジェクトから、データベース、認証、テスト、Docker を備えた本番向けの構成まで、[FastAPI](https://github.com/fastapi/fastapi) のプロジェクトを作成します。作成したプロジェクトは、同じ `fastkit` コマンドで実行し、ルートを追加し、既知の問題がないか検査できます。 +FastAPI-fastkit は、動作するコードとテストを備えた [FastAPI](https://github.com/fastapi/fastapi) のプロジェクトを作成します。レベルは 5 つあり、エンドポイント 3 つだけの `main.py` 1 ファイルから、データベース、認証、CI、Docker を備えた本番向けの構成までをつないでいます。各レベルは 1 つ前のレベルを土台にしています。どのレベルのコードも、読めば内容が分かるように作られています。コメントには各概念を説明する FastAPI のドキュメントのページへのリンクがあり、どのプロジェクトにも最後に次のステップの一覧が付いています。 -## ここから始める +## どこから始めるか {#where-to-start} -- **fastkit をインストールする**: [インストール](start/installation.md)の手順に従ってインストールし、`fastkit init` を実行してください。 -- **インストールせずに試す**: [Web ジェネレーター](start/web-generator.md)を使うと、ブラウザー上でプロジェクトを作成し、zip ファイルとして受け取れます。 -- **FastAPI を初めて使う方**: 「学ぶ」コースは[最初の FastAPI アプリを生成する](learn/generate.md)から始まり、1 つのプロジェクトが単一ファイルから本番環境に至るまでを順に追っていきます。 +- **ブラウザーで試す**: [Web ジェネレーター](start/web-generator.md)を使うと、何もインストールせずにプロジェクトを作成し、zip ファイルとして受け取れます。 +- **fastkit をインストールしてプロジェクトを作成する**: [インストール](start/installation.md)の手順に従ってインストールし、`fastkit init` を実行してください。 +- **FastAPI を段階的に学ぶ**: 「学ぶ」コースは[最初の FastAPI アプリを生成する](learn/generate.md)から始まり、1 つのプロジェクトが本番環境に至るまでを順に追っていきます。 +- **調べものをする**: [ハウツーガイド](how-to/choose-a-level.md)の各ページはそれぞれ 1 つの作業を扱い、[リファレンス](reference/cli.md)はすべてのコマンド、オプション、レベル、機能を説明しています。 +- **fastkit 1.x からアップグレードする**: [fastkit 1.x からアップグレードする](how-to/upgrade-from-1x.md)のページに、コマンドとスクリプトで変更が必要な点をまとめています。既存のプロジェクトは引き続きそのまま動作します。 + +## ブラウザーで使う {#in-your-browser} + +[Web ジェネレーター](start/web-generator.md)は Spring Initializr と同じように使えます。レベル、データベース、機能を選び、選択に応じてファイル一覧が変わるのを確かめてから、プロジェクトを zip ファイルとしてダウンロードします。このページは fastkit のジェネレーターそのものを [Pyodide](https://pyodide.org/) でブラウザー上で実行するため、入力した内容がどこかに送信されることはありません。zip には、ページのフォームの横に表示される `fastkit init ... --no-venv` コマンドを実行した場合と同じファイルが入っています。 ![layered レベルと SQLite を選んだ Web ジェネレーターのページ。フォーム、ファイル一覧、選択内容に対応する fastkit init コマンド、"Generate and download" ボタンが表示されています](img/2.0/index-web-generator.png) -## レベル +ダウンロードが終わると、ページにはこのプロジェクトの次のステップが表示されます。あわせて、選択した機能ごとに、その機能が追加したファイルと設定、ドキュメントへのリンクも表示されます。 + +![ダウンロード後の Web ジェネレーター。52 ファイルを含む shop.zip をダウンロードしたことを示す表示、cd shop から fastkit init --level production までの番号付きの Next steps、SQLite データベースについての Selected features セクションが表示されています](img/2.0/web-generator-result.png) + +## ターミナルで使う {#in-your-terminal} + +`fastkit init` はプロジェクト名とレベルを尋ね、概要を表示してからプロジェクトを作成し、依存関係をインストールします。プロジェクト名を入力し、それ以外のすべての質問で Enter キーを押すと、`hello` レベルのプロジェクトができます。実行の最後には Next steps パネルが表示され、プロジェクトの `README.md` には、クローンしたばかりのプロジェクトで実行する手順が書かれています。 + +![fastkit init を実行したターミナル。プロジェクト名 shop、Levels の表、Project summary、Next steps パネルが表示されています](img/2.0/generate-init-dialogue.svg) + +スクリプトや CI では、すべての選択をオプションとして渡してください。そうすると質問は一切表示されません。 -`fastkit init` は最初にレベルを尋ねます。各レベルは 1 つ前のレベルに構造を加えたもので、既定のレベルは `hello` です。 +```console +$ fastkit init --project-name shop --level domain --database SQLite --feature authentication=JWT -y +``` + +作成したプロジェクトの中では、`fastkit runserver` でアプリを起動し、`fastkit addroute` でリソースをそのルート、スキーマ、データ層、テストとともに追加し(`hello` 以外のどのレベルでも使えます)、`fastkit doctor` でプロジェクトに既知の問題がないかを検査できます。fastkit には Python 3.12 以降が必要で、uv、pip、pdm、Poetry のどれでも使えます。 + +## レベル {#levels} + +各レベルは 1 つ前のレベルに構造を加えたものです。fastkit はプロジェクトを別のレベルに変換しません。コードを次のレベルの構成に移す方法は、「学ぶ」コースで説明しています。`hello` 以外のすべてのレベルでは、データベースと、認証、バックグラウンドタスク、キャッシュ、マイグレーション、開発ツール、Docker などの機能を選べます。詳しくは[機能をカスタマイズする](how-to/customise-features.md)を参照してください。 @@ -42,7 +66,18 @@ FastAPI-fastkit は、`main.py` 1 ファイルだけのプロジェクトから -## サンプルプロジェクト +## 1 つのプロジェクトで FastAPI を学ぶ {#learn-fastapi} + +どのレベルでも、FastAPI の各概念は、生成されたコードの中でその概念が最初に登場する箇所で、短いコメントによって説明されます。コメントの最後には、公式チュートリアルの該当ページへのリンクがあります。「学ぶ」コースでは、`shop` という 1 つのプロジェクトを `hello` レベルから `production` まで追っていきます。 + +1. [最初の FastAPI アプリを生成する](learn/generate.md) +2. [コードを理解する](learn/understand.md) +3. [アプリを拡張する](learn/extend.md) +4. [アプリをテストする](learn/test.md) +5. [ドメイン構成とデータベースへ移行する](learn/migrate.md) +6. [本番環境にデプロイする](learn/deploy.md) + +## サンプルプロジェクト {#example-projects} `fastkit init --template ` は、レベルの代わりに完成したサンプルプロジェクトをコピーします。各サンプルの説明は[サンプルプロジェクトから始める](how-to/example-projects.md)にあります。 @@ -58,11 +93,12 @@ FastAPI-fastkit は、`main.py` 1 ファイルだけのプロジェクトから -## ドキュメントの構成 +## ドキュメントの構成 {#documentation-map} - [ハウツーガイド](how-to/choose-a-level.md): レベルの選び方、機能のカスタマイズ、スクリプトからの `fastkit init` の実行、プロジェクトの検査、fastkit 1.x からのアップグレードなど、作業ごとのページがあります。 - [リファレンス](reference/cli.md): すべてのコマンドとオプション、レベルと機能、生成されたプロジェクトの中身を説明しています。 - [コントリビューション](contributing/development-setup.md): リポジトリのセットアップ、テンプレートの作成、ドキュメントの翻訳の方法を案内しています。 +- このドキュメントは English、한국어、日本語、中文、Español、Français、Deutsch で読めます。言語はページ上部の言語メニューで切り替えてください。 ## FastAPI-fastkit が目指すもの diff --git a/docs/ja/learn/generate.md b/docs/ja/learn/generate.md index 8ea4dc39..0b1bef10 100644 --- a/docs/ja/learn/generate.md +++ b/docs/ja/learn/generate.md @@ -2,7 +2,7 @@ このページでは、`fastkit init` で小さな FastAPI アプリケーションを作成し、`fastkit runserver` で起動して、リクエストを送ってみます。その過程で、FastAPI のアプリケーションオブジェクト、*パスオペレーション*、uvicorn サーバー、そして FastAPI が自動で用意する対話的な API ドキュメントに触れます。 -`hello` レベルは、`main.py` 1 ファイルで構成される `shop` というプロジェクトを作成します。このプロジェクトには、エンドポイント 3 つ、メモリ上に保持するアイテム、エンドポイントごとのテストが含まれます。「学ぶ」コースの残りのページではこのプロジェクトを育てていくので、名前は `shop` のままにしてください。fastkit([インストール](../start/installation.md))が必要です。また、このページのコマンドを実行するには [uv](https://docs.astral.sh/uv/) も必要です。 +`hello` レベルは、`main.py` 1 ファイルで構成される `shop` というプロジェクトを作成します。このプロジェクトには、エンドポイント 3 つ、メモリ上に保持するアイテム、エンドポイントごとのテストが含まれます。「学ぶ」コースの残りのページでもこのプロジェクトを使い続けるので、名前は `shop` のままにしてください。fastkit([インストール](../start/installation.md))が必要です。また、このページのコマンドを実行するには [uv](https://docs.astral.sh/uv/) も必要です。 ## プロジェクトを作成する ![fastkit init を実行したターミナル。プロジェクト名 shop、Levels の表、Project summary、Next steps パネルが表示されています](../img/2.0/generate-init-dialogue.svg) @@ -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/ja/reference/generated-projects.md b/docs/ja/reference/generated-projects.md index 725b5af9..9548cc25 100644 --- a/docs/ja/reference/generated-projects.md +++ b/docs/ja/reference/generated-projects.md @@ -103,7 +103,7 @@ features = ["database:PostgreSQL", "authentication:JWT", "testing:Coverage", "mi ## README.md の次のステップ -生成される各 `README.md` には、`fastkit init` が最後に表示するものと同じ Next steps(次のステップ)の一覧が、2 つのコメント行に挟まれて入っています。 +生成される各 `README.md` には、`fastkit init` が最後に表示する Next steps(次のステップ)が、クローンしたばかりのプロジェクト向けに書き直された形(`cd` がなく、環境を作成する手順があり、サーバーの起動には uvicorn を使います)で、2 つのコメント行に挟まれて入っています。 ```markdown @@ -116,7 +116,7 @@ features = ["database:PostgreSQL", "authentication:JWT", "testing:Coverage", "mi ## 概念コメント -生成されるコードでは、FastAPI の各構成要素を、それが最初に登場する場所で 2 行のコメントで説明しています。1 行目は 1 文の説明で、2 行目はその要素を解説している FastAPI ドキュメントのページのアドレスです。 +レベルから作成したプロジェクトでは、テンプレートのコードと、機能が追加するコードが、FastAPI の各構成要素をそれが最初に登場する場所で 2 行のコメントで説明しています。1 行目は 1 文の説明で、2 行目はその要素を解説している FastAPI ドキュメントのページのアドレスです。サンプルのテンプレートにはこのようなコメントはありません。各サンプルが扱っている概念は、サンプルプロジェクトについてのハウツーガイドのページに一覧があります。 ```python title="src/main.py" # `app` is the FastAPI application that uvicorn serves: `uvicorn src.main:app`. diff --git a/docs/ko/contributing/template-creation-guide.md b/docs/ko/contributing/template-creation-guide.md index bfc9dfa4..3bbe60fd 100644 --- a/docs/ko/contributing/template-creation-guide.md +++ b/docs/ko/contributing/template-creation-guide.md @@ -10,7 +10,7 @@ 템플릿에는 최소한 다음 파일이 있어야 합니다. -- `README.md-tpl`이 있어야 합니다. +- `README.md-tpl`과, 템플릿 루트나 `src/` 또는 `src/app/`에 있으면서 `FastAPI` 애플리케이션을 만드는 `main.py-tpl`이 있어야 합니다. - `[project].dependencies`에 `fastapi`가 들어 있는 `pyproject.toml-tpl`이 있어야 합니다. - `test_*.py-tpl` 모듈이 하나 이상 들어 있는 `tests/` 폴더가 있어야 합니다. @@ -123,7 +123,7 @@ app = FastAPI( | Junk files | `.DS_Store`, `__pycache__`, `.venv`, `.pyc` 같은 불필요한 파일이 없는지 확인합니다. | | Dependencies | `fastapi`가 의존성으로 선언되어 있는지 확인합니다. | | Configuration consistency | Python 3.12 고정 설정이 있는지, `[project].dependencies`의 패키지가 `requirements.txt-tpl`에 빠짐없이 있는지, `FastAPI-fastkit` 의존성이 없는지 확인합니다. | -| FastAPI implementation | 생성된 프로젝트가 `FastAPI(...)` 애플리케이션을 만드는지 확인합니다. | +| FastAPI implementation | 생성된 프로젝트의 루트나 `src/` 또는 `src/app/`에 `main.py`가 있는지, 그리고 프로젝트가 `FastAPI(...)` 애플리케이션을 만드는지 확인합니다. | | Placeholder substitution | 생성된 프로젝트에 ``가 남아 있지 않은지 확인합니다. | | Compile check | 모든 Python 파일이 컴파일되는지 확인합니다. | | Template tests | 가상 환경을 만들고 의존성을 설치한 다음 `scripts/test.sh`를 실행합니다. 이 스크립트가 없으면 `pytest tests/ -v`를 실행합니다. | diff --git a/docs/ko/index.md b/docs/ko/index.md index b49edc4c..04cae2ce 100644 --- a/docs/ko/index.md +++ b/docs/ko/index.md @@ -16,19 +16,43 @@

-FastAPI-fastkit은 `main.py` 파일 하나로 된 프로젝트부터 데이터베이스, 인증, 테스트, Docker를 갖춘 프로덕션 구조의 프로젝트까지 [FastAPI](https://github.com/fastapi/fastapi) 프로젝트를 생성합니다. 프로젝트를 만든 뒤에는 같은 `fastkit` 명령으로 프로젝트를 실행하고, 라우트를 추가하고, 알려진 문제가 있는지 검사할 수 있습니다. +FastAPI-fastkit은 동작하는 코드와 테스트를 갖춘 [FastAPI](https://github.com/fastapi/fastapi) 프로젝트를 생성합니다. 다섯 가지 레벨이 엔드포인트 3개로 된 `main.py` 파일 하나부터 데이터베이스, 인증, CI, Docker를 갖춘 프로덕션 구조까지 이어지며, 각 레벨은 바로 앞 레벨을 바탕으로 만들어집니다. 모든 레벨의 코드에는 코드를 이해하는 데 필요한 설명이 함께 들어 있습니다. 주석마다 해당 개념을 설명하는 FastAPI 문서 페이지의 링크가 있고, 어떤 프로젝트를 만들든 마지막에는 다음 단계를 정리한 목록이 제공됩니다. -## 여기서 시작하세요 +## 어디서 시작할까요 {#where-to-start} -- **fastkit 설치하기**: [설치](start/installation.md) 페이지를 따라 설치한 다음 `fastkit init`을 실행하세요. -- **설치하지 않고 사용해 보기**: [웹 생성기](start/web-generator.md)는 브라우저 안에서 프로젝트를 만들고 zip 파일로 내려받게 해 줍니다. -- **FastAPI가 처음이라면**: 배우기 과정은 [첫 FastAPI 앱 생성하기](learn/generate.md)에서 시작하며, 프로젝트 하나를 파일 하나짜리 상태에서 프로덕션 단계까지 따라가며 설명합니다. +- **브라우저에서 사용해 보기**: [웹 생성기](start/web-generator.md)는 아무것도 설치하지 않은 상태에서 프로젝트를 만들어 zip 파일로 내려받게 해 줍니다. +- **fastkit을 설치하고 프로젝트 만들기**: [설치](start/installation.md) 페이지를 따라 설치한 다음 `fastkit init`을 실행하세요. +- **FastAPI를 단계별로 배우기**: 배우기 과정은 [첫 FastAPI 앱 생성하기](learn/generate.md)에서 시작하며, 프로젝트 하나가 프로덕션에 이르기까지의 과정을 따라가며 설명합니다. +- **필요한 내용 찾아보기**: [실전 가이드](how-to/choose-a-level.md)의 각 페이지는 작업 하나를 해결하는 방법을 다루고, [레퍼런스](reference/cli.md)는 모든 명령, 옵션, 레벨, 기능을 설명합니다. +- **fastkit 1.x에서 업그레이드하기**: [fastkit 1.x에서 업그레이드하기](how-to/upgrade-from-1x.md) 페이지에는 명령과 스크립트에서 바꿔야 할 내용이 정리되어 있습니다. 이미 만든 프로젝트는 그대로 계속 동작합니다. + +## 브라우저에서 {#in-your-browser} + +[웹 생성기](start/web-generator.md)는 Spring Initializr처럼 동작합니다. 레벨, 데이터베이스, 기능을 고르면 파일 목록이 바뀌는 모습을 바로 확인할 수 있고, 완성된 프로젝트를 zip 파일로 내려받을 수 있습니다. 웹 생성기는 [Pyodide](https://pyodide.org/)를 이용해 fastkit 생성기 자체를 브라우저 안에서 실행하므로, 입력한 내용은 어디에도 전송되지 않습니다. zip 파일에는 페이지가 입력 양식 옆에 보여 주는 `fastkit init ... --no-venv` 명령을 실행했을 때와 같은 파일이 들어 있습니다. ![layered 레벨과 SQLite를 선택한 웹 생성기 페이지: 입력 양식, 파일 목록, 선택에 맞는 fastkit init 명령, Generate and download 버튼이 보입니다](img/2.0/index-web-generator.png) -## 레벨 +내려받기가 끝나면 페이지에 이 프로젝트에서 이어서 할 다음 단계가 표시되고, 선택한 기능마다 그 기능이 추가한 파일과 설정, 관련 문서의 링크가 표시됩니다. + +![내려받기를 마친 뒤의 웹 생성기: 파일 52개가 담긴 shop.zip을 내려받았다는 안내, cd shop부터 fastkit init --level production까지 번호를 매긴 Next steps, SQLite 데이터베이스에 대한 Selected features 섹션이 보입니다](img/2.0/web-generator-result.png) + +## 터미널에서 {#in-your-terminal} + +`fastkit init`은 프로젝트 이름과 레벨을 묻고, 요약을 보여 준 다음, 프로젝트를 만들고 의존성을 설치합니다. 프로젝트 이름을 입력하고 나머지 모든 질문에서 Enter 키를 누르면 `hello` 레벨의 프로젝트가 만들어집니다. 실행이 끝나면 Next steps 패널이 표시되며, 프로젝트의 `README.md`에는 프로젝트를 새로 클론했을 때 따라야 할 단계가 정리되어 있습니다. + +![fastkit init을 실행한 터미널: 프로젝트 이름 shop, Levels 표, Project summary, Next steps 패널](img/2.0/generate-init-dialogue.svg) + +스크립트나 CI에서는 모든 선택 사항을 옵션으로 지정하면 fastkit이 아무것도 묻지 않습니다: -`fastkit init`은 먼저 레벨을 묻습니다. 각 레벨은 바로 앞 레벨에 구조를 더한 형태이며, 기본값은 `hello`입니다. +```console +$ fastkit init --project-name shop --level domain --database SQLite --feature authentication=JWT -y +``` + +프로젝트 안에서는 `fastkit runserver`로 앱을 실행하고, `fastkit addroute`로 리소스 하나를 그 리소스의 라우트, 스키마, 데이터 계층, 테스트와 함께 추가하고(`hello`를 제외한 모든 레벨에서 사용할 수 있습니다), `fastkit doctor`로 프로젝트에 알려진 문제가 있는지 검사합니다. fastkit을 사용하려면 Python 3.12 이상이 필요하며, uv, pip, pdm, Poetry와 함께 사용할 수 있습니다. + +## 레벨 {#levels} + +각 레벨은 바로 앞 레벨에 구조를 더한 형태입니다. fastkit은 프로젝트를 다른 레벨로 변환하지 않으며, 코드를 다음 레벨의 구조로 옮기는 방법은 배우기 과정에서 설명합니다. `hello` 다음의 모든 레벨에서는 데이터베이스를 고를 수 있고, 인증, 백그라운드 작업, 캐싱, 마이그레이션, 개발자 도구, Docker 같은 기능도 선택할 수 있습니다. 자세한 내용은 [기능 커스터마이즈하기](how-to/customise-features.md)를 참고하세요. @@ -42,7 +66,18 @@ FastAPI-fastkit은 `main.py` 파일 하나로 된 프로젝트부터 데이터 -## 예제 프로젝트 +## 프로젝트 하나로 FastAPI 배우기 {#learn-fastapi} + +모든 레벨에서 FastAPI의 각 개념은 생성된 코드에서 그 개념이 처음 등장하는 자리에 짧은 주석으로 설명되어 있으며, 주석 끝에는 공식 튜토리얼 페이지의 링크가 있습니다. 배우기 과정은 `shop`이라는 프로젝트 하나를 `hello` 레벨부터 `production` 레벨까지 따라갑니다: + +1. [첫 FastAPI 앱 생성하기](learn/generate.md) +2. [코드 이해하기](learn/understand.md) +3. [앱 확장하기](learn/extend.md) +4. [앱 테스트하기](learn/test.md) +5. [도메인 구조와 데이터베이스로 옮기기](learn/migrate.md) +6. [프로덕션에 배포하기](learn/deploy.md) + +## 예제 프로젝트 {#example-projects} `fastkit init --template `은 레벨 대신 완성된 예제 프로젝트를 복사합니다. 각 예제는 [예제 프로젝트로 시작하기](how-to/example-projects.md)에서 설명합니다. @@ -58,11 +93,12 @@ FastAPI-fastkit은 `main.py` 파일 하나로 된 프로젝트부터 데이터 -## 문서 안내 +## 문서 안내 {#documentation-map} - [실전 가이드](how-to/choose-a-level.md): 레벨 고르기, 기능 커스터마이즈하기, 스크립트에서 `fastkit init` 실행하기, 프로젝트 검사하기, fastkit 1.x에서 업그레이드하기처럼 작업 단위로 정리한 페이지가 있습니다. - [레퍼런스](reference/cli.md): 모든 명령과 옵션, 레벨과 기능, 생성된 프로젝트에 들어 있는 내용을 설명합니다. - [기여하기](contributing/development-setup.md): 저장소를 설정하는 방법, 템플릿을 작성하는 방법, 문서를 번역하는 방법을 안내합니다. +- 이 문서는 English, 한국어, 日本語, 中文, Español, Français, Deutsch로 제공됩니다. 페이지 상단의 언어 메뉴에서 원하는 언어를 고르세요. ## FastAPI-fastkit이 지향하는 것 diff --git a/docs/ko/learn/generate.md b/docs/ko/learn/generate.md index ac17d4f2..b774b5e4 100644 --- a/docs/ko/learn/generate.md +++ b/docs/ko/learn/generate.md @@ -2,7 +2,7 @@ 이 페이지에서는 `fastkit init`으로 작은 FastAPI 애플리케이션을 만들고, `fastkit runserver`로 실행한 다음 요청을 보내 봅니다. 그 과정에서 FastAPI 애플리케이션 객체, 경로 작동(path operation), uvicorn 서버, 그리고 FastAPI가 자동으로 만들어 주는 대화형 API 문서를 차례로 접하게 됩니다. -`hello` 레벨은 `main.py` 하나로 이루어진 `shop`이라는 프로젝트를 만듭니다. 이 프로젝트에는 엔드포인트 3개, 메모리에 저장되는 아이템, 그리고 엔드포인트마다 하나씩 작성된 테스트가 있습니다. 배우기 과정의 나머지 페이지에서도 이 프로젝트를 계속 키워 나가므로 이름은 `shop`으로 유지하세요. fastkit([설치](../start/installation.md))이 필요하며, 이 페이지의 명령을 실행하려면 [uv](https://docs.astral.sh/uv/)도 필요합니다. +`hello` 레벨은 `main.py` 하나로 이루어진 `shop`이라는 프로젝트를 만듭니다. 이 프로젝트에는 엔드포인트 3개, 메모리에 저장되는 아이템, 그리고 엔드포인트마다 하나씩 작성된 테스트가 있습니다. 배우기 과정의 나머지 페이지에서도 이 프로젝트를 계속 따라가므로 이름은 `shop`으로 유지하세요. fastkit([설치](../start/installation.md))이 필요하며, 이 페이지의 명령을 실행하려면 [uv](https://docs.astral.sh/uv/)도 필요합니다. ## 프로젝트 만들기 ![fastkit init을 실행한 터미널: 프로젝트 이름 shop, Levels 표, Project summary, Next steps 패널](../img/2.0/generate-init-dialogue.svg) @@ -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/reference/generated-projects.md b/docs/ko/reference/generated-projects.md index 192e1804..ed588906 100644 --- a/docs/ko/reference/generated-projects.md +++ b/docs/ko/reference/generated-projects.md @@ -103,7 +103,7 @@ features = ["database:PostgreSQL", "authentication:JWT", "testing:Coverage", "mi ## README.md의 다음 단계 -생성된 `README.md`에는 `fastkit init`이 마지막에 출력하는 것과 같은 다음 단계(Next steps) 목록이 두 주석 줄 사이에 들어 있습니다. +생성된 `README.md`에는 두 주석 줄 사이에 `fastkit init`이 마지막에 출력하는 다음 단계(Next steps)가 들어 있습니다. 이 단계는 프로젝트를 새로 클론한 상황을 기준으로 작성되어 있어서 `cd` 단계가 없고, 가상 환경을 만드는 단계가 있으며, 서버를 시작할 때 uvicorn을 사용합니다. ```markdown @@ -116,7 +116,7 @@ features = ["database:PostgreSQL", "authentication:JWT", "testing:Coverage", "mi ## 개념 주석 -생성된 코드는 각 FastAPI 구성 요소가 처음 나오는 위치에서 두 줄짜리 주석으로 그 요소를 설명합니다. 첫 줄은 설명 문장 하나이고, 둘째 줄은 그 요소를 다루는 FastAPI 문서 페이지의 주소입니다. +레벨로 만든 프로젝트에서는 템플릿의 코드와 기능이 추가한 코드에 두 줄짜리 주석이 들어 있으며, 이 주석은 각 FastAPI 구성 요소가 처음 나오는 위치에서 그 요소를 설명합니다. 첫 줄은 설명 문장 하나이고, 둘째 줄은 그 요소를 다루는 FastAPI 문서 페이지의 주소입니다. 예제 템플릿에는 이런 주석이 없으며, 각 예제가 보여 주는 개념은 실전 가이드의 예제 프로젝트로 시작하기 페이지에 정리되어 있습니다. ```python title="src/main.py" # `app` is the FastAPI application that uvicorn serves: `uvicorn src.main:app`. diff --git a/docs/zh/contributing/template-creation-guide.md b/docs/zh/contributing/template-creation-guide.md index 23099f03..42bb53e5 100644 --- a/docs/zh/contributing/template-creation-guide.md +++ b/docs/zh/contributing/template-creation-guide.md @@ -10,7 +10,7 @@ fastkit 复制模板时,以 `-tpl` 结尾的文件会去掉这个后缀:`src 一个模板至少需要: -- `README.md-tpl`。 +- `README.md-tpl`,以及一个创建 `FastAPI` 应用的 `main.py-tpl`,它位于模板根目录、`src/` 或 `src/app/` 中。 - `pyproject.toml-tpl`,并且其 `[project].dependencies` 中包含 `fastapi`。 - `tests/` 文件夹,其中至少有一个 `test_*.py-tpl` 模块。 @@ -123,7 +123,7 @@ app = FastAPI( | Junk files | 没有 `.DS_Store`、`__pycache__`、`.venv`、`.pyc` 之类的文件。 | | Dependencies | 声明了 `fastapi`。 | | Configuration consistency | 固定了 Python 3.12,`[project].dependencies` 中的包在 `requirements.txt-tpl` 中都有列出,并且没有对 `FastAPI-fastkit` 的依赖。 | -| FastAPI implementation | 生成的项目创建了一个 `FastAPI(...)` 应用。 | +| FastAPI implementation | 生成的项目在根目录、`src/` 或 `src/app/` 中有一个 `main.py`,并且它创建了一个 `FastAPI(...)` 应用。 | | Placeholder substitution | 生成的项目中没有残留任何 ``。 | | Compile check | 每个 Python 文件都能编译。 | | Template tests | 创建虚拟环境,安装依赖,然后运行 `scripts/test.sh`;没有该脚本时运行 `pytest tests/ -v`。 | diff --git a/docs/zh/index.md b/docs/zh/index.md index 3b7d9c30..463d8fee 100644 --- a/docs/zh/index.md +++ b/docs/zh/index.md @@ -16,19 +16,43 @@

-FastAPI-fastkit 用于创建 [FastAPI](https://github.com/fastapi/fastapi) 项目,既可以是只有一个 `main.py` 的项目,也可以是带有数据库、认证、测试和 Docker 的生产级结构。项目创建之后,同一个 `fastkit` 命令还可以运行项目、为项目添加路由,并检查项目中是否存在已知问题。 +FastAPI-fastkit 用于创建带有可运行代码和测试的 [FastAPI](https://github.com/fastapi/fastapi) 项目。五个级别从只有一个 `main.py`、包含 3 个端点的项目开始,一直到带有数据库、认证、CI 和 Docker 的生产级结构,每个级别都建立在前一个级别的基础上。每个级别的代码都自带讲解:每个概念旁的注释都链接到介绍该概念的 FastAPI 文档页面,每个项目最后都会给出一份后续步骤列表。 -## 从这里开始 +## 从哪里开始 {#where-to-start} -- **安装 fastkit**:按照[安装](start/installation.md)中的步骤操作,然后运行 `fastkit init`。 -- **不安装也能试用**:[网页生成器](start/web-generator.md)直接在浏览器中创建项目,并提供一个 zip 文件供你下载。 -- **刚接触 FastAPI**:“学习”部分从[生成你的第一个 FastAPI 应用](learn/generate.md)开始,跟随同一个项目从单个文件一路走到生产环境。 +- **在浏览器中试用**:[网页生成器](start/web-generator.md)无需安装任何东西即可创建项目,并提供一个 zip 文件供你下载。 +- **安装 fastkit 并创建项目**:按照[安装](start/installation.md)中的步骤操作,然后运行 `fastkit init`。 +- **循序渐进地学习 FastAPI**:“学习”部分从[生成你的第一个 FastAPI 应用](learn/generate.md)开始,跟随同一个项目一直走到生产环境。 +- **查阅资料**:[操作指南](how-to/choose-a-level.md)中的每个页面解决一项任务,[参考](reference/cli.md)介绍了每个命令、选项、级别和功能。 +- **从 fastkit 1.x 升级**:[从 fastkit 1.x 升级](how-to/upgrade-from-1x.md)列出了你的命令和脚本中需要修改的地方。你现有的项目仍然可以正常运行。 + +## 在浏览器中 {#in-your-browser} + +[网页生成器](start/web-generator.md)的用法与 Spring Initializr 类似:选择级别、数据库和功能,同时观察文件列表的变化,然后把项目下载为 zip 文件。它通过 [Pyodide](https://pyodide.org/) 在你的浏览器中运行 fastkit 生成器本身,因此你输入的任何内容都不会被发送到别处。zip 中的文件与页面在表单旁显示的 `fastkit init ... --no-venv` 命令生成的文件相同。 ![选择了 layered 级别和 SQLite 的网页生成器页面:表单、文件列表、与所选内容对应的 fastkit init 命令,以及“Generate and download”按钮](img/2.0/index-web-generator.png) -## 级别 +下载完成后,页面会列出这个项目的后续步骤,以及每个已选功能添加的内容:相关的文件、设置和文档链接。 + +![下载完成后的网页生成器:已下载包含 52 个文件的 shop.zip,从 cd shop 到 fastkit init --level production 按编号列出的“Next steps”,以及 SQLite 数据库的“Selected features”部分](img/2.0/web-generator-result.png) + +## 在终端中 {#in-your-terminal} + +`fastkit init` 会询问项目名称和级别,显示摘要,然后创建项目并安装项目的依赖。只需输入项目名称,其余提问都直接按 Enter,即可得到 `hello` 级别。运行结束时会显示“Next steps”面板,项目的 `README.md` 则列出了在全新检出的项目中要执行的步骤。 + +![运行 fastkit init 的终端:项目名称 shop、“Levels”表格、“Project summary”和“Next steps”面板](img/2.0/generate-init-dialogue.svg) + +在脚本和 CI 中,把每个选择都作为选项传入,就不会出现任何提问: -`fastkit init` 会询问要使用哪个级别。每个级别都在上一个级别的基础上增加结构,默认级别是 `hello`。 +```console +$ fastkit init --project-name shop --level domain --database SQLite --feature authentication=JWT -y +``` + +在项目中,`fastkit runserver` 用于启动应用,`fastkit addroute` 用于添加一个资源及其路由、schema、数据层和测试(除 `hello` 外的任何级别都可以使用该命令),`fastkit doctor` 用于检查项目中是否存在已知问题。fastkit 需要 Python 3.12 或更高版本,支持 uv、pip、pdm 和 Poetry。 + +## 级别 {#levels} + +每个级别都在上一个级别的基础上增加结构。fastkit 不会把项目转换为另一个级别;“学习”部分会介绍如何把你的代码迁移到下一个级别。在 `hello` 之后的每个级别,你都可以选择数据库,以及认证、后台任务、缓存、迁移、开发工具和 Docker 等功能,详见[自定义功能](how-to/customise-features.md)。 @@ -42,7 +66,18 @@ FastAPI-fastkit 用于创建 [FastAPI](https://github.com/fastapi/fastapi) 项 -## 示例项目 +## 用一个项目学习 FastAPI {#learn-fastapi} + +在每个级别生成的代码中,每个 FastAPI 概念在首次出现的地方都有一条简短的注释加以讲解,注释末尾附有对应官方教程页面的链接。“学习”部分跟随同一个项目 `shop`,从 `hello` 级别一直走到 `production` 级别: + +1. [生成你的第一个 FastAPI 应用](learn/generate.md) +2. [理解代码](learn/understand.md) +3. [扩展应用](learn/extend.md) +4. [测试应用](learn/test.md) +5. [迁移到领域结构和数据库](learn/migrate.md) +6. [部署到生产环境](learn/deploy.md) + +## 示例项目 {#example-projects} `fastkit init --template ` 复制的是一个完整的示例项目,而不是某个级别。[从示例项目开始](how-to/example-projects.md)逐一介绍了这些示例项目。 @@ -58,11 +93,12 @@ FastAPI-fastkit 用于创建 [FastAPI](https://github.com/fastapi/fastapi) 项 -## 文档导览 +## 文档导览 {#documentation-map} - [操作指南](how-to/choose-a-level.md):按任务组织的页面,例如选择级别、自定义功能、在脚本中运行 `fastkit init`、检查项目,以及从 fastkit 1.x 升级。 - [参考](reference/cli.md):所有命令和选项、各个级别和功能,以及生成的项目包含哪些内容。 - [参与贡献](contributing/development-setup.md):搭建仓库的开发环境、编写模板,以及翻译文档。 +- 文档提供 English、한국어、日本語、中文、Español、Français 和 Deutsch 版本,可以通过页面顶部的语言菜单切换语言。 ## FastAPI-fastkit 的意义 diff --git a/docs/zh/learn/generate.md b/docs/zh/learn/generate.md index d24efacf..b80333a2 100644 --- a/docs/zh/learn/generate.md +++ b/docs/zh/learn/generate.md @@ -2,7 +2,7 @@ 在本页中,你将用 `fastkit init` 创建一个小型 FastAPI 应用,用 `fastkit runserver` 启动它,然后向它发送请求。在这个过程中,你会认识 FastAPI 的应用对象、路径操作、uvicorn 服务器,以及 FastAPI 自动为你生成的交互式 API 文档。 -`hello` 级别会创建一个名为 `shop` 的项目,其中只有一个 `main.py`:包含三个端点和保存在内存中的条目。项目还为每个端点各附带一个测试。“学习”部分后面的页面都会在这个项目的基础上继续扩展,所以请保留 `shop` 这个名称。你需要先安装 fastkit([安装](../start/installation.md)),运行本页的命令还需要 [uv](https://docs.astral.sh/uv/)。 +`hello` 级别会创建一个名为 `shop` 的项目,其中只有一个 `main.py`:包含三个端点和保存在内存中的条目。项目还为每个端点各附带一个测试。“学习”部分后面的页面都会沿用这个项目,所以请保留 `shop` 这个名称。你需要先安装 fastkit([安装](../start/installation.md)),运行本页的命令还需要 [uv](https://docs.astral.sh/uv/)。 ## 创建项目 ![运行 fastkit init 的终端:项目名称 shop、“Levels”表格、“Project summary”和“Next steps”面板](../img/2.0/generate-init-dialogue.svg) @@ -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 只写入文件,之后在项目文件夹中运行 `uv sync` 即可创建 `.venv`,这和从 git 克隆项目之后的做法相同。 +“Author”一行的值取自 `git config`(这里的 git 没有设置作者姓名)。fastkit 在 `shop/.venv` 中创建了虚拟环境,并把所需的包安装到其中。“Next steps”面板就是你接下来要做的事,项目的 `README.md` 则列出了在全新检出的项目中要执行的步骤。如果使用 `fastkit init --no-venv`,fastkit 只写入文件,之后在项目文件夹中运行 `uv sync` 即可创建 `.venv`,这和从 git 克隆项目之后的做法相同。 ## fastkit 创建了什么 diff --git a/docs/zh/reference/generated-projects.md b/docs/zh/reference/generated-projects.md index ad9cc99b..78bb0b61 100644 --- a/docs/zh/reference/generated-projects.md +++ b/docs/zh/reference/generated-projects.md @@ -103,7 +103,7 @@ features = ["database:PostgreSQL", "authentication:JWT", "testing:Coverage", "mi ## README.md 中的后续步骤 -每个生成的 `README.md` 都在两个注释行之间包含一份“Next steps”(后续步骤)列表,内容与 `fastkit init` 最后打印的列表相同: +每个生成的 `README.md` 都在两个注释行之间包含 `fastkit init` 最后打印的“Next steps”(后续步骤),这些步骤是为全新检出的项目编写的(没有 `cd`,包含一个创建环境的步骤,并用 uvicorn 启动服务器): ```markdown @@ -116,7 +116,7 @@ features = ["database:PostgreSQL", "authentication:JWT", "testing:Coverage", "mi ## 概念注释 -生成的代码会在每个 FastAPI 概念首次出现的位置用两行注释加以解释:第一行是一句说明,第二行是讲解它的 FastAPI 文档页面地址。 +在由级别创建的项目中,模板的代码和功能添加的代码会在每个 FastAPI 概念首次出现的位置用两行注释加以解释:第一行是一句说明,第二行是讲解它的 FastAPI 文档页面地址。示例模板中没有这类注释;介绍示例项目的操作指南页面列出了每个示例模板展示的概念。 ```python title="src/main.py" # `app` is the FastAPI application that uvicorn serves: `uvicorn src.main:app`. diff --git a/pdm.lock b/pdm.lock index dbee4218..a0031157 100644 --- a/pdm.lock +++ b/pdm.lock @@ -5,7 +5,7 @@ groups = ["default", "dev", "docs", "test-runtime", "translation"] strategy = ["inherit_metadata"] lock_version = "4.5.0" -content_hash = "sha256:917a194bf8ac260d4a23f6f0606a314e11d3b707e9b3943a6fe5fc55fe7b87e6" +content_hash = "sha256:6db94c2d6fa21ed9d3adb68b0ca00bd28587859b9dcc849a2f8e302ba8271575" [[metadata.targets]] requires_python = ">=3.12" diff --git a/pyproject.toml b/pyproject.toml index b82a017c..d3132875 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,17 +6,36 @@ authors = [ {name = "bnbong", email = "bbbong9@gmail.com"}, ] dependencies = [ - "click>=8.1.7", + # click 8.2.0 is the first with a generic click.Choice (commands/init.py + # subclasses click.Choice[str]); with 8.1 the CLI fails at import. The + # test suite needs 8.2.1, whose CliRunner ends prompts at end of input. + "click>=8.2.0", "rich>=13.9.2", "jinja2>=3.1", ] requires-python = ">=3.12" readme = "README.md" license = {text = "MIT"} +keywords = ["fastapi", "starter", "template", "scaffolding", "code-generator", "cli"] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Environment :: Console", + "Framework :: FastAPI", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Operating System :: OS Independent", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", + "Topic :: Software Development :: Code Generators", + "Typing :: Typed", +] [project.urls] -Homepage = "https://github.com/bnbong/FastAPI-kit" -Repository = "https://github.com/bnbong/FastAPI-kit" +Homepage = "https://github.com/bnbong/FastAPI-fastkit" +Repository = "https://github.com/bnbong/FastAPI-fastkit" Documentation = "https://bnbong.github.io/FastAPI-fastkit/" Changelog = "https://bnbong.github.io/FastAPI-fastkit/changelog/" diff --git a/scripts/web_generator/build_assets.py b/scripts/web_generator/build_assets.py index 8ae42fa8..65f8097c 100644 --- a/scripts/web_generator/build_assets.py +++ b/scripts/web_generator/build_assets.py @@ -41,7 +41,7 @@ MANIFEST_SCHEMA = 1 PYODIDE_DIR = "pyodide" TARBALL_PREFIX = "package/" -FASTKIT_SOURCE = "https://github.com/bnbong/FastAPI-kit" +FASTKIT_SOURCE = "https://github.com/bnbong/FastAPI-fastkit" CPYTHON_SOURCE = "https://github.com/python/cpython" WHEEL_NAME = re.compile( r"^fastapi_fastkit-(?P[^-]+)(-\d[^-]*)?-py3-none-any\.whl$", re.I diff --git a/uv.lock b/uv.lock index 9228ee89..ae08a791 100644 --- a/uv.lock +++ b/uv.lock @@ -33,25 +33,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/78/b6/6307fbef88d9b5ee7421e68d78a9f162e0da4900bc5f5793f6d3d0e34fb8/annotated_types-0.7.0-py3-none-any.whl", hash = "sha256:1f02e8b43a8fbbc3f3e0d4f0f4bfc8131bcb4eebe8849b8e5c773f3a1c582a53", size = 13643, upload-time = "2024-05-20T21:33:24.1Z" }, ] -[[package]] -name = "anthropic" -version = "0.74.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "anyio" }, - { name = "distro" }, - { name = "docstring-parser" }, - { name = "httpx" }, - { name = "jiter" }, - { name = "pydantic" }, - { name = "sniffio" }, - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/5b/f9/baa1b885c8664b446e6a13003938046901e54ffd70b532bbebd01256e34b/anthropic-0.74.0.tar.gz", hash = "sha256:114ec10cb394b6764e199da06335da4747b019c5629e53add33572f66964ad99", size = 428958, upload-time = "2025-11-18T15:29:47.579Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/61/27/8c404b290ec650e634eacc674df943913722ec21097b0476d68458250c2f/anthropic-0.74.0-py3-none-any.whl", hash = "sha256:df29b8dfcdbd2751fa31177f643d8d8f66c5315fe06bdc42f9139e9f00d181d5", size = 371474, upload-time = "2025-11-18T15:29:45.748Z" }, -] - [[package]] name = "anyio" version = "4.14.2" @@ -381,15 +362,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/12/b3/231ffd4ab1fc9d679809f356cebee130ac7daa00d6d6f3206dd4fd137e9e/distro-1.9.0-py3-none-any.whl", hash = "sha256:7bffd925d65168f85027d8da9af6bddab658135b840670a223589bc0c8ef02b2", size = 20277, upload-time = "2023-12-24T09:54:30.421Z" }, ] -[[package]] -name = "docstring-parser" -version = "0.17.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/b2/9d/c3b43da9515bd270df0f80548d9944e389870713cc1fe2b8fb35fe2bcefd/docstring_parser-0.17.0.tar.gz", hash = "sha256:583de4a309722b3315439bb31d64ba3eebada841f2e2cee23b99df001434c912", size = 27442, upload-time = "2025-07-21T07:35:01.868Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/55/e2/2537ebcff11c1ee1ff17d8d0b6f4db75873e3b0fb32c2d4a2ee31ecb310a/docstring_parser-0.17.0-py3-none-any.whl", hash = "sha256:cf2569abd23dce8099b300f9b4fa8191e9582dda731fd533daf54c4551658708", size = 36896, upload-time = "2025-07-21T07:35:00.684Z" }, -] - [[package]] name = "fastapi" version = "0.165.0" @@ -455,7 +427,6 @@ test-runtime = [ { name = "pyyaml" }, ] translation = [ - { name = "anthropic" }, { name = "anyio" }, { name = "openai" }, ] @@ -463,7 +434,7 @@ translation = [ [package.metadata] requires-dist = [ { name = "black", marker = "extra == 'dev'", specifier = ">=26.10.1" }, - { name = "click", specifier = ">=8.1.7" }, + { name = "click", specifier = ">=8.2.0" }, { name = "filelock", marker = "extra == 'dev'", specifier = ">=4.2.1" }, { name = "isort", marker = "extra == 'dev'", specifier = ">=9.0.1" }, { name = "jinja2", specifier = ">=3.1" }, @@ -502,7 +473,6 @@ test-runtime = [ { name = "pyyaml", specifier = ">=6.0.3" }, ] translation = [ - { name = "anthropic", specifier = ">=0.74.0" }, { name = "anyio", specifier = ">=4.14.2" }, { name = "openai", specifier = ">=2.8.1" }, ]