Performance: Configuration management
This affects the startup time and runtime efficiency of the FastAPI app by managing how configuration data is loaded and accessed.
from fastapi import FastAPI import json app = FastAPI() with open('config.json') as f: config = json.load(f) @app.get('/') async def root(): return {"message": config['welcome_message']}
from fastapi import FastAPI import json app = FastAPI() def get_config(): with open('config.json') as f: return json.load(f) @app.get('/') async def root(): config = get_config() return {"message": config['welcome_message']}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Load config per request | N/A | N/A | Blocks server response causing delayed paint | [X] Bad |
| Load config once at startup | N/A | N/A | Fast server response enables quicker paint | [OK] Good |
pydantic.BaseSettings in a FastAPI application?pydantic.BaseSettingsBaseSettings is designed to load configuration values from environment variables or .env files.BaseSettings.pydantic.BaseSettings?BaseSettings to load environment variables.API_KEY=secret123 set, what will print(settings.api_key) output?
from pydantic import BaseSettings
class Settings(BaseSettings):
api_key: str
settings = Settings()BaseSettings automatically reads environment variables matching attribute names in uppercase.API_KEY is setAPI_KEY=secret123 is set, so settings.api_key will be 'secret123'.from pydantic import BaseSettings
class Settings(BaseSettings):
debug: bool = False
settings = Settings(debug="foo")debug attribute expects a boolean, but the code passes a string "foo"..env file and override some values with environment variables in FastAPI. Which approach correctly achieves this using pydantic.BaseSettings?BaseSettings loads .env files when env_file='.env' is set in the inner Config class.class Config: env_file = '.env' and place a .env file in the project root; environment variables override .env values automatically -> Option APass the test and this pattern moves unknown