Quellcode durchsuchen

Added config file loading and yaml support

master
Robin Thoni vor 3 Jahren
Ursprung
Commit
198ee45960
Signiert von: Robin THONI <robin@rthoni.com> GPG-Schlüssel-ID: 4E09DEF46B99E61E
4 geänderte Dateien mit 42 neuen und 2 gelöschten Zeilen
  1. 2
    0
      config.yml
  2. 1
    0
      config.yml.d/common.jinja
  3. 35
    0
      main.py
  4. 4
    2
      requirements.txt

+ 2
- 0
config.yml Datei anzeigen

@@ -0,0 +1,2 @@
1
+{% import 'config.d/common.jinja' as common %}
2
+answer: {{ common.answer | yaml }}

+ 1
- 0
config.yml.d/common.jinja Datei anzeigen

@@ -0,0 +1 @@
1
+{% set answer = 'The answer is: 42' %}

+ 35
- 0
main.py Datei anzeigen

@@ -3,7 +3,22 @@
3 3
 import sys
4 4
 
5 5
 import argparse
6
+import jinja2
6 7
 import pydantic
8
+import yaml
9
+
10
+
11
+def to_yaml(value):
12
+    value_str = yaml.safe_dump(value, default_style='"', default_flow_style=True)
13
+    return value_str[:-1] if value_str and value_str[-1] == '\n' else value_str
14
+
15
+
16
+class ConfigBase(pydantic.BaseModel):
17
+    pass
18
+
19
+
20
+class ConfigRoot(ConfigBase):
21
+    answer: str = pydantic.Field()
7 22
 
8 23
 
9 24
 class Options(pydantic.BaseModel):
@@ -21,7 +36,27 @@ def main(argv):
21 36
 
22 37
     options = Options(**vars(args))
23 38
 
39
+    with open(options.config_path, 'r') as f:
40
+        config_template = f.read()
41
+
42
+    jinja_env = jinja2.Environment(
43
+        loader=jinja2.PrefixLoader({
44
+            'config': jinja2.DictLoader({
45
+                'config.yml': config_template
46
+            }),
47
+            'config.d': jinja2.FileSystemLoader('{}.d'.format(options.config_path))
48
+        }),
49
+        extensions=["jinja2.ext.do"]
50
+    )
51
+    jinja_env.filters['yaml'] = to_yaml
52
+
53
+    template = jinja_env.get_template('config/config.yml')
54
+    config_yml = template.render(options=options)
55
+    config_dict = yaml.safe_load(config_yml)
56
+    config = ConfigRoot(**config_dict)
57
+
24 58
     print(options.config_path)
59
+    print(config.answer)
25 60
 
26 61
     return 0
27 62
 

+ 4
- 2
requirements.txt Datei anzeigen

@@ -1,2 +1,4 @@
1
-pydantic~=1.6.1
2
-argparse~=1.4.0
1
+argparse
2
+pydantic
3
+jinja2
4
+pyyaml

Laden…
Abbrechen
Speichern