pypi i Flask-Locale


Implements i18n and l10n support for Flask.

by Erkan Durmuş

1.0.4 (see all)License:BSD
pypi i Flask-Locale


Implements i18n and l10n support for Flask. This is based on the old Flask-Locale extension. Uses files or database to get translations.

You can use this extension to translate your applications really easily. No babel preperation is needed. Just put your English text and its translation in a file.


pip install Flask-Locale

Quick Start

  • Py3 ready

  • For very quick test look at demo directory.

  • Create a directory translations at app root.

  • Create file translations/tr_TR.csv with this content:

"Hello %(name)s","Merhaba %(name)s"

  • Create templates directory at app root.

  • Create locale.html file with this content:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
 <h2>Translate with parameters in template</h2>
 {{ _('Hello %(name)s', name=name) }}
 <h2>Translated in Python Code:</h2>
 {{ py_translated }}

-- Create your application main file demo.py:

# -*- coding: utf-8 -*-   
from flask import Flask, request, render_template, g
from flask_locale import Locale, _    
app = Flask(__name__)
app.config['LOCALE_PATH'] = 'translations'    
locale = Locale(app)        
def get_locale():
    # if a user is logged in, use the locale from the user settings    
    user = getattr(g, 'user', None)
    if user is not None:
        return user.locale
    # otherwise try to guess the language from the user accept
    # header the browser transmits.  We support tr/fr/en in this
    # example.  The best match wins.
    return request.accept_languages.best_match(['tr_TR', 'fr_FR', 'en_US'])
def index():
    # How we do translation in python code:
    py_translated = _('Hello')
    # How we do translation in template:
    return render_template('locale.html', name='Erkan', 
if __name__ == '__main__':
  • Run your app:

python demo.py

  • Now access your app:


Loading translations from a file:

Loads translations from CSV files having locale extension in a directory. File should be utf-8 encoded.

Translations are strings with optional Python-style named placeholders (e.g., "My name is %(name)s") and their associated translations.

The directory should have translation files of the form filename: LOCALE, e.g. tr_TR.

Translation files should have two or three columns: string, translation, and an optional plural indicator. Plural indicators should be one of "plural" or "singular".

A given string can have both singular and plural forms. For example "%(name)s liked this" may have a different verb conjugation depending on whether %(name)s is one name or a list of names. There should be two rows in the CSV file for that string, one with plural indicator "singular", and one "plural".

For strings with no verbs that would change on translation, simply use "unknown" or the empty string (or don't include the column at all).

The file is read using the csv module in the default "excel" dialect. In this format there should not be spaces after the commas.

Example translation tr_TR.csv:

"I love you","Seni seviyorum"
"%(name)s liked these","A %(name)s bunları sevdi","plural"
"%(name)s liked this","A %(name)s bunu sevdi","singular"

Loading translations from database:

def get_translations():
    """Translations selector for db"""
        sql = select(
            [Locale.c.code, TranslationKey.c.name, Translation.c.translated, Translation.c.singular],
        q = db.session.execute(sql)
        data = q.fetchall()
    return list(data)

Reloading translations

When user's locale is changed, call refresh() method:

user.locale = request.form['locale']
flash(_('Language is changed'))

Translate Functions

translate() (or its alias _()) method does a lazy translation, that means its actual translate function is called when you access it. So you can use translate functions in your forms before Flask-Locale is initialized.

from flask.ext.wtf import Form
from wtforms.fields import TextField, PasswordField
from wtforms.validators import Required, Email
from extensions import _  
class EmailPasswordForm(Form):
    email = TextField(_('Email'), validators=[Required(), Email()])
    password = PasswordField(_('Password'), validators=[Required()])

If you want immediate translation, use do_translate method.

5yrs ago
5yrs ago
6yrs ago
6yrs ago
No tutorials found
Add a tutorial
No dependencies found

Rate & Review

No reviews found
Be the first to rate