Flask develop globalized applications

From the C # world into the python always give people a sense of relief, the same effect as the same function, only need to pay less than a tenth of the price, it is probably the power of Python philosophy advocated by Chien brought.

I do remember the deep global experience in ASP.NET, it can be described as miserable. Since .net is the use of the resource files in xml format as a resource bearer format, resulting in a reference to the globalization of resources it is necessary to adopt a strict line with c # naming conventions. Such an action would increase in the use of resources in the "name" of this complexity. I never before thought what the problem is, but yet translated into a multi-national version or to update the resource file will be facing a huge workload.
And ASP.NET official recommendation of globalization is even more deceptive practices, it is simply the "Quickly and duty" to the extreme, but did also had a fall into never-ending maintenance like hell.

Or until they found only a little contact with Web2Py decent for a global approach, Web2Py no middle name keywords, but the words directly as a search key natural resource, which is used for long-term development of the global ASP.NET I have no doubt of the project is to open a large hole in the brain we process. Moreover, making the default template language is a huge amount of work required in this process is still handled manually, so I have been looking for better applications.

Until it met with Flask Flask-Babel this plugin. It took over 10 minutes to get started, and see that it's simply exciting to use - simple, easy.

Flask-Babel is with Flask of Babel plugin, it has several very impressive features:

  • Automatic search from the code page and extracts the keyword global resources and generate default dictionary
  • Provide a series of command-line tools to synchronize and translate global resource file
  • Resource files can be compiled into a common *.moformat, by other editors to maintain Dictionary
  • Code page can be a way to access resources gettext(),_()
  • You can automatically switch the current regional language

Flask-Babel Usage

Flask-Babel loaded into the application context of Flask

from flask import Flask
from flask.ext.babel import Babel

app = Flask(__name__)
app.config.from_pyfile('babel.cfg')
babel = Babel(app)

babel.cfg Profiles

babel.cfg Babel is placed in a configuration file in the root directory Flask project, it is a fixed configuration, the following is the official recommended wording:

[python: **.py]
[jinja2: **/templates/**.html]
extensions=jinja2.ext.autoescape,jinja2.ext.with_

If the Flask-Assets plug if need to modify the extensionssettings

[python: **.py]
[jinja2: **/templates/**.html]
extensions=jinja2.ext.autoescape,jinja2.ext.with_,webassets.ext.jinja2.AssetsExtension

gettext()/_()

Then you can use in python code or page within jinia gettext()method references global resources. In fact, at this time we do not have any resource files, but that is the most attractive place Babel - first use and then generate resources.

It can be used as such in the python code gettext()

from flask import Flask, render_template

from flaskext.babel import Babel, gettext as _

app = Flask(__name__)
app.config['BABEL_DEFAULT_LOCALE'] = 'zh'
babel = Babel(app)

@app.route('/')
def hello():
    s = _("Saturday")
    return render_template('index.html', day=day)

if __name__ == '__main__':
    app.debug = True
    app.run()

The above code _("Saturday")is to get the name from the resource in Saturdaythe resource, if the resource file does not correspond to the region or will not find a direct output"Saturday"

Jinja is then used in a template:

<p>{{ _("Hello, world!") }}</p>
<p>{{ _("It's %(day)s today", day=day) }}</p>

Similarly, in the other modules of code and is used in two ways to this global resource.

Generated translation template

This is a very important step, but also the effort of Babel most time-saving step. Babel can be drawn with the code and templates from gettext()all the resources and generate names into the default template language. This template is generated after every need can be translated into local language.

Just type the following command in the command line

$ pybabel extract -F babel.cfg -o messages.pot .

Will be generated under the project root directory Flask of messages.potthe default template language

Translation template

The next step is to specify the default template for translation from regional language resource files, and also deal with the command line:

$ pybabel init -i messages.pot -d translations -l zh

The result of this instruction is executed in accordance with messages.potthe Chinese (zh) resource files ( message.pogenerated to) translationsdirectory.

Directory structure is as follows:

.
├── babel.cfg
├── messages.pot
├── static
├── templates
└── translations
      └── zh
           └── LC_MESSAGES
                  └─ message.po
      

message.poIt is the target resource file, you can now open and the associated translation work. *.poFile is simply a text can be edited directly, or you can choose some special po programming tools have become. I am more recommended POEdit

645016-20151123093117545-672420583.png

Note When referring to the need to use shorthand when regional area rather than the full name of the area, if you specify zh-CN(Simplified Chinese), then on the direct use zhor instruction errors.

message.po file

The following is the message.opcontent

# Chinese translations for PROJECT.
# Copyright (C) 2015 ORGANIZATION
# This file is distributed under the same license as the PROJECT project.
# Ray <csharp2002@hotmail>, 2015.
#, fuzzy

msgid ""
msgstr ""
"Project-Id-Version: PROJECT VERSION\n"
"Report-Msgid-Bugs-To: [email protected]\n"
"POT-Creation-Date: 2015-03-29 22:46+0800\n"
"PO-Revision-Date: 2015-03-29 21:49+0800\n"
"Last-Translator: Ray <[email protected]>\n"
"Language-Team: zh <[email protected]>\n"
"Plural-Forms: nplurals=2; plural=(n != 1)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: Babel 1.3\n"

#: views.py:103
#,fuzzy, python-format
msgid "Articles tagged with:%(value)s"
msgstr "标记%(value)s主题的文章"

Note : ,fuzzyThis keyword, if you need to compile the resource file to be *.moif you need to remove it, otherwise the resource file compiler will ignore the entire resource files directly without compilation.

Compile resources

Compilation process is very simple, just need to execute the following command translationsall the *.pofiles will be compiled into a binary *.moresource files.

$ pybabel compile -d translations

Update the default template

This is indeed a very Babel sake of functionality for developers, because our program resources must be the need to change and maintain the content naturally bound to be changes in the resource file. When we translate a copy of the N languages ​​it would be without the tools to do by hand but then a very horrible job process. Fortunately, we just need to execute the following command, babel will update the default template file and all the all the resources generated from this template:

$ pybabel update -i messages.pot -d translations

Area switchover

Flask-Babel default is read flask.g.langautomatically switch the current locale request context of use. However, in many scenarios we need to manually change the current regional language, in which case we would need to add a get_local()function:

from flask import g, request

@babel.localeselector
def get_locale():
    # 如果在g对象内有登入的用户对象则从用户对象中读取 locale 区域信息
    user = getattr(g, 'user', None)
    if user is not None:
        return user.locale
    
    # 此方法只需要返会一个区域字符串
    return request.accept_languages.best_match(['de', 'fr', 'en'])


@babel.timezoneselector
def get_timezone():
    """此函数与 get_locale 类似,只是向babel提供获取时区的设置"""
    user = getattr(g, 'user', None)
    if user is not None:
        return user.timezone

After providing these two functions, calling gettextupon Babel will automatically call them. Here by decorators @babel.localeselectorand @babel.timezoneselectorachieve similar functionality rewriting, but the proportion of the amount of code written write fewer classes.

summary

Of course, API more than Babel herein provided in these, if you need a more detailed understanding may be carefully read Flask-Babel documents. Here I aimed at the most conventional usage records Babel to make notes but also to share with more people are using Flask of friends.

Reproduced in: https: //www.cnblogs.com/Ray-liang/p/4987455.html

Guess you like

Origin blog.csdn.net/weixin_33895604/article/details/94195959