paramecio2fm/paramecio2/libraries/i18n.py

132 lines
3.6 KiB
Python

#!/usr/bin/env python3
from importlib import import_module
#from paramecio.citoplasma.sessions import get_session
import json
from flask import session, has_request_context
yes_session=False
i18n_module={}
def load_lang(*args):
"""A function for load the lang module dinamically
"""
for module in args:
lang_path=module[0]+'.i18n.'+module[1]
try:
i18n_module[lang_path]=import_module(lang_path)
pass
except:
pass
# here load the language
class I18n:
"""Class for i18n tasks
Class for i18n tasks, how, strings for every language supported, for now are en-US and es-ES. You can add more languages adding
Attributes:
default_lang (str): The default string lang used when get someone
dict_i18n (list): The list with default languages. You can add more calling it static variable in settings/config.py
"""
default_lang='en-US'
dict_i18n=['en-US', 'es-ES']
l={}
#@staticmethod
#def set_lang(code_lang):
# if default_lang
@staticmethod
def get_default_lang():
"""Static method for get the default lang"""
lang=I18n.default_lang
if has_request_context():
lang=session.get('lang', lang)
return lang
@staticmethod
def lang(module, symbol, text_default):
"""Static method for get a string from selected language
Static method used to get the string of the selected language. If there is no string in the selected language, it returns text_default.
Args:
module (str): The module to which the translation string belongs
symbol (str): Simple symbol that is useful for identify the string
text_default (str): The text used by default when there are not translation in the selected language
"""
#if not lang:
# lang=I18n.get_default_lang()
lang=I18n.get_default_lang()
I18n.l[lang]=I18n.l.get(lang, {})
I18n.l[lang][module]=I18n.l[lang].get(module, {})
I18n.l[lang][module][symbol]=I18n.l[lang][module].get(symbol, text_default)
return I18n.l[lang][module][symbol]
@staticmethod
def extract_value(value):
"""Static method for get values from json lang array
Args:
value (json): Lang dict in json format
"""
value=json.loads(value)
lang=I18n.get_default_lang()
if value[lang]!='':
return value[lang]
return value[I18n.default_lang]
"""
@staticmethod
def get_browser_lang():
return request.headers.get('Accept-Language', 'en-US')
"""
@staticmethod
def lang_json(module, symbol, text_default):
"""Static method for return a language dict in JSON
Static method used to get the string of the selected language in JSON format. If there are not string in the selected language, it returns text_default.
Args:
module (str): The module to which the translation string belongs
symbol (str): Simple symbol that is useful for identify the string
text_default (str): The text used by default when there are not translation in the selected language
"""
arr_final={}
for l in I18n.dict_i18n:
arr_final[l]=I18n.lang(module, symbol, text_default, l)
return json.dumps(arr_final)