From 56dcc94c2674085b37aa584cb5c22f8aad50ea7a Mon Sep 17 00:00:00 2001 From: vinyll Date: Fri, 26 Jan 2018 15:38:30 -0600 Subject: [PATCH] removed template system and moved cache into Translator class --- .gitignore | 2 ++ setup.py | 4 ++-- tcii18n/template.py | 14 -------------- tcii18n/translator.py | 27 ++++++++++++++++++++------- 4 files changed, 24 insertions(+), 23 deletions(-) delete mode 100644 tcii18n/template.py diff --git a/.gitignore b/.gitignore index e69de29..7a60b85 100644 --- a/.gitignore +++ b/.gitignore @@ -0,0 +1,2 @@ +__pycache__/ +*.pyc diff --git a/setup.py b/setup.py index 6b51438..86e8eda 100644 --- a/setup.py +++ b/setup.py @@ -3,8 +3,8 @@ setup( name='tcii18n', - version='0.1', - author='Hugo Mochet', + version='0.2', + author='Vincent Agnano', license='Copyright Anthropedia', long_description=open('readme.md').read(), ) diff --git a/tcii18n/template.py b/tcii18n/template.py deleted file mode 100644 index 00ad089..0000000 --- a/tcii18n/template.py +++ /dev/null @@ -1,14 +0,0 @@ -from .translator import Translator - -_cached_translators = {} - - -def flask_methods(app, get_translations_file): - @app.context_processor - def utility_processor(): - def trans(sentence): - filename = get_translations_file() - if filename not in _cached_translators: - _cached_translators[filename] = Translator(filename) - return _cached_translators[filename].translate(sentence) - return dict(trans=trans, _=trans) diff --git a/tcii18n/translator.py b/tcii18n/translator.py index 5a3f4ee..702d811 100644 --- a/tcii18n/translator.py +++ b/tcii18n/translator.py @@ -1,16 +1,29 @@ import csv +_translators = {} + + class Translator: - def __init__(self, filename): + def __init__(self, filename, cache=True): + self._cache_key = filename + self._cache = cache reader = open(filename, 'r') self.content = tuple(csv.reader(reader)) reader.close() + if self._cache and self._cache_key not in _translators.keys(): + _translators[self._cache_key] = self.content + + def get_translations(self): + if self._cache: + return _translators[self._cache_key] + else: + return self.content def translate(self, sentence, **kwargs): - for row in self.content: - if row[0] == sentence: - for key, value in kwargs.items(): - row[1] = row[1] % {key: value} - return row[1] - return sentence + translation = dict(self.get_translations()).get(sentence) + if not translation: + return sentence + for key, value in kwargs.items(): + translation = translation % {key: value} + return translation