-
-
Save ckkz-it/ca30a67737e839c1b0663681ddfc5c0d to your computer and use it in GitHub Desktop.
Python YAML (PyYAML) with environment file support (python-dotenv)
This file contains 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
POSTGRES_DB=postgres | |
POSTGRES_USER=postgres | |
POSTGRES_PASSWORD=p@ssw0rd | |
POSTGRES_HOST=localhost | |
POSTGRES_PORT=5432 | |
JWT_SECRET=very secret | |
JWT_ACCESS_EXP=1800 | |
JWT_REFRESH_EXP=864000 | |
JWT_ALGORITHM=HS256 |
This file contains 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
import os | |
import pathlib | |
import re | |
import yaml | |
from dotenv import load_dotenv | |
BASE_DIR = pathlib.Path(__file__) | |
config_path = BASE_DIR / 'main.yaml' | |
load_dotenv(dotenv_path=BASE_DIR / '.env') | |
FROM_ENV_RE = re.compile(r'\${{.+}}') | |
def parse_env_placeholders(content: str) -> str: | |
def replace(match: re.Match): | |
value = match.group().strip('${}').strip() | |
return os.getenv(value) | |
return FROM_ENV_RE.sub(replace, content) | |
def get_config(path) -> dict: | |
with open(path) as f: | |
content = f.read() | |
parsed = parse_env_placeholders(content) | |
cfg = yaml.safe_load(parsed) | |
return cfg | |
config = get_config(config_path) |
This file contains 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
postgres: | |
database: ${{ POSTGRES_DB }} | |
user: ${{ POSTGRES_USER }} | |
password: ${{ POSTGRES_PASSWORD }} | |
host: ${{ POSTGRES_HOST }} | |
port: ${{ POSTGRES_PORT }} | |
minsize: 1 | |
maxsize: 5 | |
jwt: | |
secret: ${{ JWT_SECRET }} | |
access_exp: ${{ JWT_ACCESS_EXP }} | |
refresh_exp: ${{ JWT_REFRESH_EXP }} | |
algorithm: ${{ JWT_ALGORITHM }} | |
request_property: jwt_payload |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
PyYAML https://github.com/yaml/pyyaml
python-dotenv https://github.com/theskumar/python-dotenv