вторник, 17 мая 2011 г.

How do I disable caching in python gettext and django gettext?

For disabling cache in python-gettext module you are to edit gettext module.

Execute the command below to get known where you're python-gettext module is:
$ python -c "import gettext; print gettext.__file__"
/usr/lib/python2.6/gettext.py


Then open that file and find lines in translation() function:
for mofile in mofiles:
    key = os.path.abspath(mofile)
    t = _translations.get(key)
    if t is None:
        t = _translations.setdefault(key, class_(open(mofile, 'rb')))


Replace it with:
for mofile in mofiles:
    key = os.path.abspath(mofile)
    t = _translations.get(key)
    t = None # new line
    if t is None:
        t = _translations.setdefault(key, class_(open(mofile, 'rb')))


It will simply disable gettext's cache for your debugging purposes. I wouldn't recomend this patch to use in production.

However if you use django framework it won't solve your caching problems. I wonder to know why but django uses its own gettext caching layer. To disable it simply replace in file utils/translation/trans_real.py:
def translation(language):
    """
    Returns a translation object.

    This translation object will be constructed out of multiple GNUTranslations
    objects by merging their catalogs. It will construct a object for the
    requested language and add a fallback to the default language, if it's
    different from the requested language.
    """
    global _translations

    t = _translations.get(language, None)
    if t is not None:
        return t


with:
def translation(language):
    """
    Returns a translation object.

    This translation object will be constructed out of multiple GNUTranslations
    objects by merging their catalogs. It will construct a object for the
    requested language and add a fallback to the default language, if it's
    different from the requested language.
    """
    global _translations

    t = _translations.get(language, None)
    t = None # new line
    if t is not None:
        return t

Patches available here: for gettext.py and for trans_real.py