Created
December 15, 2022 13:11
-
-
Save ozcanyarimdunya/047fa864c01addfbf1dce308643007e2 to your computer and use it in GitHub Desktop.
Yaml construction
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
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": [ | |
"[email protected]", | |
"[email protected]" | |
], | |
"apikey": "secret_test_123" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment