我只是想为两种语言运行flask web app我试过这个:
from flask import Flask, Blueprint, g
app = Flask(__name__)
bp = Blueprint('frontend', __name__, url_prefix='/<lang_code>')
@bp.url_defaults
def add_language_code(endpoint, values):
values.setdefault('lang_code', g.lang_code)
@bp.url_value_preprocessor
def pull_lang_code(endpoint, values):
g.lang_code = values.pop('lang_code')
@bp.route('/')
def hello():
return 'Hello ' +'!'
@bp.route('/about')
def about():
return 'Hello ' + '!'
app.register_blueprint(bp, url_defaults={'lang_code': 'en'})
if __name__ == '__main__':
app.run()
我的目标是为英语和格鲁吉亚语提供两种语言的网站。
我还需要知道在哪里添加另一种语言以及如何在HTML模板中切换语言?
答案 0 :(得分:3)
from flask import Flask, Blueprint, g, redirect, request, \
session, abort, render_template, url_for, Response, make_response
import datetime
app = Flask(__name__, template_folder='../templates')
main = Blueprint('main', __name__, url_prefix='/<lang_code>')
app.url_map.strict_slashes = False
app.secret_key='p9uyg7yuwriwjigjergkrgrrrr'
app.config['SUPPORTED_LANGUAGES'] = {'ka': 'Georgian', 'en': 'English'}
translation_list = [{ 'name': 'anytrans',
'ka': 'ქარ',
'en': 'Eng'},
{ 'name': 'any',
'ka': 'რამე',
'en': 'Any'},
]
@main.before_request
def ensure_lang_support():
lang_code = g.get('lang_code', None)
session['lang_code'] = lang_code
if lang_code and lang_code not in app.config['SUPPORTED_LANGUAGES'].keys():
''' fix for unsupported lang inserted '''
session['lang_code'] = '/ka/'
g.lang_code = 'ka'
return abort(404)
@main.context_processor
def inject_language():
return dict(sess_lang=g.lang_code)
@main.url_defaults
def add_language_code(endpoint, values):
if 'lang_code' in values or not g.get('lang_code', None):
return
if app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):
values['lang_code'] = g.lang_code
@main.url_value_preprocessor
def pull_lang_code(endpoint, values):
g.lang_code = values.pop('lang_code')
@main.route('/change/<new_lang_code>', methods=['POST','GET'])
def change(new_lang_code):
response = make_response(session["lang_code"])
session['lang_code'] = new_lang_code
response.set_cookie('lang_code', new_lang_code)
return response
@main.after_request
def set_lang_cookie(response):
response.set_cookie('lang_code', g.lang_code)
return response
@main.context_processor
def inject_translations():
return dict(translations=get_translation())
def get_translation():
lang = g.lang_code
translations = {}
for trans in translation_list:
translations.update({trans['name']:trans[lang]})
return translations
@main.route('/')
def index():
return render_template('index.html')
@main.route('/home/hale/')
def home():
url = url_for('main.index')
return render_template('index.html')
@app.route('/')
def redir():
lang = request.cookies.get('lang_code',None)
if lang:
return redirect('/'+ lang + '/')
else:
return redirect('/ka/')
if __name__ == '__main__':
app.run()
{% extends 'html/base.html' %}
{% block body%}
<script type="text/javascript">
function change_lang(id){
$.get('/{{sess_lang}}/change/'+id, function(data){
var pathname = window.location.pathname.split( '/' );
var newPathname = "";
for (i = 2; i < pathname.length; i++) {
newPathname += "/";
newPathname += pathname[i];
}
window.location.href = '/'+ id + newPathname
});
}
</script>
{% if sess_lang =='ka' %}
<p>{{sess_lang}}</p>
<p onclick='change_lang(id)' id="en" >change</p>
{% else %}
<p>{{sess_lang}}</p>
<p onclick='change_lang(id)' id="ka" >change</p>
{% endif %}
<div class="rame">
<a href="/">Home</a>
<a href="/{{sess_lang}}/home/hale/">Home</a>
</div>
{% endblock %}