CodeSampleX

샘플

pydantic-settings 2.14.2: Load configuration from JSON files using JsonConfigSettingsSource

검증된 샘플 — pypi pydantic-settings 2.14.2: Load configuration from JSON files using JsonConfigSettingsSource. python 3.12 · linux alpine/x64 · docker에서…

sha256:9e9078dad9ab1767420c64904a3ac1de5d21b21b877622ab1ee4b2c4690f29f3

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

실행 증거

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

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 python linux 24 · ubuntu · glibc 2.39 x64 python python pip

검증 실행 환경

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

케이스

HOW
목표
Load configuration from JSON files using JsonConfigSettingsSource
패키지
심벌
  • JsonConfigSettingsSource
환경
python
생성일
2026-08-20T02:46:11Z

컨트랙트

  1. JsonConfigSettingsSource loads configuration values from a JSON file
  2. JsonConfigSettingsSource allows init arguments to override values from the JSON file

파일

  • PROMPT.md
  • csx.json
  • requirements.txt
  • sample.py
  • spec.json
  • test/contract.py

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

소스

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: Load configuration from JSON files using JsonConfigSettingsSource
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/pydantic-settings@2.14.2
Demonstrate these symbols/APIs:
  - JsonConfigSettingsSource

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:0c39849db15b48ecab4b713717661808b254125a10d0a7c4e421e9bf6a3611bb","contract":["JsonConfigSettingsSource loads configuration values from a JSON file","JsonConfigSettingsSource allows init arguments to override values from the JSON file"],"goal":"Load configuration from JSON files using JsonConfigSettingsSource","kind":"HOW","packages":["pkg:pypi/pydantic-settings@2.14.2"],"schemaVersion":1,"symbols":["JsonConfigSettingsSource"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","language":"python","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/pydantic-settings@2.14.2"],"schemaVersion":1,"symbols":["JsonConfigSettingsSource"],"verifierAdapter":"python@1"}
requirements.txt
annotated-types==0.8.0
pydantic==2.13.4
pydantic-core==2.46.4
pydantic-settings==2.14.2
python-dotenv==1.2.3
typing-extensions==4.16.0
typing-inspection==0.4.4
sample.py
"""Sample demonstrating JSON configuration loading with JsonConfigSettingsSource in Pydantic Settings."""

from typing import Tuple, Type
from pydantic import BaseModel, Field
from pydantic_settings import (
    BaseSettings,
    JsonConfigSettingsSource,
    PydanticBaseSettingsSource,
    SettingsConfigDict,
)


class DatabaseConfig(BaseModel):
    """Database connection configuration."""

    host: str = "localhost"
    port: int = 5432
    database_name: str = "default_db"


class AppSettings(BaseSettings):
    """Application settings loaded from JSON file with fallback defaults and source customization."""

    model_config = SettingsConfigDict(
        json_file="config.json",
        json_file_encoding="utf-8",
    )

    app_name: str = "DefaultApp"
    environment: str = "development"
    debug: bool = False
    database: DatabaseConfig = Field(default_factory=DatabaseConfig)

    @classmethod
    def settings_customise_sources(
        cls,
        settings_cls: Type[BaseSettings],
        init_settings: PydanticBaseSettingsSource,
        env_settings: PydanticBaseSettingsSource,
        dotenv_settings: PydanticBaseSettingsSource,
        file_secret_settings: PydanticBaseSettingsSource,
    ) -> Tuple[PydanticBaseSettingsSource, ...]:
        """Customise settings sources to include JsonConfigSettingsSource."""
        return (
            init_settings,
            JsonConfigSettingsSource(settings_cls),
            env_settings,
            dotenv_settings,
            file_secret_settings,
        )


def load_application_settings(**kwargs) -> AppSettings:
    """Instantiate and return AppSettings."""
    return AppSettings(**kwargs)


if __name__ == "__main__":
    settings = load_application_settings()
    print(f"Loaded {settings.app_name} (env={settings.environment}, debug={settings.debug})")
    print(f"Database: {settings.database.host}:{settings.database.port}/{settings.database.database_name}")
spec.json
{
  "schemaVersion": 1,
  "goal": "Load configuration from JSON files using JsonConfigSettingsSource",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/pydantic-settings@2.14.2"
  ],
  "symbols": [
    "JsonConfigSettingsSource"
  ]
}
test/contract.py
import json
import os
import sys

# Ensure project root is on sys.path for local module imports
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from sample import AppSettings, load_application_settings


def test_json_config_loading():
    # Assertion 1: JsonConfigSettingsSource loads configuration values from a JSON file
    payload = {
        "app_name": "SampleJsonService",
        "environment": "staging",
        "debug": True,
        "database": {
            "host": "db.example.com",
            "port": 5433,
            "database_name": "service_db",
        },
    }

    config_path = "config.json"
    with open(config_path, "w", encoding="utf-8") as f:
        json.dump(payload, f)

    try:
        settings = load_application_settings()
        assert settings.app_name == "SampleJsonService"
        assert settings.environment == "staging"
        assert settings.debug is True
        assert settings.database.host == "db.example.com"
        assert settings.database.port == 5433
        assert settings.database.database_name == "service_db"
    finally:
        if os.path.exists(config_path):
            os.remove(config_path)


def test_init_arg_override_precedence():
    # Assertion 2: JsonConfigSettingsSource allows init arguments to override values from the JSON file
    payload = {
        "app_name": "BaseApp",
        "environment": "production",
        "debug": False,
        "database": {
            "host": "db.example.com",
            "port": 5432,
            "database_name": "prod_db",
        },
    }

    config_path = "config.json"
    with open(config_path, "w", encoding="utf-8") as f:
        json.dump(payload, f)

    try:
        settings = load_application_settings(
            app_name="OverriddenApp",
            debug=True,
        )
        assert settings.app_name == "OverriddenApp"
        assert settings.environment == "production"
        assert settings.debug is True
        assert settings.database.host == "db.example.com"
        assert settings.database.port == 5432
    finally:
        if os.path.exists(config_path):
            os.remove(config_path)


def main():
    test_json_config_loading()
    test_init_arg_override_precedence()
    print("Contract verification passed.")


if __name__ == "__main__":
    main()

오리진 시더

익명