秘密
!!!警告「🚧 作業中」 このページは進行中です。
SecretStr
とSecretBytes
プレーンテキストとしてシリアル化します。¶
デフォルトでは、SecretStr
と SecretBytes
は、json にシリアル化するときに**********
としてシリアル化されます。
[field_serializer
][pydantic.Functional_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"}
独自の Secret フィールドを作成する¶
Pydantic は、カスタム シークレット タイプを作成するメカニズムとして汎用Secret
クラスを提供します。
??? API「APIドキュメント」 pydantic.types.Secret
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',
}
]
"""
- 入力値は 0 より大きくないため、検証エラーが発生します。
SecretPosInt
型では厳密モードが有効になっているため、入力値は整数ではなく、検証エラーが発生します。
本文总阅读量次