콘텐츠로 이동

Pydantic 플러그인

!!! 경고 "실험적 기능" 플러그인 지원은 실험적이며 마이너 릴리스에서 변경될 수 있습니다. 기능이 안정화될 때까지 플러그인 개발은 권장되지 않습니다.

Pydantic을 사용하면 사용자는 라이브러리의 기능을 확장하는 데 사용할 수 있는 플러그인을 만들 수 있습니다.

플러그인은 Python 진입점을 통해 설치됩니다. Python Packaging Authority의 진입점 사양 에서 진입점에 대한 자세한 내용을 읽을 수 있습니다.

my-pydantic-plugin 이라는 프로젝트가 있는 경우 pyproject.toml 에 다음을 추가하여 플러그인을 생성할 수 있습니다.

[project.entry-points.pydantic]
my_plugin = "my_pydantic_plugin:plugin"

진입점 그룹은 pydantic 이고, my_plugin 플러그인 이름이고, my_pydantic_plugin 은 플러그인 객체를 로드할 모듈이고, plugin 은 로드할 객체 이름입니다.

플러그인은 검색된 순서대로 로드되며 검색된 순서는 보장되지 않습니다.

사용자는 plugin_settings 모델 구성 인수 또는 클래스 키워드 인수를 사용하여 BaseModel 에서 플러그인의 동작을 수정할 수 있습니다. 이 인수는 모든 플러그인에 그대로 전달될 설정 사전을 사용합니다. 그런 다음 플러그인은 이러한 설정을 사용하여 동작을 수정할 수 있습니다. 플러그인이 자신의 설정을 plugin_settings 사전의 플러그인 특정 키에 있는 자체 전용 키로 분리하는 것이 좋습니다.

from pydantic import BaseModel


class Foo(BaseModel, plugin_settings={'my-plugin': {'observe': 'all'}}): ...

플러그인 빌드

??? api "API 문서" [pydantic.plugin][pydantic.플러그인]

Pydantic은 플러그인 생성을 위한 API를 제공합니다. API는 pydantic.plugin 모듈을 통해 노출됩니다.

플러그인에서 다음 메소드를 래핑 할 수 있습니다:

  • validate_python: Python 객체에서 데이터의 유효성을 검사하는 데 사용됩니다.
  • validate_json: JSON 문자열에서 데이터의 유효성을 검사하는 데 사용됩니다.
  • validate_strings: 문자열에서 데이터의 유효성을 검사하는 데 사용됩니다.

각 메서드에 대해 다음 콜백을 구현할 수 있습니다.

  • on_enter : 필드 유효성 검사가 시작되기 전에 호출됩니다.
  • on_success : 필드 유효성 검사가 성공하면 호출됩니다.
  • on_error : 필드 유효성 검사에 실패하면 호출됩니다.

SchemaValidatorvalidate_python 메서드를 래핑하는 플러그인의 예를 살펴보겠습니다.

from typing import Any, Dict, Optional, Union

from pydantic_core import CoreConfig, CoreSchema, ValidationError

from pydantic.plugin import (
    NewSchemaReturns,
    PydanticPluginProtocol,
    SchemaKind,
    SchemaTypePath,
    ValidatePythonHandlerProtocol,
)


class OnValidatePython(ValidatePythonHandlerProtocol):
    def on_enter(
        self,
        input: Any,
        *,
        strict: Optional[bool] = None,
        from_attributes: Optional[bool] = None,
        context: Optional[Dict[str, Any]] = None,
        self_instance: Optional[Any] = None,
    ) -> None:
        print(input)

    def on_success(self, result: Any) -> None:
        print(result)

    def on_error(self, error: ValidationError) -> None:
        print(error.json())


class Plugin(PydanticPluginProtocol):
    def new_schema_validator(
        self,
        schema: CoreSchema,
        schema_type: Any,
        schema_type_path: SchemaTypePath,
        schema_kind: SchemaKind,
        config: Union[CoreConfig, None],
        plugin_settings: Dict[str, object],
    ) -> NewSchemaReturns:
        return OnValidatePython(), None, None


plugin = Plugin()

플러그인 설정 사용

"observer"라는 설정이라는 플러그인이 있다고 가정하면 다음과 같이 사용할 수 있습니다.

from pydantic import BaseModel


class Foo(BaseModel, plugin_settings={'observer': 'all'}): ...

각 유효성 검사 호출에서 plugin_settings 이벤트에 등록된 콜러블에 전달됩니다.

플러그인 비활성화

환경 변수 PYDANTIC_DISABLE_PLUGINS 사용하여 전체 또는 특정 플러그인을 비활성화할 수 있습니다.


환경변수

허용되는 값

설명
PYDANTIC_DISABLE_PLUGINS
__all__ , 1 , true

모든 플러그인을 비활성화합니다.

쉼표로 구분된 문자열(예: my-plugin-1,my-plugin2 )

지정된 플러그인을 비활성화합니다.

本文总阅读量