jumpserver/apps/common/utils/yml.py

35 lines
817 B
Python
Raw Normal View History

2023-04-20 03:13:28 +00:00
import io
import yaml
2023-04-20 06:19:13 +00:00
from django.conf import settings
2023-04-20 03:13:28 +00:00
from jinja2 import Environment
2023-04-20 06:39:31 +00:00
def translate(key, i18n):
2023-04-20 06:19:13 +00:00
lang = settings.LANGUAGE_CODE[:2]
2023-04-20 03:27:10 +00:00
lang_data = i18n.get(key, {})
return lang_data.get(lang, key)
2023-04-20 03:13:28 +00:00
def yaml_load_with_i18n(stream):
ori_text = stream.read()
stream = io.StringIO(ori_text)
yaml_data = yaml.safe_load(stream)
i18n = yaml_data.get('i18n', {})
env = Environment()
2023-04-20 06:39:31 +00:00
env.filters['trans'] = lambda key: translate(key, i18n)
2023-04-20 03:13:28 +00:00
template = env.from_string(ori_text)
yaml_data = template.render()
yaml_f = io.StringIO(yaml_data)
d = yaml.safe_load(yaml_f)
if isinstance(d, dict):
d.pop('i18n', None)
return d
if __name__ == '__main__':
with open('manifest.yml') as f:
data = yaml_load_with_i18n(f)
print(data)