Cant route urls with Flask-babel and blueprints when url doesnt specify language

Question:

I have been digging around Flask-babel for a while and cant seem to get the url routing with a simple blueprint. Here’s the trimmed down app

on my __ init __.py file,

app = Flask(__name__)
babel.init_app(app)


@babel.localeselector
def get_locale():
    return g.get('lang_code', 'fr')


from .mod_main import mod_main as main_blueprint
app.register_blueprint(main_blueprint,url_prefix='/<lang_code>')

In the blueprint views.py file

@mod_main.url_defaults
def add_language_code(endpoint, values):
    values.setdefault('lang_code', g.lang_code)


@mod_main.url_value_preprocessor
def pull_lang_code(endpoint, values):
    g.lang_code = values.pop('lang_code')


@mod_main.route('/', methods=['GET', 'POST'])
def index():
    return render_template('main/index.html')

This works perfectly fine as long as i navigate to http://localhost:5000/fr but when I navigate to http://localhost:5000/ (without the lang),i get the 404 error. Normal – since the blueprint is expecting a lang_code as a prefix.

On first time when a user navigates to http://localhost:5000/ (without lang), I expect the site to show pages with the language in ‘fr’. If the user then switches it to English, and navigates to http://localhost:5000/, i would like it to show up in english but not in french. Cant seem to get this working !!!

Asked By: Shankar ARUL

||

Answers:

I finally figured out the solution – all I needed to do was add a before_request function on the app to check for request.view_args and serve the right language based on the session variable.

I also figured out the g variable in flask is valid only for the active request and cannot be used to store values across requests. (As i was trying to store the lang on the g variable across requests – had to use the session variable to transfer values across requests)

I just uploaded a stripped down app implementing babel with blueprints here : https://github.com/shankararul/simple-babel

Answered By: Shankar ARUL
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.