环境配置管理

使用pydantic的BaseSettings

  1. 类型校验
  2. 整合dotenv
import os

from pydantic import BaseSettings


class Settings(BaseSettings):
    API_BASE: str
    DB_HOST: str = 'localhost'
    DB_PORT: int = 8888
    DB_NAME: str
    TESTING: bool = False


class Production(Settings):
    API_BASE = 'https://example.com/api'
    DB_NAME = 'production'


class Testing(Settings):
    API_BASE = 'https://testing.example.com/api'
    DB_NAME = 'testing'
    TESTING = True


def get_settings():
    env = os.getenv('ENV', 'TESTING')
    if env == 'PRODUCTION':
        return Production()
    return Testing()


settings = get_settings()

print('DB Host =', settings.DB_HOST)
print('DB Port =', settings.DB_PORT)

print('Override =', Production(TESTING=True).dict())

使用Python类

# settings.py
class Settings(object):
    DB_HOST = 'localhost'
    DB_PORT = 8888

settings = Settings()
# test.py
from settings import settings
print(settings.DB_HOST, settings.DB_PORT)

你可能感兴趣的:(环境配置管理)