add frontend language default parameter #6

This commit is contained in:
worldworm 2021-01-10 08:07:56 +00:00
parent 9fb974b7b1
commit 72b624db4c
3 changed files with 86 additions and 17 deletions

View file

@ -10,7 +10,7 @@ def get_remote_address():
return ip return ip
def create_app(char_limit=-1, req_limit=-1, ga_id=None, debug=False): def create_app(char_limit=-1, req_limit=-1, ga_id=None, debug=False, frontend_language_source="en", frontend_language_target="es"):
from app.init import boot from app.init import boot
boot() boot()
@ -20,6 +20,15 @@ def create_app(char_limit=-1, req_limit=-1, ga_id=None, debug=False):
if debug: if debug:
app.config['TEMPLATES_AUTO_RELOAD'] = True app.config['TEMPLATES_AUTO_RELOAD'] = True
# Map userdefined frontend languages to argos language object.
frontend_argos_language_source = next(iter([l for l in languages if l.code == frontend_language_source]), None)
frontend_argos_language_target = next(iter([l for l in languages if l.code == frontend_language_target]), None)
# Raise AttributeError to prevent app startup if user input is not valid.
if frontend_argos_language_source is None:
raise AttributeError(f"{frontend_language_source} as frontend source language is not supported.")
if frontend_argos_language_target is None:
raise AttributeError(f"{frontend_language_target} as frontend target language is not supported.")
if req_limit > 0: if req_limit > 0:
from flask_limiter import Limiter from flask_limiter import Limiter
limiter = Limiter( limiter = Limiter(
@ -201,6 +210,46 @@ def create_app(char_limit=-1, req_limit=-1, ga_id=None, debug=False):
except Exception as e: except Exception as e:
abort(500, description="Cannot translate text: %s" % str(e)) abort(500, description="Cannot translate text: %s" % str(e))
@app.route("/frontend/settings")
def frontend_settings():
"""
Retrieve frontend specific settings
---
tags:
- frontend
responses:
200:
description: frontend settings
schema:
id: frontend-settings
type: object
properties:
language:
type: object
properties:
source:
type: object
properties:
code:
type: string
description: Language code
name:
type: string
description: Human-readable language name (in English)
target:
type: object
properties:
code:
type: string
description: Language code
name:
type: string
description: Human-readable language name (in English)
"""
return jsonify({'language': {
'source': {'code': frontend_argos_language_source.code, 'name': frontend_argos_language_source.name},
'target': {'code': frontend_argos_language_target.code, 'name': frontend_argos_language_target.name}}
})
swag = swagger(app) swag = swagger(app)
swag['info']['version'] = "1.0" swag['info']['version'] = "1.0"

View file

@ -256,6 +256,7 @@ document.addEventListener('DOMContentLoaded', function(){
loading: true, loading: true,
error: "", error: "",
langs: [], langs: [],
settings: {},
sourceLang: "", sourceLang: "",
targetLang: "", targetLang: "",
@ -267,10 +268,33 @@ document.addEventListener('DOMContentLoaded', function(){
}, },
mounted: function(){ mounted: function(){
var self = this; var self = this;
var request = new XMLHttpRequest(); var requestSettings = new XMLHttpRequest();
request.open('GET', BaseUrl + '/languages', true); requestSettings.open('GET', BaseUrl + '/frontend/settings', true);
request.onload = function() { requestSettings.onload = function() {
if (this.status >= 200 && this.status < 400) {
// Success!
self.settings = JSON.parse(this.response);
self.sourceLang = self.settings.language.source.code;
self.targetLang = self.settings.language.target.code;
}else {
self.error = "Cannot load /frontend/settings";
self.loading = false;
}
};
requestSettings.onerror = function() {
self.error = "Error while calling /frontend/settings";
self.loading = false;
};
requestSettings.send();
var requestLanguages = new XMLHttpRequest();
requestLanguages.open('GET', BaseUrl + '/languages', true);
requestLanguages.onload = function() {
if (this.status >= 200 && this.status < 400) { if (this.status >= 200 && this.status < 400) {
// Success! // Success!
self.langs = JSON.parse(this.response); self.langs = JSON.parse(this.response);
@ -280,17 +304,7 @@ document.addEventListener('DOMContentLoaded', function(){
return; return;
} }
self.sourceLang = self.langs[0].code;
self.targetLang = self.langs[1].code;
self.charactersLimit = self.langs[0].charLimit; self.charactersLimit = self.langs[0].charLimit;
// TODO: update this when switching languages
// Set Spanish
for (var i = 1; i < self.langs.length; i++){
if (self.langs[i].code === "es"){
self.targetLang = "es";
}
}
self.loading = false; self.loading = false;
} else { } else {
@ -299,12 +313,12 @@ document.addEventListener('DOMContentLoaded', function(){
} }
}; };
request.onerror = function() { requestLanguages.onerror = function() {
self.error = "Error while calling /languages"; self.error = "Error while calling /languages";
self.loading = false; self.loading = false;
}; };
request.send(); requestLanguages.send();
}, },
updated: function(){ updated: function(){
M.FormSelect.init(this.$refs.sourceLangDropdown); M.FormSelect.init(this.$refs.sourceLangDropdown);

View file

@ -16,6 +16,10 @@ parser.add_argument('--debug', default=False, action="store_true",
help="Enable debug environment") help="Enable debug environment")
parser.add_argument('--ssl', default=None, action="store_true", parser.add_argument('--ssl', default=None, action="store_true",
help="Whether to enable SSL") help="Whether to enable SSL")
parser.add_argument('--frontend-language-source', type=str, default="en", metavar="<language code>",
help='Set frontend default language - source (%(default)s)')
parser.add_argument('--frontend-language-target', type=str, default="es", metavar="<language code>",
help='Set frontend default language - target (%(default)s)')
args = parser.parse_args() args = parser.parse_args()
@ -24,7 +28,9 @@ if __name__ == "__main__":
app = create_app(char_limit=args.char_limit, app = create_app(char_limit=args.char_limit,
req_limit=args.req_limit, req_limit=args.req_limit,
ga_id=args.ga_id, ga_id=args.ga_id,
debug=args.debug) debug=args.debug,
frontend_language_source=args.frontend_language_source,
frontend_language_target=args.frontend_language_target)
if args.debug: if args.debug:
app.run(host=args.host, port=args.port) app.run(host=args.host, port=args.port)
else: else: