Skip to main content

Typer CLI plugin for Spakky framework

Project description

Spakky Typer

Spakky Framework를 위한 Typer CLI 통합 플러그인입니다. @CliController@command 선언, actuator command group을 Typer 앱에 자동 등록합니다.

설치

pip install spakky-typer

Spakky extras로도 설치할 수 있습니다.

pip install spakky[typer]

주요 기능

  • 자동 command 등록: @CliController 클래스에서 command를 등록합니다.
  • 비동기 지원: CLI command에서 async/await 전체 지원
  • Command grouping: command를 논리적 group으로 구성
  • 의존성 주입: 서비스가 controller에 자동 주입
  • Auth boundary 통합: --auth-token / SPAKKY_AUTH_TOKEN 전달체로 AuthContext seed 및 protected command fail-closed 처리
  • Rich 통합: Typer의 rich console output 활용
  • Actuator command: spakky-actuator 로드 시 actuator 상태 command 등록

사용법

기본 CLI Controller

from spakky.plugins.typer.stereotypes.cli_controller import CliController, command

@CliController("user")
class UserCliController:
    def __init__(self, user_service: UserService) -> None:
        self.user_service = user_service

    @command("list")
    async def list_users(self) -> None:
        """모든 user를 나열합니다."""
        users = await self.user_service.list_all()
        for user in users:
            print(f"{user.id}: {user.name}")

    @command("create")
    async def create_user(self, name: str, email: str) -> None:
        """새 user를 생성합니다."""
        user = await self.user_service.create(name, email)
        print(f"Created user: {user.id}")

    @command("delete")
    async def delete_user(self, user_id: int) -> None:
        """ID로 user를 삭제합니다."""
        await self.user_service.delete(user_id)
        print(f"Deleted user: {user_id}")

CLI 사용

# 모든 user 나열
python main.py user list

# 새 user 생성
python main.py user create --name "John Doe" --email "john@example.com"

# user 삭제
python main.py user delete --user-id 123

Command 옵션

from spakky.plugins.typer.stereotypes.cli_controller import CliController, command

@CliController("db")
class DatabaseCliController:
    @command(
        name="migrate",
        help="Run database migrations",
        short_help="Run migrations",
        epilog="Use --dry-run to preview changes",
    )
    async def run_migrations(
        self,
        dry_run: bool = False,
        verbose: bool = False,
    ) -> None:
        """pending database migration을 실행합니다."""
        if dry_run:
            print("Dry run mode - no changes will be made")
        # migration logic

    @command("seed", hidden=True)  # help output에서 숨김
    async def seed_database(self) -> None:
        """test data로 database를 seed합니다."""
        pass

    @command("status", deprecated=True)  # deprecated 표시
    async def check_status(self) -> None:
        """database connection status를 확인합니다."""
        pass

Typer 인스턴스 접근

from typer import Typer
from spakky.core.application.application import SpakkyApplication
from spakky.core.application.application_context import ApplicationContext
from spakky.core.pod.annotations.pod import Pod

import apps
import spakky.plugins.typer


@Pod(name="cli")
def get_cli() -> Typer:
    return Typer()


application = (
    SpakkyApplication(ApplicationContext())
    .load_plugins(include={spakky.plugins.typer.PLUGIN_NAME})
    .scan(apps)
    .add(get_cli)
    .start()
)

# application.start() 이후
typer_app: Typer = application.container.get(Typer)

# CLI 실행
if __name__ == "__main__":
    typer_app()

spakky-typer는 command registration post-processor를 등록하지만 Typer 인스턴스 자체는 애플리케이션에서 Pod로 등록해야 합니다.

Auth boundary

spakky-auth decorator를 CLI controller method에 선언하면 Typer adapter가 command 실행 전에 auth 전달체를 추출하고 ApplicationContextAuthContext를 seed합니다.

전달체 우선순위는 --auth-token option, 그 다음 SPAKKY_AUTH_TOKEN env var입니다. stdin은 auth 전달체로 사용하지 않습니다.

from spakky.auth import protected, require_scope
from spakky.plugins.typer.stereotypes.cli_controller import CliController, command


@CliController("docs")
class DocumentCliController:
    @command("read")
    @require_scope("documents:read")
    def read_document(self, document_id: str) -> None:
        print(f"read {document_id}")
python main.py docs read --document-id doc-1 --auth-token "$TOKEN"
SPAKKY_AUTH_TOKEN="$TOKEN" python main.py docs read --document-id doc-1

Auth 결과는 reason code를 출력하고 Typer exit code로 매핑됩니다.

Decision Exit code
CHALLENGE 2
DENY 3
ERROR 1

Decorator가 없는 command는 provider나 token 없이 허용됩니다. Protected command는 token/provider/AuthContext/checker가 없거나 authorization decision이 ALLOW가 아니면 fail closed 됩니다.

Actuator command

spakky-typerspakky-actuator를 함께 로드하면 플러그인이 actuator command group을 등록합니다:

python main.py actuator health
python main.py actuator readiness
python main.py actuator liveness
python main.py actuator info

각 command는 transport 중립 actuator core result model에서 결정적 JSON을 출력합니다. readiness는 앱이 작업을 받을 준비가 되었는지 보고합니다. liveness는 프로세스 내부 check로 남아야 하며 외부 의존성을 사용할 수 없다는 이유만으로 실패하면 안 됩니다.

ActuatorTyperConfig는 플러그인이 등록하는 @Configuration Pod입니다. command 등록은 다음 환경변수로 비활성화합니다:

export SPAKKY_TYPER_ACTUATOR_COMMAND_ENABLED=false

command group 이름은 다음으로 변경합니다:

export SPAKKY_TYPER_ACTUATOR_COMMAND_NAME=status

Typer adapter는 플러그인별 상세 check를 자동 등록하지 않습니다. 데이터베이스, broker, worker readiness가 command 출력에 영향을 줘야 한다면 애플리케이션에 spakky.actuator.AbstractHealthProbe Pod를 등록하세요.

애플리케이션 설정

from spakky.core.application.application import SpakkyApplication
from spakky.core.application.application_context import ApplicationContext
from spakky.core.pod.annotations.pod import Pod
from typer import Typer
import my_cli_module


@Pod(name="cli")
def get_cli() -> Typer:
    return Typer()


app = (
    SpakkyApplication(ApplicationContext())
    .load_plugins()
    .scan(my_cli_module)
    .add(get_cli)
    .start()
)

typer_app = app.container.get(Typer)

if __name__ == "__main__":
    typer_app()

구성 요소

컴포넌트 설명
CliController CLI command group용 stereotype
command CLI command용 decorator
TyperCLIPostProcessor 자동 command 등록 post-processor
ActuatorTyperConfig @Configuration 기반 actuator command 설정
ActuatorTyperCommandPostProcessor ActuatorAggregationService가 있을 때 actuator command group 등록

Command decorator 옵션

옵션 타입 설명
name str command 이름(기본값은 kebab-case 메서드명)
help str command 전체 help text
short_help str command 목록용 짧은 help text
epilog str command help 뒤에 표시할 text
hidden bool help output에서 command 숨김
deprecated bool command를 deprecated로 표시
no_args_is_help bool 인자가 없을 때 help 표시
add_help_option bool --help option 추가 여부
rich_help_panel str Rich console help panel 이름

라이선스

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

spakky_typer-6.8.0.tar.gz (10.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

spakky_typer-6.8.0-py3-none-any.whl (14.0 kB view details)

Uploaded Python 3

File details

Details for the file spakky_typer-6.8.0.tar.gz.

File metadata

  • Download URL: spakky_typer-6.8.0.tar.gz
  • Upload date:
  • Size: 10.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for spakky_typer-6.8.0.tar.gz
Algorithm Hash digest
SHA256 5069bf8b824e7e906f99b6f5290a9e9c02e4502bb1d29a677bfcfb0540d503d7
MD5 f5aa03aadc332fada277bbc4b64a8eba
BLAKE2b-256 cb581b0848e2fb271133309213f664b4b3b34d3ec68c9af8818038931fa7bde1

See more details on using hashes here.

Provenance

The following attestation bundles were made for spakky_typer-6.8.0.tar.gz:

Publisher: release.yml on E5presso/spakky-framework

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file spakky_typer-6.8.0-py3-none-any.whl.

File metadata

  • Download URL: spakky_typer-6.8.0-py3-none-any.whl
  • Upload date:
  • Size: 14.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for spakky_typer-6.8.0-py3-none-any.whl
Algorithm Hash digest
SHA256 a107e13316e6add08921489255d40b18fa66b9b378c6e618b82c00383408922e
MD5 6e29c65e3d2728550ae7a1299ec036c4
BLAKE2b-256 10ccb65fa17cf347eb565acad6bb8a31378199d84cada60c3bae96898dbeee24

See more details on using hashes here.

Provenance

The following attestation bundles were made for spakky_typer-6.8.0-py3-none-any.whl:

Publisher: release.yml on E5presso/spakky-framework

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page