Reputation: 1073
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 towebsite.com/en/
orwebsite.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!
Upvotes: 6
Views: 2188
Reputation: 26070
Look like you need only one blueprint:
app.register_blueprint(mainBlueprint, url_defaults='/<lang>')
But you should decide behaviour for default blueprint route:
It can return 404:
app.register_blueprint(mainBlueprint, url_defaults='/<lang>')
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>')
Upvotes: 6