Created
June 2, 2019 12:20
-
-
Save reinefjord/f5ce3f0aab50ef43e98adaecf2ad178a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import flask | |
import werkzeug | |
from teknologkoren_se_v2.translations import translations | |
def get_string(name): | |
return translations[name][get_locale()] | |
def get_locale(): | |
lang_code = (flask.g.get('lang_code') or flask.session.get('lang_code')) | |
if not lang_code: | |
lang_code = flask.request.accept_languages.best_match(['sv', 'en']) | |
return lang_code | |
def fix_missing_lang_code(): | |
if flask.g.get('lang_code') or flask.request.endpoint == 'static': | |
# Lang code is not missing. | |
return | |
# If g.lang_code is not set, the lang code in path is probably | |
# missing or misspelled/invalid. | |
# Get a MapAdapter, the object used for matching urls. | |
urls = flask.current_app.url_map.bind( | |
flask.current_app.config['SERVER_NAME'] | |
) | |
# Get whatever lang get_locale() decides (cookie or, if no cookie, | |
# default), and prepend it to the requested path. | |
proposed_lang = get_locale() | |
new_path = proposed_lang + flask.request.path | |
try: | |
# Does this new path match any view? | |
urls.match(new_path) | |
except werkzeug.routing.RequestRedirect as e: | |
# The new path results in a redirect. | |
return flask.redirect(e.new_url) | |
except (werkzeug.routing.MethodNotAllowed, werkzeug.routing.NotFound): | |
# The new path does not match anything, we allow the request | |
# to continue with the non-lang path. Probably 404. In case | |
# this request results in something that does want a lang | |
# code (error pages need it as main.html builds urls for the | |
# nav), we set it to whatever was proposed by get_locale(). | |
# If we don't set it AND the client does not have lang saved | |
# in a cookie, we'd get a 500. | |
flask.g.lang_code = proposed_lang | |
return None | |
# The new path matches a view! We redirect there. | |
return flask.redirect(new_path) | |
def url_for_other_lang(endpoint, view_args, fallback='index.index', **args): | |
if get_locale() == 'sv': | |
lang_code = 'en' | |
else: | |
lang_code = 'sv' | |
if (endpoint and (flask | |
.current_app | |
.url_map | |
.is_endpoint_expecting(endpoint, 'lang_code'))): | |
return flask.url_for(endpoint, | |
lang_code=lang_code, | |
**view_args or {}, | |
**args) | |
return flask.url_for(fallback, | |
lang_code=lang_code, | |
**view_args or {}, | |
**args) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment