Skip to content

Instantly share code, notes, and snippets.

@ckkz-it
Last active December 3, 2021 08:14
Show Gist options
  • Save ckkz-it/ca30a67737e839c1b0663681ddfc5c0d to your computer and use it in GitHub Desktop.
Save ckkz-it/ca30a67737e839c1b0663681ddfc5c0d to your computer and use it in GitHub Desktop.
Python YAML (PyYAML) with environment file support (python-dotenv)
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
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)
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
@ckkz-it
Copy link
Author

ckkz-it commented Apr 17, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment