How to build multilingual Flask application

Creating a suitable Flask sample to try out Gitloc

If you want to create your project from scratch, then you can use the following step-by-step guide, where we will create a multilingual Flask sample project using i18n and Gitloc

Create a Flask Application (more at flask.palletsprojects.com)

Prerequisites

  • Familiarity with the command line

  • Install Python version 3.8 or higher

First we need to install Flask (more in the Flask installation guide):

$ pip install Flask

A minimal Flask application looks something like this:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "<p>Hello, World!</p>"

Save it as app.py.

To run the application, use the flask command or python -m flask. You need to tell the Flask where your application is with the --app option.

$ flask --app app run
 * Serving Flask app 'app'
 * Running on http://127.0.0.1:5000 (Press CTRL+C to quit)

Now let's use some templates in our app. Create new template hello.html in templates folder.

templates/hello.html
<!doctype html>
<title>Hello from Flask</title>
<h1>Hello, World!</h1>

Add this template to our app:

app.py
from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def hello_world():
    return render_template('hello.html')

Setup i18n (more at pypi.org)

In our example, we will create a project with 2 languages and separate .json files for translations.

Install i18n:

$ pip install python-i18n

Add i18n to the app.py and set i18n translations config:

app.py
from os import path

from flask import Flask, render_template

from i18n import config
from i18n.translator import t

RESOURCE_FOLDER = path.join(path.dirname(__file__), "static")
config.set('filename_format', '{namespace}.{format}')
config.set('file_format', 'json')
config.set('skip_locale_root_data', True)

app = Flask(__name__)

@app.route("/")
def hello_world():
    return render_template('hello.html')

Add translations usage (more at pypi.org)

Place translations into dedicated .json files in the public folder:

└── static
    └── locales
        ├── de
        │   ├── common.json
        │   └── welcome.json
        └── en
            ├── common.json
            └── welcome.json

Now let's define a language switcher and some variable content in our template:

templates/hello.html
<!doctype html>
<title>Hello from Flask</title>
{% if title %}
  <h1>{{ title }}</h1>
{% else %}
  <h1>Hello, World!</h1>
{% endif %}
<div>
  Select language
</div>
<p>
  <button onclick="window.location.href='/en';">
    English
  </button>
  <button onclick="window.location.href='/de';">
    Deutsch
  </button>
</p>

We will need title translations for different application locales. Let's add it to welcome.json.

static/locales/en/welcome.json
{
    "title": "You did it!",
}

And next we need to process our new routes /en and /de. Let's define a renderHello function to render localized templates and use it in the router.

app.py
from os import path

from flask import Flask, render_template

from i18n import config
from i18n.translator import t

RESOURCE_FOLDER = path.join(path.dirname(__file__), "static")
config.set('filename_format', '{namespace}.{format}')
config.set('file_format', 'json')
config.set('skip_locale_root_data', True)

def renderHello(lang):
  config.set('locale', lang)
  config.set("load_path", [path.join(RESOURCE_FOLDER, "locales", lang)])
  return render_template('hello.html', title=t('welcome.title'))

app = Flask(__name__)

@app.route('/')
def index():
  return renderHello('en')

@app.route('/en')
def en():
  return renderHello('en')

@app.route('/de')
def de():
  return renderHello('de')

For more information on using translation files (as placeholders, plurals, etc.), see the python-i18n docs.

Finally, сonnect your local project folder to your new repository on GitHub.

Done! Now you can move to the next step - connect remote repository to Gitloc

Last updated