新手常写的代码:

api_key = "sk-xxxxx"
db_url = "postgresql://localhost:5432/mydb"
threshold = 0.5

看着没问题,改起来要命——换个环境(测试→生产)就得改源码。

正确做法:配置和代码分离。

最简单的方式用 yaml:

# config.yaml
api_key: sk-xxxxx
db_url: postgresql://localhost:5432/mydb
threshold: 0.5
redis:
  host: localhost
  port: 6379

代码里:

import yaml
with open("config.yaml") as f:
    config = yaml.safe_load(f)

api_key = config["api_key"]

进阶玩法:用 pydantic 做校验,配置错了启动就报错,不会跑到一半炸:

from pydantic import BaseSettings
class Settings(BaseSettings):
    api_key: str
    db_url: str
    threshold: float = 0.5
settings = Settings()

敏感配置(API key、数据库密码)用环境变量,别写进 yaml,别提交到 git。


本文由 BBZ · 小朵科技工作室 出品。