Flask Snippets

Snippets are unofficial and unmaintained.

This is an archived view of user-submitted snippets. Despite being hosted on the Flask site, they are not official. No Flask maintainer has curated or checked the snippets for security, correctness, or design.

Language Switcher via Cookie, Accept Headers

Posted by Paul on 2015-02-24 @ 15:05 and filed in Internationalization

A combination of Decorator, Context Processor and Post-Request Injection to handle switching languages by first looking at the Accept Language Header and subsequently giving the user control over the preset language, as mirrored by a cookie.

def match_languages(f):

    def decorated(*args, **kwargs):
        '''Decorator to determine preferred language by Accept
        Language Header. Switching Languages is provided through
        an injected unordered list.

        cookie = request.cookies.get("App-Language")
        '''Ping flask for available languages'''
        AVAILABLE_LOCALES = flask.g.i10n.get_available_locales()
        if not cookie in AVAILABLE_LOCALES: cookie = None

        if cookie is None:
            UA_langs = request.headers.get('Accept-Language').split(",")
            matches = filter(lambda x: x.split(";")[0] in AVAILABLE_LOCALES, UA_langs)
            lang = matches[0] if matches else AVAILABLE_LOCALES[0]

        '''Set best match as global language'''
        flask.g.lang = cookie if cookie else lang
        return f(*args, **kwargs)

    return decorated

The Post-Request Cookie Setter

def pass_language():
    def set_lang_cookie(response):
        response.set_cookie('App-Language', flask.g.lang)
        return response

Inject Language Dictionary into Template

def inject_lang_switcher():
    '''Inject prefixes of available feed languages in unordered list
    Test root langs in Accept-Language Header
    against langs in aufschaltung'''

    if request.is_xhr or \
        not flask.g.i10n.has_langs:
            return []

    AVAILABLE_LOCALES = flask.g.i10n.get_available_locales()    
    lang_prefixes = [dict(prefix = l.split("-")[0], lang = l,
        selected = l == flask.g.lang) for l in AVAILABLE_LOCALES]

    return dict(lang_switcher = lang_prefixes)

This snippet by Paul can be used freely for anything you like. Consider it public domain.