几个月前我做过类似的事情。我对其进行了一些修改并推送到了 github。如果您无法使模板语言中立,您可以执行 codegeek 建议的操作。使用这种方法,您可以减少所需的模板文件。
https://github.com/scragg0x/Flask-Localisation-Example
我的网站.py
from flask import Flask, Blueprint, g, redirect, request
app = Flask(__name__)
mod = Blueprint('mysite', __name__, url_prefix='/<lang_code>')
sites = {
'mysite.com': 'en',
'myothersite.com': 'fr'
}
@app.url_defaults
def add_language_code(endpoint, values):
values.setdefault('lang_code', g.lang_code)
@app.url_value_preprocessor
def pull_lang_code(endpoint, values):
url = request.url.split('/', 3)
g.lang_code = sites[url[2]]
@mod.url_defaults
def add_language_code(endpoint, values):
values.setdefault('lang_code', g.lang_code)
@mod.url_value_preprocessor
def pull_lang_code(endpoint, values):
g.lang_code = values.pop('lang_code')
@app.route('/')
@mod.route('/')
def index():
# Use g.lang_code to pull localized data for template
return 'lang = %s' % g.lang_code
app.register_blueprint(mod)
测试.py
import os
import unittest
import re
import requests
import urllib2
import json
from mysite import app
class MySiteTestCase(unittest.TestCase):
def setUp(self):
app.config['TESTING'] = True
app.config['SERVER_NAME'] = 'mysite.com'
self.domain = 'http://mysite.com/'
self.app = app.test_client()
def tearDown(self):
pass
def test_en_index(self):
rv = self.app.get('/en/', self.domain)
self.assertEqual(rv.data, 'lang = en')
print self.domain, rv.data
def test_fr_index(self):
rv = self.app.get('/fr/', self.domain)
self.assertEqual(rv.data, 'lang = fr')
print self.domain, rv.data
def test_default(self):
rv = self.app.get('/', self.domain)
self.assertEqual(rv.data, 'lang = en')
print self.domain, rv.data
class MyOtherSiteTestCase(unittest.TestCase):
def setUp(self):
app.config['TESTING'] = True
app.config['SERVER_NAME'] = 'myothersite.com'
self.domain = 'http://myothersite.com/'
self.app = app.test_client()
def tearDown(self):
pass
def test_en_index(self):
rv = self.app.get('/en/', self.domain)
self.assertEqual(rv.data, 'lang = en')
print self.domain, rv.data
def test_fr_index(self):
rv = self.app.get('/fr/', self.domain)
self.assertEqual(rv.data, 'lang = fr')
print self.domain, rv.data
def test_default(self):
rv = self.app.get('/', self.domain)
self.assertEqual(rv.data, 'lang = fr')
print self.domain, rv.data
if __name__ == '__main__':
unittest.main()