CodeSampleX

サンプル

pydantic-settings 2.14.2: BaseSettings environment variable parsing with SettingsConfigDict

検証済みサンプル — pypi pydantic-settings 2.14.2: BaseSettings environment variable parsing with SettingsConfigDict. python 3.12 · linux alpine/x64 · docker で…

sha256:9a61f55667b44868a6ad1da2ae05e5c068410fcf30ddd7d252d3a7fa73da739b

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
1
ビルドした署名鍵
1
宣言された環境 python linux 24 · ubuntu · glibc 2.39 x64 python python pip

検証実行環境

環境 コントラクト ステージ 実行日
python 3.12 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-20

ケース

HOW
ゴール
BaseSettings environment variable parsing with SettingsConfigDict
パッケージ
シンボル
  • BaseSettings
環境
python
作成日
2026-08-20T02:42:39Z

コントラクト

  1. BaseSettings loads configuration fields from prefixed environment variables
  2. BaseSettings applies default field values and type conversions when environment variables are omitted

ファイル

  • 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: BaseSettings environment variable parsing with SettingsConfigDict
Kind: HOW

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

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:453d62c79ca483f013310489e16953c0a132cfd1118a66db4ff3a15199fbdc6a","contract":["BaseSettings loads configuration fields from prefixed environment variables","BaseSettings applies default field values and type conversions when environment variables are omitted"],"goal":"BaseSettings environment variable parsing with SettingsConfigDict","kind":"HOW","packages":["pkg:pypi/pydantic-settings@2.14.2"],"schemaVersion":1,"symbols":["BaseSettings"]},"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":["BaseSettings"],"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 environment variable parsing using Pydantic Settings."""

from typing import List
from pydantic import Field
from pydantic_settings import BaseSettings, SettingsConfigDict


class DatabaseSettings(BaseSettings):
    """Database connection and pool configuration."""

    model_config = SettingsConfigDict(
        env_prefix="DB_",
        case_sensitive=False,
    )

    host: str = "localhost"
    port: int = 5432
    name: str = "app_db"
    pool_size: int = Field(default=10, ge=1, le=100)


class AppSettings(BaseSettings):
    """Application settings populated from environment variables."""

    model_config = SettingsConfigDict(
        env_prefix="APP_",
        case_sensitive=False,
    )

    app_name: str = "ExampleService"
    environment: str = "development"
    debug: bool = False
    allowed_hosts: List[str] = Field(default_factory=lambda: ["localhost", "127.0.0.1"])


def load_application_settings() -> AppSettings:
    """Instantiate and return the current AppSettings."""
    return AppSettings()


def load_database_settings() -> DatabaseSettings:
    """Instantiate and return the current DatabaseSettings."""
    return DatabaseSettings()


if __name__ == "__main__":
    app_cfg = load_application_settings()
    db_cfg = load_database_settings()
    print(f"Loaded {app_cfg.app_name} (env={app_cfg.environment}, debug={app_cfg.debug})")
    print(f"Database target: {db_cfg.host}:{db_cfg.port}/{db_cfg.name}")
spec.json
{
  "schemaVersion": 1,
  "goal": "BaseSettings environment variable parsing with SettingsConfigDict",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/pydantic-settings@2.14.2"
  ],
  "symbols": [
    "BaseSettings"
  ]
}
test/contract.py
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, DatabaseSettings, load_application_settings, load_database_settings


def test_environment_variable_override():
    # Assertion 1: BaseSettings loads configuration fields from prefixed environment variables
    os.environ["APP_APP_NAME"] = "CustomService"
    os.environ["APP_ENVIRONMENT"] = "production"
    os.environ["APP_DEBUG"] = "true"
    os.environ["APP_ALLOWED_HOSTS"] = '["api.example.com", "admin.example.com"]'

    os.environ["DB_HOST"] = "db.example.com"
    os.environ["DB_PORT"] = "5433"
    os.environ["DB_NAME"] = "custom_db"
    os.environ["DB_POOL_SIZE"] = "25"

    try:
        app_cfg = load_application_settings()
        assert app_cfg.app_name == "CustomService"
        assert app_cfg.environment == "production"
        assert app_cfg.debug is True
        assert app_cfg.allowed_hosts == ["api.example.com", "admin.example.com"]

        db_cfg = load_database_settings()
        assert db_cfg.host == "db.example.com"
        assert db_cfg.port == 5433
        assert db_cfg.name == "custom_db"
        assert db_cfg.pool_size == 25
    finally:
        # Clean up modified environment variables
        for key in [
            "APP_APP_NAME",
            "APP_ENVIRONMENT",
            "APP_DEBUG",
            "APP_ALLOWED_HOSTS",
            "DB_HOST",
            "DB_PORT",
            "DB_NAME",
            "DB_POOL_SIZE",
        ]:
            os.environ.pop(key, None)


def test_default_fallbacks_and_types():
    # Assertion 2: BaseSettings applies default field values and type conversions when environment variables are omitted
    for key in [
        "APP_APP_NAME",
        "APP_ENVIRONMENT",
        "APP_DEBUG",
        "APP_ALLOWED_HOSTS",
        "DB_HOST",
        "DB_PORT",
        "DB_NAME",
        "DB_POOL_SIZE",
    ]:
        os.environ.pop(key, None)

    app_cfg = load_application_settings()
    assert app_cfg.app_name == "ExampleService"
    assert app_cfg.environment == "development"
    assert app_cfg.debug is False
    assert app_cfg.allowed_hosts == ["localhost", "127.0.0.1"]

    db_cfg = load_database_settings()
    assert db_cfg.host == "localhost"
    assert db_cfg.port == 5432
    assert db_cfg.name == "app_db"
    assert db_cfg.pool_size == 10


def main():
    test_environment_variable_override()
    test_default_fallbacks_and_types()
    print("Contract verification passed.")


if __name__ == "__main__":
    main()

オリジンシーダー

匿名