Skip to content

Instantly share code, notes, and snippets.

@rednafi
Last active Jun 3, 2020
Embed
What would you like to do?
Pedantic config management using Pydantic
ENV_STATE="dev" # or prod
DEV_REDIS_HOST="127.0.0.1"
DEV_REDIS_PORT="4000"
PROD_REDIS_HOST="127.0.0.2"
PROD_REDIS_PORT="5000"
# configs.py
from typing import Optional
from pydantic import BaseSettings, Field, BaseModel
class AppConfig(BaseModel):
"""Application configurations."""
VAR_A: int = 33
VAR_B: float = 22.0
class GlobalConfig(BaseSettings):
"""Global configurations."""
# This variable will be loaded from the .env file. However, if there is a
# shell environment variable having the same name, that will take precedence.
ENV_STATE: Optional[str] = Field(None, env="ENV_STATE")
APP_CONFIG: AppConfig = AppConfig()
REDIS_PASS: Optional[str] = Field(None, env="REDIS_PASS")
class Config:
"""Loads the dotenv file."""
env_file: str = ".env"
class DevConfig(GlobalConfig):
"""Development configurations."""
REDIS_HOST: Optional[str] = Field(None, env="DEV_REDIS_HOST")
REDIS_PORT: Optional[int] = Field(None, env="DEV_REDIS_PORT")
class ProdConfig(GlobalConfig):
"""Production configurations."""
REDIS_HOST: Optional[str] = Field(None, env="PROD_REDIS_HOST")
REDIS_PORT: Optional[int] = Field(None, env="PROD_REDIS_PORT")
class FactoryConfig:
"""Returns a config instance dependending on the ENV_STATE variable."""
def __init__(self, env_state: Optional[str]):
self.env_state = env_state
def __call__(self):
if self.env_state == "dev":
return DevConfig()
elif self.env_state == "prod":
return ProdConfig()
cnf = FactoryConfig(GlobalConfig().ENV_STATE)()
print(cnf.__repr__())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment