0Pricing
FastAPI Backend Development Bootcamp · Lekcja

Niestandardowe typy danych i ustawienia

Zdefiniują Państwo niestandardowe typy danych Pydantic i będą zarządzać ustawieniami aplikacji za pomocą `BaseSettings` biblioteki Pydantic.

Niestandardowe typy danych i ustawienia to bezpłatna lekcja FastAPI Backend Development Bootcamp na CoddyKit. To lekcja 2 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej FastAPI Backend Development Bootcamp, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs FastAPI Backend Development Bootcamp zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

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
  • .env files
  • 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:

  1. Environment variables (highest priority)
  2. .env file variables
  3. Default values defined in the BaseSettings class (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!

Często zadawane pytania

Czy lekcja „Niestandardowe typy danych i ustawienia” jest bezpłatna?

Tak — pełny tekst „Niestandardowe typy danych i ustawienia” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu FastAPI Backend Development Bootcamp, przejdź na CoddyKit PRO. Kurs FastAPI Backend Development Bootcamp zawiera 4 lekcji w sumie.

Co nauczysz się w „Niestandardowe typy danych i ustawienia”?

Zdefiniują Państwo niestandardowe typy danych Pydantic i będą zarządzać ustawieniami aplikacji za pomocą `BaseSettings` biblioteki Pydantic. Ćwiczysz FastAPI Backend Development Bootcamp z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć FastAPI Backend Development Bootcamp?

Nie wymagamy żadnego doświadczenia. FastAPI Backend Development Bootcamp w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 2 z 4.

Ile czasu zajmuje lekcja „Niestandardowe typy danych i ustawienia”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji FastAPI Backend Development Bootcamp?

Tak. Każda lekcja FastAPI Backend Development Bootcamp zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Walidacja pól Pydantic i walidatory
  2. Niestandardowe typy danych i ustawienia
  3. Modele zagnieżdżone i struktury rekurencyjne
  4. Serializacja za pomocą model_dump i aliasów
← Powrót do FastAPI Backend Development Bootcamp