Skip to content

Instantly share code, notes, and snippets.

@ozcanyarimdunya
Created December 15, 2022 13:11
Show Gist options
  • Save ozcanyarimdunya/047fa864c01addfbf1dce308643007e2 to your computer and use it in GitHub Desktop.
Save ozcanyarimdunya/047fa864c01addfbf1dce308643007e2 to your computer and use it in GitHub Desktop.
Yaml construction
import pathlib
import yaml
from yaml.constructor import Constructor
class CustomConstructor(Constructor):
def construct_yaml__secret(self, node):
values = self.construct_mapping(node)
username = values["username"]
password = values["password"]
return f"secret_{username}_{password}"
def construct_yaml__file(self, node):
filename = self.construct_scalar(node)
file = pathlib.Path(filename)
if not file.exists():
return f"{node.value} not found!"
with file.open(mode="r") as file:
return file.read()
def construct_yaml__user(self, node):
users = self.construct_sequence(node)
users = list(map(lambda it: f"{it}@mail.com", users))
return users
def get_loader():
loader = yaml.FullLoader
loader.add_constructor("!file", CustomConstructor.construct_yaml__file)
loader.add_constructor("!user", CustomConstructor.construct_yaml__user)
loader.add_constructor("!secret", CustomConstructor.construct_yaml__secret)
return loader
content = """
---
version: '2.7'
description: !file description.md
authors: !user
- me
- you
apikey: !secret
username: test
password: 123
"""
config = yaml.load(content, Loader=get_loader())
assert config == {
"version": "2.7",
"description": "description.md not found!",
"authors": [
"me@mail.com",
"you@mail.com"
],
"apikey": "secret_test_123"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment