Flask - how can I always include a language code in a URL?

I have been starting with Flask for a couple of weeks now and am trying to implement i18n and l10n in my Flask application. This is the behavior I really want to implement:

User inputs website.com

will be redirected to website.com/en/

or website.com/fr/

based on their Accept-Languages ​​header or default language.

This is my current implementation:

# main_blueprint.py
mainBlueprint = Blueprint('main', __name__)

def index(lang):
    return "lang: %" % lang

# application.py
app.register_blueprint(mainBlueprint, url_defaults={'lang': 'en'})
app.register_blueprint(mainBlueprint, url_prefix='/<lang>')


This way, when I type website.com

or website.com/en/

, it will only respond website.com

. If I don't type website.com/fr

, he will reply with /fr/

. However, I want to always enable /en/

, even if this is the default setting.

I tried the url pattern tutorial in the Flask doc, but when I typed website.com

it answered 404 error

. It only worked fine when I include language_code

in the url, which is not the behavior I want.

Thank you in advance!


source to share

1 answer

It looks like you only need one plan:

app.register_blueprint(mainBlueprint, url_defaults='/<lang>')


But you have to choose the default route behavior:

  • It can return 404:

    app.register_blueprint(mainBlueprint, url_defaults='/<lang>')

  • It can be redirected to a drawing /en


    def x(*args, **kwargs):
        if not request.view_args.get('lang'):
            return redirect('/en' + request.full_path)
    app.register_blueprint(mainBlueprint, url_defaults={'lang': None})
    app.register_blueprint(mainBlueprint, url_prefix='/<lang>')



All Articles