Tornado – Internationalization

 

Web development often calls for internationalization (i18n), Tornado provides this facility with tornado.locale class.

In the example below, we create request handlers to cater to users request for different locale. For instance, DEHandler renders a standard web page (locale_template.html) in German language after translating the English words from the template.

import tornado.locale
import tornado.web
import os
class ENHandler(tornado.web.RequestHandler):
def get(self):
tornado.locale.set_default_locale('us_US')
self.render("locale_template.html")
class FRHandler(tornado.web.RequestHandler):
def get(self):
tornado.locale.set_default_locale('fr_FR')
self.render("locale_template.html")
class DEHandler(tornado.web.RequestHandler):
def get(self):
tornado.locale.set_default_locale('de_DE')
self.render("locale_template.html")
application = tornado.web.Application([
(r"/fr/", FRHandler),
(r"/en/", ENHandler),
(r"/de/", DEHandler),
],debug=True)
if __name__ == '__main__':
translationsPath = os.path.join("/home/ubuntu/tornado-2.2", "translations")
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()

Translation is governed by de_DE.csv file located under translation folder.


Hello World! Hallo Welt!
Thank You Danke

view raw

de_DE.csv

hosted with ❤ by GitHub


Hello World! Hello, world!
Thank You Thank You

view raw

us_US.csv

hosted with ❤ by GitHub

 

One thought on “Tornado – Internationalization

  1. While this article is pretty old, maybe my remark will be useful for someone.
    In current tornado version (4.0.2) method `set_default_locale` just set the default locale globally, not the locale of request. It will be used only if locale can’t be discovered from HTTP headers.
    To set the locale for request, method `get_user_locale` (http://www.tornadoweb.org/en/stable/web.html#tornado.web.RequestHandler.get_user_locale) must be used:

    class FRHandler(tornado.web.RequestHandler):
    def get_user_locale(self):
    return tornado.locale.get(“fr_FR”)

    def get(self):
    self.render(“locale_template.html”)

    Also check out this article, it describes i18n process in tornado with many details: http://www.lexev.org/en/2015/tornado-internationalization-and-localization/

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.