FastAPI अनुप्रयोग pydantic-settings (BaseSettings) सह configuration व्यवस्थापित करतात — एक वर्ग जो environment variables (आणि .env files) पासून config वाचतो सह, secrets कोडच्या बाहेर ठेवतो आणि startup वर config योग्य असल्याची खात्री करतो.
FastAPI अनुप्रयोग pydantic-settings (BaseSettings) सह configuration व्यवस्थापित करतात — एक वर्ग जो environment variables (आणि .env files) पासून config वाचतो सह, secrets कोडच्या बाहेर ठेवतो आणि startup वर config योग्य असल्याची खात्री करतो.
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
app_name: str = "My API"
database_url: str # required — must be provided
secret_key: str # required (a secret)
debug: bool = False
max_connections: int = 10
class Config:
env_file = ".env" # also read from a .env file
settings = Settings() # reads & VALIDATES env vars at startup
BaseSettings स्वयंचलितपणे प्रत्येक field हे जुळणारे environment variable (उदा. DATABASE_URL) पासून वाचतो, types रूपांतरित करतो ("true" → bool, "10" → int), आणि validates करतो — एक missing required value किंवा wrong type लगेच startup वर स्पष्ट error सह अयशस्वी होते (fail-fast).
from functools import lru_cache
from fastapi import Depends
@lru_cache # create the Settings once (cached)
def get_settings():
return Settings()
@app.get("/info")
def info(settings: Settings = Depends(get_settings)):
return {"app": settings.app_name, "debug": settings.debug}
Cached dependency द्वारे settings inject करणे त्यांना testable बनवते (tests मध्ये override करा) आणि एकल instance सुनिश्चित करते.
# .env — local config, GITIGNORED (never commit secrets)
DATABASE_URL=postgresql://localhost/mydb
SECRET_KEY=dev-secret
DEBUG=true
✓ Keep secrets in env vars / .env (gitignored); commit a .env.example documenting keys
✓ In production, inject config via the platform's environment / secret manager
✓ Validation at startup catches misconfiguration immediately (not deep in a request)
योग्य settings management हे operational necessity (apps ला dev/staging/production व्यापी वेगवेगळे config आवश्यक आहे) आणि security requirement (database URLs आणि keys सारखे secrets हे कधीही source control मध्ये hardcoded असू शकत नाहीत — एक सामान्य, गंभीर breach) दोन्ही आहे.
Pydantic चा BaseSettings idiomatic FastAPI solution प्रदान करतो, आणि त्याची समज महत्वाचे दैनंदिन ज्ञान आहे.
त्याचे मुख्य फायदे: environment variables पासून config वाचणे (secrets कोडच्या बाहेर ठेवणे, twelve-factor approach) स्वयंचलित type conversion आणि validation सह — म्हणून misconfiguration startup वर स्पष्ट error सह fail करते त्याऐवजी confusing runtime failure म्हणून.
Dependency injection (settings testable आणि singleton बनवणे) आणि local development साठी gitignored .env files च्या सराव सह, हे तुम्हाला safe, validated, environment-appropriate configuration देते.
Settings परिभाषित करणे, त्यांचा DI द्वारे वापर करणे, आणि secrets securely हँडल करणे कसे हे जाणून घेणे हे production-ready FastAPI applications बांधण्यासाठी मूलभूत आहे.