import os, traceback import cherrypy from genshi.core import Stream from genshi.output import encode, get_serializer from genshi.template import Context, TemplateLoader from genshi.filters import Translator import gettext languages = {'en': None, 'de': None} for l in languages.keys(): languages[l] = gettext.translation('subdap', os.path.join(os.path.dirname(__file__), 'locale'), [l], fallback = True) print l, '->', languages[l] def do_translate(text): return cherrypy.thread_data.translations.gettext(text) def select_language(): if cherrypy.thread_data.lang != None: lang = cherrypy.thread_data.lang return languages[lang if languages.has_key(lang) else 'en'] accept = cherrypy.request.headers['Accept-Language'] try: accept = str(accept) except: accept = None if accept is not None: for group in accept.split(';'): for lang in group.split(','): if lang.find('=') >= 0: continue if lang.find('-') >= 0: lang = lang[:lang.find('-')] if languages.has_key(lang): return languages[lang] return languages['en'] def template_loaded(template): Translator(do_translate).setup(template) loader = TemplateLoader( os.path.join(os.path.dirname(__file__), 'templates'), auto_reload = True, callback = template_loaded ) def render(*args, **kwargs): if args: assert len(args) == 1, 'Expected exactly one argument, but got %r' % (args,) template = loader.load(args[0]) else: template = cherrypy.thread_data.template #ctxt = Context(url = cherrypy.url) ctxt = Context(url = myurl, lang = cherrypy.thread_data.lang) ctxt.push(kwargs) return template.generate(ctxt) def exc(exc): return render('error.html', details = traceback.format_exc()) def expose(filename, method='html', encoding='utf-8', **options): def decorate(func): @cherrypy.expose def wrapper(*args, **kwargs): cherrypy.thread_data.template = loader.load(filename) cherrypy.thread_data.func = func cherrypy.thread_data.lang = None if cherrypy.request.cookie.has_key('lang'): cherrypy.thread_data.lang = cherrypy.request.cookie['lang'].value if cherrypy.request.params.has_key('lang'): cherrypy.thread_data.lang = cherrypy.request.params['lang'] if cherrypy.thread_data.lang != None: cherrypy.response.cookie['lang'] = cherrypy.thread_data.lang cherrypy.response.cookie['lang']['path'] = '/' cherrypy.response.cookie['lang']['max-age'] = 2419200 cherrypy.response.cookie['lang']['version'] = 1 if kwargs.has_key('lang'): del kwargs['lang'] cherrypy.thread_data.translations = select_language() cherrypy.response.headers['Vary'] = 'Accept-Language' opt = options.copy() if method == 'html': opt.setdefault('doctype', 'html') serializer = get_serializer(method, **opt) try: stream = func(*args, **kwargs) except Exception, e: stream = exc(e) if not isinstance(stream, Stream): return stream try: return encode(serializer(stream), method = serializer, encoding = encoding) except Exception, e: return encode(serializer(exc(e)), method = serializer, encoding = encoding) return wrapper return decorate def myurl(url): return '/subdap/' + url