diff --git a/app.py b/app.py index 3dfce46..6e7e759 100644 --- a/app.py +++ b/app.py @@ -1,4 +1,4 @@ -from configparser import ConfigParser +from modules import locale from blueprints.root import bp as root_bp from blueprints.risdeveau import bp as rdv_bp @@ -6,64 +6,18 @@ from blueprints.risdeveau import bp as rdv_bp import blueprints.root.modules.style import blueprints.risdeveau.modules.style -from flask import ( - Flask, - g, - request, -) +from flask import Flask -translations_cache = {} - -def load_translations(lang): - if lang not in translations_cache: - translations_cache[lang] = {} - - try: - config = ConfigParser() - config.read(f'locale/{lang}.ini') - for section in config.sections(): - translations_cache[lang][section] = dict(config.items(section)) - except: - pass - - return translations_cache[lang] - - -def get_locale(): - return request.accept_languages.best_match(('en', 'ru', 'de', 'fr', 'ja'), 'en') - app = Flask(__name__, static_folder=None, subdomain_matching=True) + +app.before_request(locale.before_request) +app.context_processor(locale.inject_translations) + app.register_blueprint(root_bp) app.register_blueprint(rdv_bp) -@app.before_request -def before_request(): - g.locale = get_locale() - g.translations = load_translations(g.locale) - - -@app.context_processor -def inject_translations(): - def translate(text, **kwargs): - if ":" in text: - section, key = text.split(":", 1) - else: - section, key = "common", text - - template = g.translations \ - .get(section, {}) \ - .get(key, f"${section}: {key}$") - - try: - return template.format(**kwargs) - except: - return template - - return {'_': translate} - - if app.debug: blueprints.root.modules.style.compile_styles() blueprints.risdeveau.modules.style.compile_styles() diff --git a/modules/locale.py b/modules/locale.py new file mode 100644 index 0000000..0887723 --- /dev/null +++ b/modules/locale.py @@ -0,0 +1,47 @@ +from configparser import ConfigParser +from flask import g, request + + +translations_cache = {} + + +def load_translations(lang): + if lang not in translations_cache: + translations_cache[lang] = {} + + try: + config = ConfigParser() + config.read(f'locale/{lang}.ini') + for section in config.sections(): + translations_cache[lang][section] = dict(config.items(section)) + except: + pass + + return translations_cache[lang] + +def get_locale(): + return request.accept_languages.best_match( + ('en', 'ru', 'de', 'fr', 'ja'), + ) or 'en' + +def before_request(): + g.locale = get_locale() + g.translations = load_translations(g.locale) + +def inject_translations(): + def translate(text, **kwargs): + if ":" in text: + section, key = text.split(":", 1) + else: + section, key = "common", text + + template = g.translations \ + .get(section, {}) \ + .get(key, f"${section}: {key}$") + + try: + return template.format(**kwargs) + except: + return template + + return {'_': translate}