콘텐츠로 이동

비밀

!!! 경고 "🚧 작업 진행 중" 이 페이지는 진행 중인 작업입니다.

SecretStrSecretBytes 일반 텍스트로 직렬화

기본적으로 SecretStrSecretBytes는 json으로 직렬화할 때 ********** 로 직렬화됩니다.

[field_serializer][pydantic.function_serializers.field_serializer]를 사용하여 json으로 직렬화할 때 비밀을 일반 텍스트로 덤프할 수 있습니다.

from pydantic import BaseModel, SecretBytes, SecretStr, field_serializer


class Model(BaseModel):
    password: SecretStr
    password_bytes: SecretBytes

    @field_serializer('password', 'password_bytes', when_used='json')
    def dump_secret(self, v):
        return v.get_secret_value()


model = Model(password='IAmSensitive', password_bytes=b'IAmSensitiveBytes')
print(model)
#> password=SecretStr('**********') password_bytes=SecretBytes(b'**********')
print(model.password)
#> **********
print(model.model_dump())
"""
{
    'password': SecretStr('**********'),
    'password_bytes': SecretBytes(b'**********'),
}
"""
print(model.model_dump_json())
#> {"password":"IAmSensitive","password_bytes":"IAmSensitiveBytes"}

나만의 비밀 필드 만들기

Pydantic은 사용자 정의 비밀 유형을 생성하기 위한 메커니즘으로 일반 Secret 클래스를 제공합니다.

??? api "API 문서" [pydantic.types.Secret][pydantic.types.비밀]

Pydantic은 사용자 정의 비밀 유형을 생성하기 위한 메커니즘으로 일반 Secret 클래스를 제공합니다. Secret 직접 매개변수화하거나 매개변수화된 Secret 에서 하위 클래스를 만들어 비밀 유형의 str()repr() 사용자 정의할 수 있습니다.

from datetime import date

from pydantic import BaseModel, Secret

# Using the default representation
SecretDate = Secret[date]


# Overwriting the representation
class SecretSalary(Secret[float]):
    def _display(self) -> str:
        return '$****.**'


class Employee(BaseModel):
    date_of_birth: SecretDate
    salary: SecretSalary


employee = Employee(date_of_birth='1990-01-01', salary=42)

print(employee)
#> date_of_birth=Secret('**********') salary=SecretSalary('$****.**')

print(employee.salary)
#> $****.**

print(employee.salary.get_secret_value())
#> 42.0

print(employee.date_of_birth)
#> **********

print(employee.date_of_birth.get_secret_value())
#> 1990-01-01

주석을 통해 기본 유형에 제약 조건을 적용할 수 있습니다. 예를 들면 다음과 같습니다.

from typing_extensions import Annotated

from pydantic import BaseModel, Field, Secret, ValidationError

SecretPosInt = Secret[Annotated[int, Field(gt=0, strict=True)]]


class Model(BaseModel):
    sensitive_int: SecretPosInt


m = Model(sensitive_int=42)
print(m.model_dump())
#> {'sensitive_int': Secret('**********')}

try:
    m = Model(sensitive_int=-42)  # (1)!
except ValidationError as exc_info:
    print(exc_info.errors(include_url=False, include_input=False))
    """
    [
        {
            'type': 'greater_than',
            'loc': ('sensitive_int',),
            'msg': 'Input should be greater than 0',
            'ctx': {'gt': 0},
        }
    ]
    """

try:
    m = Model(sensitive_int='42')  # (2)!
except ValidationError as exc_info:
    print(exc_info.errors(include_url=False, include_input=False))
    """
    [
        {
            'type': 'int_type',
            'loc': ('sensitive_int',),
            'msg': 'Input should be a valid integer',
        }
    ]
    """
  1. 입력값이 0보다 크지 않아 유효성 검사 오류가 발생합니다.
  2. 입력 값이 정수가 아니므로 SecretPosInt 유형에 엄격 모드가 활성화되어 있으므로 유효성 검사 오류가 발생합니다.

本文总阅读量