2011-10-20 14 views
5

Ho un'applicazione che viene eseguita in diversi processi (un server web e pochi processi che vengono utilizzati per calcoli pesanti). L'obiettivo è di rendere questi processi di calcolo restituiti errori localizzati. Per fare questo, ho fatto un dizionario che verrà utilizzata da Babel:Come registrare un oggetto traduttore Pylons?

errors = { 
    'ERR_REQUEST_FORMAT': (1, _('ERR_REQUEST_FORMAT')), 
    'ERR_REQUEST_TYPE': (2, _('ERR_REQUEST_TYPE')), 
} 

Ma quando provo a lanciare l'applicazione, ottengo

TypeError: No object (name: translator) has been registered for this thread 

Qual è il modo giusto caricare l'oggetto traduttore?

Grazie in anticipo, Ivan.

risposta

1

Suggerirei si traduce nel thread del server principale, ma è possibile registrare/usare un oggetto traduttore in questo modo:

import gettext 
str_to_translate = u'String to Translate' 
DOMAIN = 'example' # name of your translation babel translation file, here would be example.po 
LOCALE_DIR = '/path/to/locale/dir' # directory containing language subdirectories 
LANGUAGES = ['es'] 
CODESET = 'utf8' 
translator = gettext.translation(DOMAIN, localedir=LOCALE_DIR, languages=LANGUAGES, codeset=CODESET) 
translated_str = translator.gettext(str_to_translate) 

Se si vuole fare uso dell'ambiente tralicci un po 'di più, si può fare qualcosa di simile:

from pylons import config 
from pylons.i18n.translation import set_lang 
conf = config.current_conf() 
if not conf['pylons.paths']['root']: 
    conf['pylons.paths']['root'] = os.path.abspath(NAME_OF_YOUR_PROJECT) 
if not conf.get('pylons.package'): 
    conf['pylons.package'] = 'example' # same as domain above 
set_lang(LANG, pylons_config=conf) 

Dopo di che, _ funzionerà come nel thread principale.