jumpserver/apps/common/utils/yml.py

36 lines
882 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-11-22 10:22:51 +00:00
def translate(key, i18n, lang):
lang = settings.LANGUAGE_CODE if lang is None else lang
lang = lang[: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
2023-12-05 09:14:35 +00:00
def yaml_load_with_i18n(stream, lang=None):
2023-04-20 03:13:28 +00:00
ori_text = stream.read()
stream = io.StringIO(ori_text)
yaml_data = yaml.safe_load(stream)
i18n = yaml_data.get('i18n', {})
env = Environment()
2023-11-22 10:22:51 +00:00
env.filters['trans'] = lambda key: translate(key, i18n, lang)
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)