librelist archives

« back to archive

Help: session between templates and views

Help: session between templates and views

From:
Lix Xu
Date:
2010-08-03 @ 05:26
Hi,
    I have some problems about session, templates.
    I want to make my pages to i18n support, but I don't want to use babel
as have to create .po files.
    So, I use my own way to do this:
    My site arch is:
    mysite\
        mysite\
            __init__.py
            config.py
            static\
            templates\
                layout.html
            views\
            models\
                __init__.py
                user.py
            utils\
                __init__.py
                myutils.py
            locals\
                __init__.py
                en.py
                zh.py

    1. the locals packages contains the i18n messages for each language
(just a dict), e.g.:
        in en.py, the content is:
        msg = dict(
            about = u'About',
            login = u'Login',
            password_confirm = u'Password Confirmation',
       )
       in zh.py the content is:
       msg = dict(
            about = u'关于',
            login = u'登录',
            password_confirm = u'确认密码',
       )

    2. and myutils.py contains the method t, e.g.
    from flask import session
    from ..locals.en import msg as en_msg
    from ..locals.zh import msg as zh_msg

    def get_msg(lang = 'en'):
        if lang in ('en', 'en-US'): return en_msg
        if lang in ('zh', 'zh-CN'): return zh_msg
        return en_msg

    def t(name, lang = None):
        lang = lang if lang else session.get('lang')
        msg = get_msg(lang)
        return msg[name] if name in msg else name

    3. in mysite\__init__.py
    from flask import session, Flask, g
    from .models.user import User
    from .views.users import users as users_view
    from .utils.myutils import t
    app = Flask(__name__)
    app.config.from_pyfile('config.py')
    app.register_module(users_view)
    app.jinja_env.filters['t'] = t
    @app.before_request
    def before_request():
         g.db = connect_db()
         g.user = User.find(session.get('user_id'))
         session['lang'] = g.user.lang if g.user else
request.accept_languages.best

    @app.after_request
    def shutdown_session(response):
        g.db.close()
        return response

   4. in templates, e.g. layout.html
       <html><head> ..... </head><body>
       Test: {{ 'about'|t }}
        </body></html>

  Problem in 4. If I changes the browser accept language order, the* {{
'about'|t }}* is the same as last value.
  If I write it as *{{ 'about'|t(session.lang) }}*, it works fine (seems the
template was cached).
 But it's a little ugly. I wonder whether there is a better way to do this.

Thanks a lot.
Lix Xu