Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask - how can I always include language code in url

I am starting with Flask for a couple weeks and is trying to implement i18n and l10n to my Flask app. This is the behavior that I really want to implement:

User enters website.com will be redirected to website.com/en/ or website.com/fr/ depends on their Accept-Languages header or default language in their settings.

This is my current implementation:

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

@mainBlueprint.route('/')
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 respond with just website.com. Unless I type website.com/fr it would respond with /fr/. However, I want to always include /en/ even if it is the default option.


I have tried the guide URL Processors pattern in Flask doc, but when I typed website.com it responded with 404 error. It only worked fine when I include the language_code into the url—which is not the behavior that I want.


Thank you in advance!

like image 867
Luan Nguyen Avatar asked Sep 21 '14 17:09

Luan Nguyen


1 Answers

Look like you need only one blueprint:

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

But you should decide behaviour for default blueprint route:

  1. It can return 404:

    app.register_blueprint(mainBlueprint, url_defaults='/<lang>')
    
  2. It can redirect to /en blueprint:

    @mainBlueprint.before_request
    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>')
    
like image 183
tbicr Avatar answered Oct 09 '22 11:10

tbicr