如何在Python各部署阶段使用不同配置文件?类比Java Maven方案
Great question! Managing different configs for Alpha, Beta, and Production environments is a common need, and Python has plenty of flexible ways to replicate Maven's approach. Here are the most practical methods I've used across projects of all sizes:
1. Basic Environment Variable + Custom Loading Logic (No Extra Dependencies)
This is the simplest approach if you don't want to add third-party packages. You'll rely on an environment variable to tell your app which config to load.
First, set an environment variable when starting your app (the exact command depends on your OS/deployment tool):
- For Linux/macOS:
export DEPLOY_ENV=alpha - For Windows (PowerShell):
$env:DEPLOY_ENV = "alpha"
Then, in your Python code:
import os import configparser # Fall back to production if no env is specified (safe default!) current_env = os.getenv("DEPLOY_ENV", "production") config_path = f"config.{current_env}.conf" # Load the config file config = configparser.ConfigParser() config.read(config_path) # Access your config values db_url = config.get("database", "url") api_port = config.getint("server", "port")
This works perfectly for small to medium projects where you want minimal overhead.
2. Use python-dotenv for Cleaner Env Management
If you prefer using .env files (super common for local development), the python-dotenv package makes it easy to load environment-specific files.
First, install the package:
pip install python-dotenv
Create .env.alpha, .env.beta, and .env.production files (each with your environment-specific values, e.g., DATABASE_URL=postgres://user:pass@alpha-db:5432/mydb).
Then in your code:
import os from dotenv import load_dotenv current_env = os.getenv("DEPLOY_ENV", "production") env_file = f".env.{current_env}" # Load the environment-specific .env file load_dotenv(env_file) # Access values directly via os.getenv db_url = os.getenv("DATABASE_URL") api_key = os.getenv("API_SECRET_KEY")
This is great for teams that want consistent local development setups and easy deployment.
3. Modern Type-Safe Configs with pydantic-settings
For larger, more complex projects, pydantic-settings (part of the Pydantic ecosystem) adds type safety, validation, and automatic loading—perfect for avoiding config bugs.
Install the package first:
pip install pydantic-settings
Then define your settings class, which automatically loads the right config based on the environment variable:
import os from pydantic_settings import BaseSettings, SettingsConfigDict class AppSettings(BaseSettings): database_url: str server_port: int api_secret: str # Tell Pydantic which config file to use model_config = SettingsConfigDict( env_file=f"config.{os.getenv('DEPLOY_ENV', 'production')}.conf", env_file_encoding="utf-8" ) # Initialize settings (Pydantic will validate values automatically!) settings = AppSettings() # Use your typed settings print(f"Connecting to DB: {settings.database_url}") print(f"Starting server on port: {settings.server_port}")
Pydantic will throw clear errors if a config value is missing or of the wrong type—super helpful for catching issues early.
4. CI/CD & Deployment Automation
If you're using a CI/CD pipeline (like GitHub Actions, GitLab CI), you can automate copying the right config file before deployment. For example, a simple Makefile to streamline commands:
deploy-alpha: export DEPLOY_ENV=alpha && \ cp config.alpha.conf config.active.conf && \ python app.py deploy-beta: export DEPLOY_ENV=beta && \ cp config.beta.conf config.active.conf && \ python app.py deploy-prod: export DEPLOY_ENV=production && \ cp config.production.conf config.active.conf && \ python app.py
Then just run make deploy-alpha to deploy to your Alpha environment—no manual config switching needed.
内容的提问来源于stack exchange,提问作者Won-Sik Kim

