2013-06-29 25 views
3

我用燒瓶,pybabel for i18n。有時我需要發送電子郵件給我的用戶。我想用他們自己的語言發送電子郵件。語言代碼存儲在數據庫中,所以問題是用正確的語言翻譯模板。這裏是我的發送功能的一部分:模板python gettext同一時間不同的語言

  lang = user.get_lang() 
      subject = _('Subject') 
      for user in users: 
       if user.email: 
         body = render_template('emails/template.eml', user=user) 
         recipients = [user.email] 
         msg = Message(subject, html=body, recipients=recipients) 
         conn.send(msg) 

而且例如:

{{ _('Hi {name}. How are you?').format(user.name) }} 

所有我需要的是一樣的東西set_langauge(lang)每個模板渲染之前,我可以打電話。我該怎麼做?

謝謝。

回答

4

我對未來的電子郵件功能render_template

def render_template(template_name_or_list, **context): 

    # get request context 
    ctx = _request_ctx_stack.top 

    # check request context 
    # if function called without request context 
    # then call with `test_tequest_context` 
    # this because I send email from celery tasks 
    if ctx is None: 
     with current_app.test_request_context(): 
      return render_template(template_name_or_list, **context) 

    # I have specific locale detection (from url) 
    # and also use `lang` variable in template for `url_for` links 
    # so you can just pass language parameter without context parameter 
    # and always set `babel_locate` with passed language 
    locale = getattr(ctx, 'babel_locale', None) 
    if locale is None: 
     ctx.babel_locale = Locale.parse(context['lang']) 

    # render template without additinals context processor 
    # because I don't need this context for emails 
    # (compare with default flask `render_template` function) 
    return _render(ctx.app.jinja_env.get_or_select_template(
     template_name_or_list), context, ctx.app) 

所以,如果你只需要改變語言要求方面使用下面的代碼(見get_locale):

def set_langauge(lang) 
    ctx = _request_ctx_stack.top 
    ctx.babel_locale = Locale.parse(lang) 
4

感謝@tbicr我結束採用這種解決方案。

在我app.py我有set_locale功能:

from flask import _request_ctx_stack as ctx_stack 
# ... 
def set_locale(lang): 
    ctx = ctx_stack.top 
    ctx.babel_locale = lang 
# ... 

和我渲染電子郵件模板之前調用它。

的問題是,我需要在同一時間發送郵件給衆多用戶提供了不同的語言:

with app.test_request_context(): 
    with mail.connect() as conn: 
     for user in users: 
      set_locale(user.get_lang()) 
      subject = _(u'Best works').format(get_month_display(month)) 
      body = render_template('emails/best_works.eml' 
       recipients = [user.email] 
       msg = Message(subject, html=body, recipients=recipients) 
       conn.send(msg) 

,當我打電話set_locale第一次區域的價值被緩存和所有的電子郵件都呈現與語言的第一個用戶。

解決的辦法是每次撥打flaskext.babel.refreshset_locale