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. contract 在 python 3.12 · linux alpine/x64 …

sha256:3ea42df47255426affc822fffa2fe475b71a881239b1db84e637d566bf47ae93

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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