Gestione delle variabili d’ambiente e dei secret
Impari a configurare FastAPI in sicurezza per ambienti diversi usando variabili d’ambiente e la gestione dei secret.
Gestione delle variabili d’ambiente e dei secret è una lezione FastAPI Backend Development Bootcamp gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento FastAPI Backend Development Bootcamp, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso FastAPI Backend Development Bootcamp include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
Why Externalize Configuration?
Hardcoding database URLs, API keys, or debug flags into your code is dangerous and inflexible.
The 12-factor app approach stores configuration in the environment, so the same image runs in dev, staging, and production with different settings.
Reading Environment Variables
Python reads variables via os.environ or os.getenv with a default.
import os
DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./dev.db")
DEBUG = os.getenv("DEBUG", "false").lower() == "true"Pydantic Settings
FastAPI projects commonly use pydantic-settings to load and validate config into a typed object.
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
database_url: str
secret_key: str
debug: bool = FalseLoading from a .env File
Configure the settings class to read a local .env file during development.
class Settings(BaseSettings):
database_url: str
secret_key: str
class Config:
env_file = ".env"Caching the Settings Object
Use lru_cache so settings are parsed once and reused as a dependency.
from functools import lru_cache
@lru_cache
def get_settings() -> Settings:
return Settings()Injecting Settings into Routes
Treat settings as a FastAPI dependency for clean access and easy testing.
from fastapi import Depends
@app.get("/info")
def info(settings: Settings = Depends(get_settings)):
return {"debug": settings.debug}Never Commit Secrets
Add .env to .gitignore. Committed secrets are extremely hard to fully remove from git history and may leak credentials.
# .gitignore
.env
*.pem
secrets/Production Secret Stores
In production, prefer a managed secret store over plain files:
- AWS Secrets Manager or Parameter Store
- HashiCorp Vault
- Docker or Kubernetes secrets
These inject secrets at runtime without writing them to disk in plain text.
Different Configs per Environment
Use a single variable like ENV to branch behavior, keeping all values in the environment.
ENV = os.getenv("ENV", "development")
if ENV == "production":
LOG_LEVEL = "warning"
else:
LOG_LEVEL = "debug"Validating Required Variables
Pydantic settings raise a clear error at startup if a required variable is missing, failing fast instead of crashing later.
try:
settings = Settings()
except Exception as e:
print("Config error:", e)
raiseTyped Lists and Nested Config
Settings can parse complex values too, like comma-separated origins into a list, keeping parsing logic out of your routes.
class Settings(BaseSettings):
cors_origins: list[str] = []
# CORS_ORIGINS=https://a.com,https://b.comQuick Check
Test your configuration knowledge.
Recap
You learned to manage configuration safely:
- Read config from the environment, not source code
- Use pydantic-settings for typed, validated config
- Never commit
.env; use a secret store in production
Solid config management keeps deployments portable and secure.
Domande Frequenti
La lezione «Gestione delle variabili d’ambiente e dei secret» è gratuita?
Sì — il testo completo di «Gestione delle variabili d’ambiente e dei secret» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso FastAPI Backend Development Bootcamp, passa a CoddyKit PRO. Il corso FastAPI Backend Development Bootcamp include 4 lezioni in totale.
Cosa imparerò in «Gestione delle variabili d’ambiente e dei secret»?
Impari a configurare FastAPI in sicurezza per ambienti diversi usando variabili d’ambiente e la gestione dei secret. Eserciti FastAPI Backend Development Bootcamp con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare FastAPI Backend Development Bootcamp?
Non è richiesta alcuna esperienza precedente. FastAPI Backend Development Bootcamp su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Gestione delle variabili d’ambiente e dei secret»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione FastAPI Backend Development Bootcamp?
Sì. Ogni lezione FastAPI Backend Development Bootcamp include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Creare container per applicazioni FastAPI
- Deployment con Gunicorn e Uvicorn
- Strategie di deployment sul cloud
- Gestione delle variabili d’ambiente e dei secret