管理环境变量与密钥
学习如何使用环境变量和密钥管理,安全地为不同环境配置 FastAPI。
管理环境变量与密钥 是 CoddyKit 上的免费 FastAPI Backend Development Bootcamp 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 FastAPI Backend Development Bootcamp 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 FastAPI Backend Development Bootcamp 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
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.
用 AI 导师学习 FastAPI Backend Development Bootcamp — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 21
- 课程
- 84
常见问题解答
「管理环境变量与密钥」课时是免费的吗?
是的 — 「管理环境变量与密钥」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 FastAPI Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 FastAPI Backend Development Bootcamp 课程共包含 4 节课。
「管理环境变量与密钥」这节课中我会学到什么?
学习如何使用环境变量和密钥管理,安全地为不同环境配置 FastAPI。 你通过在浏览器中直接运行的动手代码来练习 FastAPI Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 FastAPI Backend Development Bootcamp 需要有经验吗?
无需任何先前经验。CoddyKit 上的 FastAPI Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「管理环境变量与密钥」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 FastAPI Backend Development Bootcamp 课中编写并运行代码吗?
能。每节 FastAPI Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。