Skip to main content

KMVPy

简体中文版:README.zh-CN.md

KMVPy logo

KMVPy header

A FastAPI-based server-side foundation library: YAML-driven configuration, async SQLAlchemy domain layer, unified response and exception handling, JWT, APScheduler scheduling, Socket.IO, and an engineering scaffold (Python + frontend sub-projects, YAML smoke-test skeletons). Default dependencies already include Web, async SQLite/PostgreSQL, Redis, Cassandra drivers, PyJWT, OpenAI SDK and more; MySQL requires an extra optional dependency.

Core Modules (Framework Capabilities)

Module Responsibility
kmvpy.core.main ASGI entry: init_asgi_app aggregates routers, logging, i18n, Socket.IO and global exceptions; lifespan initializes/releases DB·Redis resources; get_config_path resolves the config path. The docstring contains integration notes for "create/evolve tables from ORMs at startup" (init_tables_by_orms + async driver constraints).
kmvpy.common.conf BaseConfig (YAML → Pydantic): DB table connections, Redis, logging, service/CORS, Socket.IO, auth (JWT, splittable by user type), optional first admin, SnowflakeConfig and KSnowflake, etc.
kmvpy.common.infra KOrmStorage + KOrmBase: async sessions, pagination and safe sorting, cache cooperation and other ORM semantics; Snowflake IDs (KSnowflake).
kmvpy.common.response ApiResponse / SocketioResponse: unified JSON success and error shapes, integrated with KmvException and error-code conventions.
kmvpy.common.exception KmvException, KmvError: business error codes and message conventions.
kmvpy.common.schedule APScheduler-based async scheduling: ScheduleManager, schedule_task decorator, global scheduler lifecycle (hooked to ASGI startup).
kmvpy.common.kmv kosmos: in-process config, Socket.IO and other existing runtime mount points; Storage is explicitly held by the app and passed to init_asgi_app.
kmvpy.common.st Smoke-test skeleton: StBasePyTest, StTestCase, YAML steps and expectations (used by the generated project's st_test).
kmvpy.core.main.service JWT (multiple algorithms, user-info payload, etc.; see the module).
kmvpy.core.main.router Socket.IO and FastAPI app binding.
kmvpy.generator CLI: kmvpy create / kmvpy update / kmvpy rotate-jwt-keys; generates projects and supports JWT key rotation; see kmvpy/generator/README.md.

Default Dependencies and Optional Extras

  • Declared in: pyproject.toml (PEP 517 / PEP 621, setuptools build backend).
  • Optional: [project.optional-dependencies] currently provides mysql (mysqlclient, aiomysql, etc.); the rest of Web/Redis/SocketIO etc. live in the default dependencies.

Tech Stack (excerpt)

FastAPI · Uvicorn · Pydantic v2 · SQLAlchemy 2 (async) · Redis · APScheduler · python-i18n · PyYAML · PyJWT · fastapi-socketio · asyncpg / aiosqlite · cassandra-driver · OpenAI SDK

Typical Use Cases

REST/realtime hybrid APIs, microservice foundations with unified config and error contracts, and teams that want to scaffold frontend/backend directories and smoke-test templates with one command.


Installation and Usage

Environment: Python ≥ 3.11

Release status (2026-09-08): The PyPI project index currently does not list kmvpy, but this repository has not shipped its first release yet. Until the first version is actually published, please use the local installation methods below. Maintainer actions: see the PyPI first-release guide.

Local install: pip install . · Development: pip install -e . · With MySQL: pip install ".[mysql]"

PyPI install (after first release): pip install kmvpy · With MySQL: pip install "kmvpy[mysql]"

Build: python -m pip install -U build twine && python -m build && python -m twine check --strict dist/* → artifacts land in dist/; prefer the wheel for distribution/install. Offline install from tar.gz only, while avoiding build dependencies: pip install --no-build-isolation --no-deps dist/kmvpy-0.2.3.tar.gz.

Scaffold and ops commands: kmvpy create <name> [-d parent-dir] · kmvpy update … · kmvpy rotate-jwt-keys path/to/config.yaml

Quick check:

python -c "from kmvpy.core.main.service.jwt_service import JwtUserInfo; print(JwtUserInfo)"

Example:

import kmvpy
from kmvpy.common.tool.logger import logger, init_logger

init_logger(debug=True)
logger.info("ok")

# from kmvpy.common.conf import BaseConfig
# config = BaseConfig.load_config("path/to/config.yaml")

# from kmvpy.core.main import init_asgi_app, get_config_path
# app = init_asgi_app(BaseConfig.load_config(get_config_path()), routers=[...])

Redis ACL Configuration

All Redis configurations (default_storage.redis, the top-level redis used by legacy projects, auth_config.user.redis, auth_config.admin.redis) support an optional username:

redis:
  host: localhost
  port: 6379
  db: 0
  username: app_user
  password: "your-redis-password"
  decode_responses: true

Place this snippet under the corresponding config layer. When username is configured, authentication uses the ACL username and password; when username is omitted, set to null, or left as an empty string, the existing password-only authentication is kept and no legacy config change is needed. The Socket.IO Redis clients and distributed message-forwarding connections generated by the scaffold support ACL as well.

Packaging and Local Installation (detailed)

The commands below run from the repository root (the directory containing pyproject.toml); the build is driven by setuptools via PEP 517 and artifacts are written to dist/. The first build needs network access for build-tool dependencies (setuptools, wheel); subsequent builds hit the local cache.

① Prepare build and validation tools (one-time)

python -m pip install -U pip build twine

② Clean stale artifacts and build

rm -rf build dist *.egg-info
python -m build
python -m twine check --strict dist/*

Artifacts (the version comes solely from kmvpy/__init__.py's __version__; currently 0.2.3; bump it before a new release):

Artifact Description Recommended Use
dist/kmvpy-0.2.3-py3-none-any.whl wheel, pure Python, no platform limits Preferred: install, deliver, offline distribution
dist/kmvpy-0.2.3.tar.gz sdist source package source audit, repackaging

The wheel ships the scaffold templates and nginx templates (collected via MANIFEST.in + include-package-data), so after installation kmvpy create / update can generate or update projects directly without manually copying templates from the repository.

③ Local install (pick one)

Option A: install directly from the source directory (builds on site, then installs into the current environment)

pip install .
# when MySQL drivers (mysqlclient / aiomysql) are needed:
pip install ".[mysql]"

Option B: editable install (recommended for development and debugging; code changes take effect immediately without reinstalling)

pip install -e .
pip install -e ".[mysql]"

Option C: install a built wheel (recommended for delivery / CI / offline distribution)

pip install dist/kmvpy-0.2.3-py3-none-any.whl

Option D: offline install from sdist (when the environment already has all runtime dependencies and you want to skip pulling build dependencies; bypasses build isolation and dependency resolution)

pip install --no-build-isolation --no-deps dist/kmvpy-0.2.3.tar.gz

Note: Option D's --no-deps will not auto-install any runtime dependencies; if the environment is missing dependencies, use Option A/C (or install the missing dependencies first).

It is recommended to create a virtual environment first to avoid polluting the global Python:

python -m venv .venv
source .venv/bin/activate    # Windows: .venv\Scripts\activate

④ Verify after install

python -c "from kmvpy.core.main.service.jwt_service import JwtUserInfo; print(JwtUserInfo)"
kmvpy --help

Uninstall: pip uninstall kmvpy; before reinstalling, uninstall first and then run any of the install commands above.

JWT Key Configuration

JWT supports only a whitelist of asymmetric algorithms (default RS256). Config files are forbidden from storing PEM content; they may only reference read-only key file paths injected by the deployment system. At startup kmvpy validates the paths, PEM legitimacy, kid uniqueness, and that the active private key matches the active public key.

auth_config:
  user:
    jwt:
      algorithm: "RS256"
      active_kid: "user-20050607"
      private_key_path: "/run/secrets/signal-tracker/jwt-private-user-20050607.pem"
      public_keys:
        - kid: "user-20050607"
          public_key_path: "/run/secrets/signal-tracker/jwt-public-user-20050607.pem"
        - kid: "user-20050301"
          public_key_path: "/run/secrets/signal-tracker/jwt-public-user-20050301.pem"
      issuer: "kmvpy"
      audience: "kmvpy-user-api"
      access_token_lifetime_hours: 0.25

Rotation: configure the new private key path as private_key_path, switch active_kid to the new kid, and keep both old and new public keys in public_keys. After the old tokens expire, remove the old public key; tokens with the old kid will automatically fail verification.

You can also complete one user/admin key rotation automatically with the kmvpy CLI:

kmvpy rotate-jwt-keys app/etc/release/config.yaml

The command reads the directory containing the current private_key_path and the active public key's public_key_path, generates new private/public PEM files and a random active_kid, inserts the new public key into public_keys, and backs up the original config file. Up to 1 extra old public-key pair is kept for transitional verification when the old public key file exists; when the old public key file is missing, it is removed from config and only the newly generated public key is used. If the config lacks auth_config or the user/admin JWT fragments, they are completed per RS256 and the default issuer/audience/lifetime/session/redis specs, with keys generated into ./secrets next to the config file.

Production mount recommendations:

  • Ubuntu bare metal: place keys at /etc/<app>/secrets/jwt-private-user-20050607.pem or /run/secrets/<app>/jwt-private-user-20050607.pem; for the private key, 0400 is recommended, owned by the service user, and the config references paths only.
  • Docker: mount via Docker secrets or a read-only bind mount to flat-file paths like /run/secrets/<app>/jwt-private-user-20050607.pem; reference the mounted path from the container config.
  • K8s: mount read-only via a Secret projected volume or CSI Secret Store to flat-file paths like /run/secrets/<app>/jwt-private-user-20050607.pem; K8s default file modes may be too permissive — kmvpy warns, and production startup is refused when group/other write permission or execute bits are present.

Details and generated-project conventions: see kmvpy/generator/README.md and the docstrings inside each package.

Metadata

Release files for kmvpy 0.2.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for kmvpy 0.2.3
File Size Uploaded
kmvpy-0.2.3.tar.gz 371.0 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for kmvpy 0.2.3
File Interpreter ABI Platform
kmvpy-0.2.3-py3-none-any.whl Python 3 none any Details

Total release size: 849.0 kB

Release files / kmvpy-0.2.3.tar.gz

Download URL kmvpy-0.2.3.tar.gz
Size 371.0 kB
Tags Source
SHA-256 checksum
How to use checksums
ddff7a842ffb647ca5a4e4e7ea92f02259d7abf517e17c92f945099937da3c46
BLAKE2b-256 checksum
How to use checksums
15bfc7d9abce37594ba9a13a0ac476e52ed192c79c536ae653a8e22c90c17cde
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 9, 2026.

Transparency log

Release files / kmvpy-0.2.3-py3-none-any.whl

Download URL kmvpy-0.2.3-py3-none-any.whl
Size 478.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
890cf6a8e623a77944eba0062dfa8db6e64b224bca6573af73529c89f1b68f40
BLAKE2b-256 checksum
How to use checksums
ff41cff0bcb7c76f9c1c7058e31c631494c8223707adb050da7915e7f685de66
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 9, 2026.

Transparency log

Release history Release notifications | RSS feed

This release

0.2.3 This release

2 release files

0.2.2

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page