사용자 지정 데이터 형식 및 설정
사용자 지정 Pydantic 데이터 형식을 정의하고 Pydantic의 `BaseSettings`를 사용하여 애플리케이션 설정을 관리합니다.
사용자 지정 데이터 형식 및 설정은(는) CoddyKit의 무료 FastAPI Backend Development Bootcamp 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 FastAPI Backend Development Bootcamp 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. FastAPI Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Welcome to Custom Types!
Pydantic is great for validating data, but sometimes you need validation beyond its built-in types.
- Custom Data Types let you define your own rules for data.
- This ensures your data adheres to specific formats or business logic.
- Think of it as extending Pydantic's power for unique needs.
`Annotated` for Custom Validation
Pydantic v2 uses Python's typing.Annotated alongside validator functions to create custom types.
Annotated: Adds metadata to a type hint.BeforeValidator: Runs a function before Pydantic's standard validation.- This allows you to transform or validate input data before it's assigned.
Crafting a `CapitalizedString`
Let's create a custom type called CapitalizedString that ensures the first letter of a string is always uppercase.
Our validator function will check this rule. If the string isn't capitalized, it will raise an error.
Using Your Custom Type
Here's how to define and use our new CapitalizedString type in a Pydantic model. Try changing the name to start with a lowercase letter to see the validation error!
from typing import Annotated
from pydantic import BaseModel, BeforeValidator, ValidationError
def validate_capitalized(v: str) -> str:
if not isinstance(v, str):
raise TypeError("String required")
if v and not v[0].isupper():
raise ValueError("Must start with uppercase")
return v
CapitalizedString = Annotated[str, BeforeValidator(validate_capitalized)]
class Product(BaseModel):
name: CapitalizedString
price: float
if __name__ == "__main__":
try:
product1 = Product(name="Laptop", price=1200.50)
print(f"Product: {product1.name}")
# This will raise a ValidationError
# product2 = Product(name="keyboard", price=75.00)
except ValidationError as e:
print(f"Validation Error: {e}")Manage Settings with `BaseSettings`
Application settings (like database URLs, API keys) often change between development and production environments.
BaseSettings, from pydantic-settings, is designed to manage these configurations easily. It automatically loads settings from:
- Environment variables
.envfiles- Default values
Default Settings in Action
Define your settings as attributes in a class inheriting from BaseSettings. Pydantic handles the rest, providing default values if nothing else is specified.
from pydantic_settings import BaseSettings
class AppConfig(BaseSettings):
app_name: str = "My FastAPI App"
debug_mode: bool = False
version: str = "1.0.0"
if __name__ == "__main__":
settings = AppConfig()
print(f"App Name: {settings.app_name}")
print(f"Debug Mode: {settings.debug_mode}")
print(f"Version: {settings.version}")Loading from Environment Variables
BaseSettings automatically looks for environment variables that match your setting names (case-insensitive).
In this example, we temporarily set an environment variable to demonstrate how Pydantic picks it up, overriding the default.
import os
from pydantic_settings import BaseSettings
class AppConfig(BaseSettings):
app_name: str = "Default App"
database_url: str = "sqlite:///./test.db"
if __name__ == "__main__":
print("--- Without env var ---")
settings_default = AppConfig()
print(f"App Name: {settings_default.app_name}")
# Simulate setting an environment variable
os.environ["APP_NAME"] = "Production App"
os.environ["DATABASE_URL"] = "postgresql://user:pass@host:5432/db"
print("\n--- With env var ---")
settings_env = AppConfig()
print(f"App Name: {settings_env.app_name}")
print(f"DB URL: {settings_env.database_url}")
# Clean up the environment variable for subsequent runs
del os.environ["APP_NAME"]
del os.environ["DATABASE_URL"]Leveraging `.env` Files
For local development, it's common to store settings in a .env file (e.g., .env) in your project root.
You can configure BaseSettings to load from this file using SettingsConfigDict(env_file='.env') in your settings class.
Example .env content:APP_NAME="Dev App"
API_KEY="your_dev_api_key"
from pydantic_settings import BaseSettings, SettingsConfigDict
class ProjectSettings(BaseSettings):
model_config = SettingsConfigDict(env_file='.env', extra='ignore')
app_name: str = "Default Project"
api_key: str = "default_key"
# To make this runnable, you would need python-dotenv installed
# and an actual .env file in the same directory as the script.
# For this lesson, we show the setup.
# Example usage (if .env existed and python-dotenv was active):
# if __name__ == "__main__":
# settings = ProjectSettings()
# print(f"App Name: {settings.app_name}")
# print(f"API Key: {settings.api_key}")
Understanding Settings Priority
When BaseSettings looks for a value, it follows a specific order of precedence:
- Environment variables (highest priority)
.envfile variables- Default values defined in the
BaseSettingsclass (lowest priority)
This ensures that environment variables can always override local .env files and class defaults, which is crucial for deployment.
Test Your Knowledge!
Which of the following are true about Pydantic's BaseSettings and custom types?
Recap: Custom Types & Settings
Great job! You've learned how to create powerful custom data types with Annotated and BeforeValidator, extending Pydantic's validation.
You also mastered BaseSettings for robust application configuration, understanding how it loads values from defaults, .env files, and environment variables with clear priority rules.
These tools are essential for building flexible and maintainable FastAPI applications!
자주 묻는 질문
“사용자 지정 데이터 형식 및 설정” 강의는 무료인가요?
네 — “사용자 지정 데이터 형식 및 설정” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 FastAPI Backend Development Bootcamp 강의 전체를 잠금 해제할 수 있습니다. FastAPI Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.
“사용자 지정 데이터 형식 및 설정”에서 뭘 배우나요?
사용자 지정 Pydantic 데이터 형식을 정의하고 Pydantic의 `BaseSettings`를 사용하여 애플리케이션 설정을 관리합니다. 브라우저에서 직접 실행하는 실습 코드로 FastAPI Backend Development Bootcamp을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
FastAPI Backend Development Bootcamp을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 FastAPI Backend Development Bootcamp은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“사용자 지정 데이터 형식 및 설정” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 FastAPI Backend Development Bootcamp 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 FastAPI Backend Development Bootcamp 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Pydantic 필드 검증 및 검증기
- 사용자 지정 데이터 형식 및 설정
- 중첩 모델 및 재귀 구조
- model_dump와 별칭을 활용한 직렬화