06/15 Phase 1 + 2 codes
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
"""i18n: locale resolution + a route to switch UI language.
|
||||
|
||||
Order: explicit session choice -> authenticated user.locale -> Accept-Language -> default.
|
||||
"""
|
||||
from flask import Blueprint, session, redirect, request, current_app, url_for
|
||||
from flask_login import current_user
|
||||
|
||||
i18n_bp = Blueprint("i18n", __name__)
|
||||
|
||||
|
||||
def select_locale():
|
||||
supported = current_app.config["SUPPORTED_LOCALES"]
|
||||
# 1. explicit session override
|
||||
lang = session.get("lang")
|
||||
if lang in supported:
|
||||
return lang
|
||||
# 2. authenticated user's stored preference
|
||||
if current_user.is_authenticated and current_user.locale in supported:
|
||||
return current_user.locale
|
||||
# 3. browser preference
|
||||
best = request.accept_languages.best_match(supported)
|
||||
if best:
|
||||
return best
|
||||
# 4. default
|
||||
return current_app.config["DEFAULT_LOCALE"]
|
||||
|
||||
|
||||
@i18n_bp.route("/lang/<code>")
|
||||
def set_lang(code):
|
||||
if code in current_app.config["SUPPORTED_LOCALES"]:
|
||||
session["lang"] = code
|
||||
# persist to profile when logged in
|
||||
if current_user.is_authenticated:
|
||||
from app.extensions import db
|
||||
current_user.locale = code
|
||||
db.session.commit()
|
||||
target = request.referrer or url_for("main.index")
|
||||
return redirect(target)
|
||||
Reference in New Issue
Block a user