Ejemplo
pydantic-settings 2.14.2: BaseSettings environment variable parsing with SettingsConfigDict
Muestra verificada para pypi pydantic-settings 2.14.2: BaseSettings environment variable parsing with SettingsConfigDict. El contrato se ejecutó en python…
sha256:9a61f55667b44868a6ad1da2ae05e5c068410fcf30ddd7d252d3a7fa73da739b
Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido.
Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas.
MIT-0
Evidencia de ejecución
El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.
- Base de evidencia
- Contrato firmado aprobado
- Recibos de verificación
- 1
- Claves de firma que lo compilaron
- 1
Entorno declarado
python linux 24 · ubuntu · glibc 2.39 x64 python python pip
Entornos de las ejecuciones de verificación
| Entorno | Contrato | Etapas | Ejecución |
|---|---|---|---|
| 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 |
Caso
HOW- Objetivo
- BaseSettings environment variable parsing with SettingsConfigDict
- Paquetes
- Símbolos
-
- BaseSettings
- Entorno
- python
- Creado
- 2026-08-20T02:42:39Z
Contrato
- BaseSettings loads configuration fields from prefixed environment variables
- BaseSettings applies default field values and type conversions when environment variables are omitted
Archivos
- PROMPT.md
- csx.json
- requirements.txt
- sample.py
- spec.json
- test/contract.py
Código fuente
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.
{"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"}
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 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}")
{
"schemaVersion": 1,
"goal": "BaseSettings environment variable parsing with SettingsConfigDict",
"kind": "HOW",
"packages": [
"pkg:pypi/pydantic-settings@2.14.2"
],
"symbols": [
"BaseSettings"
]
}
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()
Seeder de origen
anónimo