How to set blank default locale for a flask app? How to set blank default locale for a flask app? flask flask

How to set blank default locale for a flask app?


You can use the following. This works by detecting the language from the url and stores it in the flask g request global, and it defaults to the browser setting if no language code has been set. Note that app.config['LANGUAGES]' must be a list containing supported languages such as ['en', 'de', 'fr].

@blueprint.url_defaultsdef set_language_code(endpoint, values):    if 'lang_code' in values or not g.get('lang_code', None):        return    # If endpoint expects lang_code, send it forward    if current_app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):        values['lang_code'] = g.lang_code@blueprint.url_value_preprocessordef get_lang_code(endpoint, values):    if values is not None:        # If no language code has been set, get the best language from the browser settings        default_lang = request.accept_languages.best_match(current_app.config['LANGUAGES'])        g.lang_code = values.pop('lang_code', default_lang)@babel.localeselectordef get_locale():    lang = g.get('lang_code')    if lang in current_app.config['LANGUAGES']:        return lang    else:        return 'en'

And then mount the blueprint on your app two times:

app.register_blueprint(blueprint, url_prefix='/')app.register_blueprint(blueprint, url_prefix='/<lang_code>')