gpt4 book ai didi

python同时获取不同语言的文本

转载 作者:太空宇宙 更新时间:2023-11-03 13:01:57 24 4
gpt4 key购买 nike

我正在为 i18n 使用 flask、pybabel。有时我需要向我的用户发送电子邮件。我想用他们自己的语言发送电子邮件。语言代码存储在数据库中,因此问题是用正确的语言翻译模板。这是我的发送功能的一部分:

            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) 这样的东西,我可以在每个模板渲染之前调用它。我该怎么做?

谢谢。

最佳答案

我有下一个用于电子邮件的 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)

关于python同时获取不同语言的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17380165/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com