I need to make a flask based website multilingual.
My site needs to acts as follows:
example.com -> Italian
example.com/it/ -> redirects to example.com
example.com/en/ -> English
This is my current implementation:
app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html', navbar={}), 404
# blueprints
from blueprints.www import www
app.register_blueprint(www, name='default_locale_www', url_defaults={'locale': 'it'})
app.register_blueprint(www, name='www', url_prefix='/<locale>')
blueprints/www.py
from flask import render_template, Blueprint, abort, redirect, url_for
www = Blueprint('www', __name__)
all_locales = ['it', 'en']
default_locale = 'it'
@www.url_value_preprocessor
def manage_locales(endpoint, values):
if values['locale'] not in all_locales:
values['locale'] = default_locale
@www.route('/')
def homepage(locale):
return render_template('homepage.html', locale=locale)
@www.route('/test')
def test(locale):
return render_template('test.html', locale=locale)
@www.route('/{slug}')
def slug(locale, slug):
return render_template('slug.html', locale=locale, slug=slug)
But have some issues:
example.com/itdose not redirect toexample.comexample.com/fooshows the homepage in Italian, but it should return 404example.com/it/fooshould match the slug route, but returns 404example.com/en/fooshould match the slug route, but returns 404example.com/foo/testshould return 404, but match the test route
How would I go about doing this? Any information would be appreciated. Thanks in advance.