Performance: Environment variable management
This affects the startup time and configuration loading speed of the FastAPI application.
import os from dotenv import load_dotenv load_dotenv() # called once at startup secret = os.getenv('SECRET_KEY') def read_root(): return {"secret": secret}
import os from dotenv import load_dotenv def read_root(): load_dotenv() # called inside a route handler secret = os.getenv('SECRET_KEY') return {"secret": secret}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Load env vars inside route | N/A | N/A | Blocks response start, delays paint | [X] Bad |
| Load env vars once at startup | N/A | N/A | Fast response start, no blocking | [OK] Good |
| Repeated os.getenv calls in handler | N/A | N/A | Minor CPU overhead, slight delay | [!] OK |
| Cache env vars in constants | N/A | N/A | Minimal overhead, fast response | [OK] Good |
API_KEY using Python's os module in FastAPI?os.getenv('VAR_NAME').os.getenv('API_KEY') correctly with quotes around the variable name and no extra parentheses.from pydantic import BaseSettings
class Settings(BaseSettings):
app_name: str
debug_mode: bool = False
settings = Settings()APP_NAME is set to "MyApp" and DEBUG_MODE is not set, what will settings.app_name and settings.debug_mode be?settings.app_name is "MyApp". DEBUG_MODE is not set, so it uses the default False.import os
API_KEY = os.getenv('API_KEY')
print(f"API key is {API_KEY.upper()}")API_KEY is not set in the environment.None.upper() raises an AttributeError because NoneType has no method upper().PORT is not set. Which code snippet correctly achieves this?port: int = 8000 provides a default if the environment variable PORT is missing.Settings() reads environment variables or uses defaults if missing, so port will be 8000 if PORT is unset.Pass the test and this pattern moves unknown