Ignas Butėnas
Ignas Butėnas

Reputation: 6307

Multilingual urls in flask

I just started to play with Flask, so very likely I just miss something obvious, but maybe it could be nice questions for others too look for the same answer :)

I want to create Flask app, which will listen of multi language URLs. So what I want to have is that one endpoint will listen on the /news/111 as same as for /naujiena/111 (Lithunian language for example).

So the one obvious solution is to give few routes to the view function, like:

@app.route('/news/<id>')
@app.route('/naujiena/<id>')
def news_view(id): pass

Which should work, but obviously it will pain in the (some intimate place) to add new language later or just to update the link.

Another solution I have in my mind is that I can have one file where I define real view function and then some "language view" files where I just grab the requests and then querying the real view functions from other file. Like

news.py

def news_view(id): pass

news_en.py

from news import news_view
@app.route('/news/<id>')
def news_view_en(id):
    return news_view(id)

news_lt.py

from news import news_view
@app.route('/naujiena/<id>')
def news_view_lt(id):
    return news_view(id)

This is not bad and at leats could be somehow nicely organized. But I bet there should be something I miss :) So guys, what is that? :) Any suggestions are welcome.

Thanks!

Upvotes: 3

Views: 1034

Answers (1)

Blender
Blender

Reputation: 298206

You can use the add_url_rule() function dynamically route the URLs:

view_functions = [news_view, foo_view, bar_view]

for view in ['news', 'foo', 'bar']:
  for translation in translations[view]:
     app.add_url_rule('/{}/'.format(translation), view, view_functions[view])

Upvotes: 4

Related Questions