Salviati
Salviati

Reputation: 788

Create a GET request that switch language on webapp using Flask

If I now search for 'localhost:5000/?lang=en' or 'localhost:5000/?lang=sv' I can switch between two languages. I use babel for the translation. Now I have written the app like this:

LANGUAGES = ['en', 'sv']

app = Flask(__name__)
app.config["BABEL_DEFAULT_LOCALE"] = LANGUAGES[0]
babel = Babel(app)

@babel.localeselector
def get_locale():
    if request.args.get("lang"):
        session["lang"] = request.args.get("lang")
    return session.get("lang", LANGUAGES[0])

@app.route("/", methods=['GET'])
def index():
    return render_template("index.html", me=me)

and in html file

<form method="GET">
  <input type="submit" name="lang" value="sv">
  <input type="submit" name="lang" value="en">
</form>

I know this is not a good way to do it, but honestly, I do not know how to do it otherwise. Here I have found an example of how I Should be able to solve it, but I have done it so different and after many many hours I have given up trying to do it that way.

What would satisfy me is just

A button that add the text '/?lang=sv' when I press it if it now is 'en' and reverse if current lang is 'sv'

This is acheved now (except that I have 2 buttons instead of one), but if I enter something like 'localhost:5000/?lang=sdfsdf' I get error code 500, witch I do not believe is particularly good to allow, I do not really know where I should add the logic to prevent it, also I know in my heart this is Not the right way of doing it! But it is the best I could come up with.

Upvotes: 0

Views: 700

Answers (1)

Eric Yang
Eric Yang

Reputation: 2750

You could have radio buttons to select a language of interest rather than having a submit button. The error code 500 isn't a bad thing in this case. You're not able to handle the input and error code 500 means that the server can't process the request. You can either add a custom page for 500 errors, or check in your server side code. Your index function can add the check for query parameters, and handle appropriately rather than just returning the rendered template.

if(LANGUAGES.index(request.args.get("lang")) != -1):
   # do something like set the session['lang'] = 'en'

Upvotes: 1

Related Questions