Flask-Language

Flask-Language is a Flask extension providing a simple mechanism to handle a client-side language cookie.

It is somewhat loosely based on this snippet: http://flask.pocoo.org/snippets/128

Installation

Install the extension with with pipenv (recommended):

$ pipenv install flask-language

Or with pip:

$ pip install flask-language

Usage

Initialize the Flask-Language extension (also compatible with the Application Factories pattern):

from flask import Flask, jsonify
from flask_language import Language, current_language

app = Flask(__name__)
lang = Language(app)

Define the language hooks:

@lang.allowed_languages
def get_allowed_languages():
    return ['en', 'fr']

@lang.default_language
def get_default_language():
    return 'en'

Define the desired end-points to retrieve and manipulate the current language:

@app.route('/api/language')
def get_language():
    return jsonify({
        'language': str(current_language),
    })

@app.route('/api/language', methods=['POST'])
def set_language():
    req = request.get_json()
    language = req.get('language', None)

    lang.change_language(language)

    return jsonify({
        'language': str(current_language),
    })

Before each request, Flask-Language will automatically determine the current language in the following order:

  1. The language cookie (if any and matching the allowed languages)
  2. The Accept-Language HTTP header (if any and matching the allowed languages)
  3. The provided default language

During each request context, the current language can be accessed using current_language.

After each request, the current language will be stored in the language cookie.

Configuration

Flask-Language is configurable via the following configuration variables:

  • LANGUAGE_COOKIE_NAME: name for the cookie language (default: 'lang')
  • LANGUAGE_COOKIE_TIMEOUT: validity duration of the cookie language (default: datetime.timedelta(days=365))
  • LANGUAGE_COOKIE_DOMAIN: domain for the cookie language (default: None)
  • LANGUAGE_COOKIE_SECURE: set secure option for the cookie language (default: False)
  • LANGUAGE_COOKIE_HTTPONLY: set HTTP-only for the cookie language (default: False)

API

class flask_language.Language(app=None)

Primary class container for language cookie handling.

Before each request, it will try to retrieve the current language in the language cookie. If no cookie is present, it will try to find a best match of allowed languages in the ‘Accept-Language’ HTTP header. Finally if still no language is found, it will use the provided default language.

Each view can then access the current language using current_language.

After each request, the current language will be stored in the language cookie.

You might initialize Language like this:

language = Language()

Then pass the application object to be configured:

language.init_app(app)
allowed_languages(callback)

A decorator to be used to specify the list of allowed languages.

Example usage of allowed_languages might look like this:

language = Language(app)

@language.allowed_languages
def get_allowed_languages():
    return ['en', 'fr']
Parameters:callback – The callback to be wrapped by the decorator.
change_language(language)

Allows to change the current language to the specified one. The current_language will reflect the provided language only if it is present in allowed_languages.

Example usage of change_language might look like this:

language = Language(app)

@app.route('/api/language', methods=['POST'])
def set_language():
    req = request.get_json()
    lang = req.get('lang')

    language.change_language(lang)

    return jsonify({
        'lang': str(current_language)
    })
Parameters:language – The new language to be set.
default_language(callback)

A decorator to be used to specify the default language.

Example usage of default_language might look like this:

language = Language(app)

@language.default_language
def get_default_language():
    return 'en'
Parameters:callback – The callback to be wrapped by the decorator.
init_app(app)

Initializes a Flask object app: binds language cookie retrieval with app.before_request and binds language cookie installation with app.after_request.

Parameters:app – The Flask application object.