-
-
Save rednafi/e44db87a6a87b1c7adb8cf770c980569 to your computer and use it in GitHub Desktop.
Pedantic config management using Pydantic
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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