CodeSampleX

샘플

pydantic 2.13.4: Replace pydantic v1 parse_obj/dict with the v2 model_validate/model_dump API

검증된 샘플 — pypi pydantic 2.13.4: Replace pydantic v1 parse_obj/dict with the v2 model_validate/model_dump API. python 3.12 · linux alpine/x64 · docker에서…

sha256:3ea42df47255426affc822fffa2fe475b71a881239b1db84e637d566bf47ae93

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
2
빌드한 서명 키
2
선언된 환경 python 3.12 linux x64 python 3.12 python pip

검증 실행 환경

환경 컨트랙트 단계 실행일
python 3.12 · linux alpine/x64 · docker ed25519:a2ec939a4c60e243 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-13
python 3.12 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-17

케이스

MIGRATION
목표
Replace pydantic v1 parse_obj/dict with the v2 model_validate/model_dump API
패키지
심벌
  • BaseModel.model_validate
  • BaseModel.model_dump
  • ValidationError
환경
python 3.12
생성일
2026-08-13T15:47:11Z

컨트랙트

  1. define a model and validate a correct payload with model_validate
  2. assert the v1 helpers still exist but warn, so a silent upgrade is not a completed migration
  3. assert an invalid payload raises ValidationError with a typed error list
  4. assert model_dump returns plain data

파일

  • csx.json
  • requirements.txt
  • src/__init__.py
  • src/models.py
  • test/contract.py

소스 아티팩트 내려받기 (tar.gz)

소스

csx.json
{"case":{"caseId":"case:sha256:847c47b53bfbe275a04f1c89c11fee352a20506a7c25dda57382f37eb96875a4","constraints":{"runtime":"python"},"contract":["define a model and validate a correct payload with model_validate","assert the v1 helpers still exist but warn, so a silent upgrade is not a completed migration","assert an invalid payload raises ValidationError with a typed error list","assert model_dump returns plain data"],"goal":"Replace pydantic v1 parse_obj/dict with the v2 model_validate/model_dump API","kind":"MIGRATION","packages":["pkg:pypi/pydantic@2.13.4"],"schemaVersion":1,"symbols":["BaseModel.model_validate","BaseModel.model_dump","ValidationError"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","ecosystem":"pypi","executionContext":"python","language":"python","os":"linux","packageManager":"pip","runtime":"python","runtimeVersion":"3.12","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/pydantic@2.13.4"],"schemaVersion":1,"symbols":["BaseModel.model_validate","BaseModel.model_dump","ValidationError"],"verifierAdapter":"python@1"}
requirements.txt
pydantic==2.13.4
pydantic-core==2.46.4
typing-extensions==4.16.0
annotated-types==0.8.0
typing-inspection==0.4.4
src/__init__.py
src/models.py
"""pydantic v2 validation, with the v1 names that no longer exist."""

from pydantic import BaseModel, Field, ValidationError


class Peer(BaseModel):
    peer_id: str = Field(min_length=3)
    port: int = Field(ge=1, le=65535)
    tags: list[str] = []


def validate(payload):
    """Validate a dict into a Peer.

    v2 renamed the whole surface: parse_obj -> model_validate,
    parse_raw -> model_validate_json, .dict() -> .model_dump(),
    .json() -> .model_dump_json(). The old names still resolve as
    deprecated shims, so a v1 codebase keeps running after the upgrade and
    the migration looks finished when it is not — the warnings are the
    only signal, and they are easy to filter away.
    """
    return Peer.model_validate(payload)


def errors_for(payload):
    """Return the structured error list for an invalid payload."""
    try:
        Peer.model_validate(payload)
    except ValidationError as exc:
        return exc.errors()
    return []
test/contract.py
import os
import sys
import warnings

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from src.models import Peer, errors_for, validate

peer = validate({"peer_id": "ed25519:abc", "port": 48620, "tags": ["blob"]})
assert peer.peer_id == "ed25519:abc"
assert peer.port == 48620

# v2 returns plain data from model_dump; .dict() is gone.
assert validate({"peer_id": "abc", "port": 1}).model_dump() == {
    "peer_id": "abc", "port": 1, "tags": []
}
# The v1 names still EXIST in v2 as deprecated shims — they do not raise
# AttributeError, they warn. That is why a v1 codebase keeps working after
# the upgrade while quietly accruing deprecation debt, and why "it still
# runs" is not evidence that the migration is done.
with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    legacy = Peer.parse_obj({"peer_id": "ed25519:ghi", "port": 2})
    assert legacy.port == 2
    assert any(issubclass(w.category, DeprecationWarning) for w in caught),         "parse_obj should warn in v2"

errs = errors_for({"peer_id": "ab", "port": 99999})
codes = sorted(e["type"] for e in errs)
assert len(errs) == 2, errs
assert all("loc" in e and "msg" in e for e in errs)
assert codes == ["less_than_equal", "string_too_short"], codes

print("CONTRACT PASS: pydantic v2 validated, dumped and reported typed errors")

오리진 시더

anonymous