I have one server with flask application instance and have several domain which mapped to this server by DNS.
My site must support several languages by host and prefix:
mysite.com - english
mysite.com/fr - franch
mysite.ru - russian
mysite.ru/by - belarusian
localhost or other unknown host without language prefix - default language (english)
I implemented it with double route registration /endpoint
and /<lang>/endpoint
and reloaded url_for
function and it work, but now I must implement custom error pages for abort
function:
mysite.com/wrong-url-there - mysite.com/404.html (english)
mysite.com/fr/wrong-url-there - mysite.com/fr/404.html (franch)
mysite.ru/wrong-url-there - mysite.ru/404.html (russian)
mysite.ru/by/wrong-url-there - mysite.ru/by/404.html (belorusian)
And I don't see solution for this. I think my implementation bad and I must improve it. I think I must create one instance of application for each site language root with predefined language for it or use blueprint, but I don't find solution for me yet.
Is anybody can give me advice how resolve this url multilanguages support with flask or wsgi or nginx?
Disclaimer: This code is not tested. I am just giving you a ballpark idea of how to approach this.
I suggest you use blueprints in combination with an extension like Flask-Babel. For example, you can do something like:
views.py
Then in your application package (usually
__init__.py
) , you can do:__init__.py
..and so on
Your directory structure could look like:
Flask-Babel would help you translate the 404.html etc.
My own solution:
I don't use blueprints there because I also use
flask-login
and I can't set several login pages with different languages for each blueprint. For example if page required login, flask redirect me to login page and I must update language for this page. Also login pages can't be asmysite.com/login
,mysite.com/fr/login
and etc without several redirections.UPD: I can't use
request.view_args
for detect language or redirection, because on this case I can't detect language for error pages asmysite.com/fr/wrong-page-there
(can't detectendpoint
andview_args
). To avoid this problem I can use hask: add url rule as/<lang_code>/<path:path>
and raise 404 error there.I worked on something similar few months back. I modified it a bit and pushed to github. You can do what codegeek suggested if you are unable to make your templates language neutral. With this method you can cut down on the template files needed.
https://github.com/scragg0x/Flask-Localisation-Example
mysite.py
tests.py
It's in the official doc: http://flask.pocoo.org/docs/patterns/urlprocessors/ (This is basically the same answer as Matthew Scragg's).