Ошибка при использовании flask babel в AppEngine - PullRequest
1 голос
/ 10 июля 2020

Я работаю над своим первым проектом Flask Babel и наткнулся на загвоздку:

NameError: name '_' is not defined

Мне нужно перевести тексты и меню на разные языки, позже я займусь числами и датами. Команды pybabel extract и init работают хорошо и не выдают ошибок.

Вот мои файлы:

main.py

import datetime
from flask import Flask, render_template
from flask import session, redirect, url_for, escape, request
from flask_babel import Babel, gettext
from google.cloud import datastore

datastore_client = datastore.Client()

app = Flask(__name__)
app.config.from_pyfile('config.py')

babel = Babel(app)

@babel.localeselector
def get_locale():
    # return request.accept_languages.best_match(app.config['LANGUAGES'].keys()
    # In the app we'll ask the user what he prefers. 
    return 'es'  # Let's force Spanish for testing purposes

message = _("This site is for development purposes only. Please contact us for more 
information.")
footer = _("Test Text #1")
username = "test-user"

@app.route('/')
def root():
    return render_template('main.html', username=user, message=message) 

config.py

# add to your app.config or config.py file
LANGUAGES = {
    'en': 'English',
    'es': 'Español'
}

Вывод messages.pot

# Translations template for PROJECT.
# Copyright (C) 2020 ORGANIZATION
# This file is distributed under the same license as the PROJECT project.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2020.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PROJECT VERSION\n"
"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
"POT-Creation-Date: 2020-07-07 23:09+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: Babel 2.6.0\n"

#: /home/xxx/AppEngine/fpp-dev-01/main.py:25
msgid ""
"This site is for development purposes only. Please contact us for more "
"information."
msgstr ""

#: /home/xxx/AppEngine/fpp-dev-01/main.py:26
msgid "Test Text #1"
msgstr ""

#: /home/xxx/AppEngine/fpp-dev-01/templates/fppbase.html:46
msgid "Settings"
msgstr ""

messages.po (расположение: / home / xxx / Appengine / fpp-dev-01 / translations / es / LC_MESSAGES)

#: /home/xxx/AppEngine/fpp-dev-01/main.py:25
msgid ""
"This site is for development purposes only. Please contact us for more "
"information."
msgstr "Este sitio es solamente para fines de desarrollo. Por favor contáctenos para 
más información"

#: /home/xxx/AppEngine/fpp-dev-01/main.py:26
msgid "Test Text #1"
msgstr ""

#: /home/xxx/AppEngine/fpp-dev-01/templates/fppbase.html:46
msgid "Settings"
msgstr "Ajustes"

Я запускаю приложение локально (Linux) с помощью следующей команды:

python main.py

Вывод приложения в терминале:

Traceback (most recent call last):
  File "main.py", line 20, in <module>
    message = _("This site is for development purposes only. Please contact us for 
more information.")
NameError: name '_' is not defined

Итак, у кого-нибудь есть подсказка, почему мой приложение не распознает '_ (' для переводов?

Заранее спасибо!

1 Ответ

1 голос
/ 11 июля 2020

Необходимо импортировать

from flask_babel import lazy_gettext as _
...