コード例 #1
0
ファイル: views.py プロジェクト: ManGregory/microblog
def get_locale():
	if (g.user is not None) and (not g.user.is_anonymous()):
		if g.user.lang_id is not None:
			app.logger.info(g.user.lang.short_name)
			return g.user.lang.short_name
		else:
			accept_lang = request.accept_languages.best_match(LANGUAGES.keys())
			if accept_lang is None or (accept_lang == ''):
				accept_lang = 'en'			
			g.user.lang = Language.query.filter_by(short_name = accept_lang).first()
			db.session.add(g.user)
			db.session.commit()
			return g.user.lang.short_name
	else:
		return request.accept_languages.best_match(LANGUAGES.keys())
コード例 #2
0
def get_locale():
    print "hi"
    # for testing, hard code the language to show
    # return 'fr'
    print request.accept_languages
    # in production use the below to change language based on http 'accept-languages' header:
    return request.accept_languages.best_match(LANGUAGES.keys())
コード例 #3
0
ファイル: views.py プロジェクト: dan-may/translation
def get_locale():
    print "hi"
    # for testing, hard code the language to show
    # return 'fr'
    print request.accept_languages
    # in production use the below to change language based on http 'accept-languages' header:
    return request.accept_languages.best_match(LANGUAGES.keys())
コード例 #4
0
ファイル: views.py プロジェクト: Showfom/iwho.is
def get_locale():
    if request.args.get('lang'):
        g.lang = request.args.get('lang')
    if g.get('lang'):
        return g.lang
    g.lang = request.accept_languages.best_match(LANGUAGES.keys())
    return g.lang
コード例 #5
0
def get_locale():
    try:
        print('setted lang: '+session['lang'])
        return session['lang']
    except:
        print('default lang')
        return request.accept_languages.best_match(LANGUAGES.keys())
コード例 #6
0
ファイル: __init__.py プロジェクト: spetrovic450/ksvotes.org
 def ensure_lang_support():
     lang_code = g.get('lang_code', None)
     if lang_code and lang_code not in LANGUAGES.keys():
         app.logger.info(
             'ensure_lang_support failed to find %s in LANGUAGES' %
             (lang_code))
         return abort(404)
コード例 #7
0
def get_locale():
    try:
        language = getArgAsList(request, 'lang')[0]
    except:
        language = 'hi'
    print request.accept_languages.best_match(LANGUAGES.keys())
    return language
コード例 #8
0
ファイル: routes.py プロジェクト: Amadman/team-mcr
def get_locale():
    """Get current language."""
    try:
        language = session['language']
    except KeyError:
        language = None
    return language if language else request.accept_languages.best_match(
        LANGUAGES.keys())
コード例 #9
0
def get_locale():
    # if language forced
    if 'LANGUAGE'in app.config:
        if app.config['LANGUAGE'] in LANGUAGES.keys():
	    return app.config['LANGUAGE']
	else:
            print 'Language not found in Config - LANGUAGES'
    # else if a user is logged in, use the locale from the user settings
    user = getattr(g, 'user', None)
    
    if user is not None:
	print user.locale
        return user.locale
    # otherwise try to guess the language from the user accept
    # header the browser transmits.  We support de/fr/en in this
    # example.  The best match wins.
    return request.accept_languages.best_match(LANGUAGES.keys()) # 'it'
コード例 #10
0
ファイル: lang.py プロジェクト: FrancescaDr/nsvki.nl
def set_lang(lang):
    if lang not in LANGUAGES.keys():
        return redirect('page.index')

    rv = make_response(redirect(redirect_url()))
    rv.set_cookie('lang', lang)
    refresh()
    return rv
コード例 #11
0
 def index_view(self):
     placeholder_images = DataGetter.get_event_default_images()
     pages = DataGetter.get_all_pages()
     custom_placeholder = DataGetter.get_custom_placeholders()
     subtopics = DataGetter.get_event_subtopics()
     settings = get_settings()
     LANGUAGES.pop("en")
     if request.method == 'POST':
         dic = dict(request.form.copy())
         for key, value in dic.items():
             settings[key] = value[0]
             set_settings(**settings)
     return self.render(
         '/gentelella/admin/super_admin/content/content.html', pages=pages, settings=settings,
         placeholder_images=placeholder_images, subtopics=subtopics, custom_placeholder=custom_placeholder,
         languages=LANGUAGES
     )
コード例 #12
0
def get_locale():
    # if a user is logged in, use the locale from the user settings
    # user = getattr(g, 'user', None)
    # if user is not None:
    #     return user.locale
    # otherwise try to guess the language from the user accept
    # header the browser transmits.  We support de/fr/en in this
    # example.  The best match wins.
    return request.accept_languages.best_match(LANGUAGES.keys())
コード例 #13
0
ファイル: helpers.py プロジェクト: spetrovic450/ksvotes.org
def guess_locale():
    req_locale = request.accept_languages.best_match(LANGUAGES.keys())
    expl_locale = g.get('lang_code')
    def_locale = g.get('lang_code', current_app.config['BABEL_DEFAULT_LOCALE'])
    if def_locale not in LANGUAGES.keys():
        def_locale = current_app.config[
            'BABEL_DEFAULT_LOCALE']  # fix recursive 404 error
    current_app.logger.debug("req_locale %s - expl_locale %s - def_locale %s" %
                             (req_locale, expl_locale, def_locale))
    # if they differ prefer the explicit
    if expl_locale and expl_locale in LANGUAGES.keys(
    ) and req_locale != expl_locale:
        locale = expl_locale
    elif req_locale in LANGUAGES.keys():
        locale = req_locale
    else:
        locale = def_locale
    current_app.logger.debug("using locale %s" % (locale))
    return locale
コード例 #14
0
class UserForm(Form):
    nickname = StringField(lazy_gettext('Nickname'), [validators.data_required(),
                                                      validators.length(min=5, max=30)])
    email = EmailField(lazy_gettext('Email'), [validators.data_required(),
                                 validators.length(max=120)])
    delivery_mail_receive = BooleanField(lazy_gettext('Email notification of new goods arrival'), default=True)
    inv_lang = dict((v, k) for k, v in LANGUAGES.items())
    lang = [(v, k) for k, v in inv_lang.iteritems()]
    language = SelectField(lazy_gettext('Preferred language'), choices=lang)
    products_per_page = IntegerField(lazy_gettext('Number of products displayed per page'), [validators.NumberRange(min=3)],
                                     default=PRODUCTS_PER_PAGE)
コード例 #15
0
class EditUserForm(Form):
    nickname = StringField(lazy_gettext('User nickname'), [validators.data_required(),
                                        validators.length(max=64)])
    email = EmailField(lazy_gettext('Email'), [validators.data_required(),
                                 validators.length(max=120)])

    role = [(str(v), k) for k, v in iter(sorted(USER_ROLES.iteritems(), key=operator.itemgetter(1)))]
    role = SelectField(lazy_gettext('User role'), choices=role)
    customer = SelectField('Customer', coerce=int)
    maker = SelectField('Maker', coerce=int)

    inv_lang = dict((v, k) for k, v in LANGUAGES.items())
    lang = [(v, k) for k, v in inv_lang.iteritems()]
    language = SelectField(lazy_gettext('User language'), choices=lang)
コード例 #16
0
ファイル: views.py プロジェクト: dregor/flask
def before():
    g.languages = LANGUAGES
    g.locale = request.cookies.get('locale')
    if g.locale is None:
        g.locale = request.accept_languages.best_match(LANGUAGES.keys())

        @after_this_request
        def remember_language(response):
            response.set_cookie('locale', g.locale)
            return response

    g.search_form = SearchForm()
    if current_user and current_user.is_authenticated:
        current_user.see_you()
        g.roles = [role.role_name for role in current_user.roles]
コード例 #17
0
ファイル: babel.py プロジェクト: ijabz/critiquebrainz
def get_locale():
    supported_languages = LANGUAGES.keys()
    language_arg = request.args.get('l')
    if language_arg is not None:
        if language_arg in supported_languages:
            @after_this_request
            def remember_language(response):
                response.set_cookie('language', language_arg)

            return language_arg
    else:
        language_cookie = request.cookies.get('language')
        if language_cookie in supported_languages:
            return language_cookie

    return request.accept_languages.best_match(supported_languages)
コード例 #18
0
def get_language():
    """
    Determinate language, by request, cookies and POST data.
    :return: language code.
    """
    result = "en"
    lang_cookies = request.cookies.get('lang')
    if lang_cookies is None:
        result = request.accept_languages.best_match(LANGUAGES.keys())
    else:
        post = request.form
        if len(post) is 0:
            result = lang_cookies
        else:
            lang_post = post.get('lang', default=None)
            if lang_post is not None:
                result = lang_post
    return result
コード例 #19
0
ファイル: views.py プロジェクト: Toruitas/Python
def get_locale():
    """
    the function targeted by this selector above will be called before each request, to give us a chance to choose the
    language when producing its response.
    For now we will do something simple, we will just read the Accept-Lanugages header sent by the browser in the HTTP
    request and find the best-matching language from the list we support. This is simple, 'best_match' method does it
    for us.

    Accept-Languages header in most browsers is config'd by default with language selected at OS level, but all give
    users chance to select others. Users can provide a list of languages, each with a weight. Looks like:
    Accept-Language: da, en-gb;q=0.8, en;q=0.7
    Danish default weight=1 is preferred, followed by GB-English, finally with generic english.

    To translate text, use gettext(string to translate) within Python code, or {{ _('string')}} inside HTML
    :return:
    """
    #return 'es'
    return request.accept_languages.best_match(LANGUAGES.keys())  # temp set to spanish for testing
コード例 #20
0
class AddUserForm(Form):
    nickname = StringField(lazy_gettext('User nickname'), [validators.data_required(),
                                        validators.length(max=64)])
    password = PasswordField(lazy_gettext('User password'), [validators.data_required(),
                                          validators.length(min=5, max=30),
                                          validators.EqualTo('confirm', message=lazy_gettext('Passwords must match'))])
    confirm = PasswordField(lazy_gettext('Password confirmation'))
    email = EmailField(lazy_gettext('Email'), [validators.data_required(),
                                 validators.length(max=120)])

    role = [(str(v), k) for k, v in iter(sorted(USER_ROLES.iteritems(), key=operator.itemgetter(1)))]
    role = SelectField(lazy_gettext('User role'), choices=role)
    customer = SelectField('Customer', coerce=int)
    maker = SelectField('Maker', coerce=int)

    inv_lang = dict((v, k) for k, v in LANGUAGES.items())
    lang = [(v, k) for k, v in inv_lang.iteritems()]
    language = SelectField(lazy_gettext('User language'), choices=lang)
コード例 #21
0
def settings_general():
    """ Display general settings """
    if not logged_in():
        return redirect(url_for('general_routes.home'))

    misc = db_retrieve_table(
        current_app.config['MYCODO_DB_PATH'], Misc, entry='first')
    form_settings_general = flaskforms.SettingsGeneral()

    languages_sorted = sorted(LANGUAGES.items(), key=operator.itemgetter(1))

    if request.method == 'POST':
        form_name = request.form['form-name']
        if form_name == 'General':
            flaskutils.settings_general_mod(form_settings_general)
        return redirect('/settings/general')

    return render_template('settings/general.html',
                           misc=misc,
                           languages=languages_sorted,
                           form_settings_general=form_settings_general)
コード例 #22
0
ファイル: views.py プロジェクト: Pballer/prayer
def get_locale():
    headers = request.headers.get('User-Agent')
    app.logger.info('Header info: ' + headers)
    return request.accept_languages.best_match(LANGUAGES.keys()) or 'en'
コード例 #23
0
ファイル: views.py プロジェクト: rinand/microblog
def get_locale():
    return request.accept_languages.best_match(LANGUAGES.keys())
    
        if query.duration >= DATABASE_QUERY_TIMEOUT:
            app.logger.warning("SLOW QUERY: %s\nParameters: %s\nDuration: %fs\nContext: %s\n" % (query.statement, query.parameters, query.duration, query.context))
コード例 #24
0
def get_locale():
    return request.accept_languages.best_match(LANGUAGES.keys())
コード例 #25
0
def get_locale():
    """Return the best matched language supported."""
    return request.accept_languages.best_match(LANGUAGES.keys())
コード例 #26
0
ファイル: kilink.py プロジェクト: carriercomm/kilink
def get_locale():
    """Return the best matched language supported."""
    return request.accept_languages.best_match(LANGUAGES.keys())
コード例 #27
0
ファイル: views.py プロジェクト: m0r3n0/microblog
def get_locale():
    # BUG: al invocarse justo before_request siempre se selecciona el preferido, no el seleccionado
    l = getattr(g, 'locale', None)
    if l is not None:
        return g.locale
    return request.accept_languages.best_match(LANGUAGES.keys())
コード例 #28
0
ファイル: app.py プロジェクト: vjousse/vim-for-humans-website
def before():
    if request.view_args and 'lang_code' in request.view_args:
        if request.view_args['lang_code'] not in LANGUAGES.keys():
            return abort(404)
        g.current_lang = request.view_args['lang_code']
        request.view_args.pop('lang_code')
コード例 #29
0
def get_locale():
    """Get the locale to use for lang."""
    locale = request.accept_languages.best_match(LANGUAGES.keys())
    # return locale
    # Temporary
    return 'fr'
コード例 #30
0
def get_locale():
    try:
        return request.cookies["selected_lang"]
    except:
        return request.accept_languages.best_match(LANGUAGES.keys())
コード例 #31
0
ファイル: views.py プロジェクト: ichar/player.python
def get_locale():
    key = _validate('locale', request.args.get('locale'))
    return LANGUAGES.has_key(key) and LANGUAGES.get(key)[0] or DEFAUL_LANGUAGE
コード例 #32
0
ファイル: views.py プロジェクト: tledoux/spar-mets-viewer
def get_locale():
    """Retrieve locale based on available languages"""
    return request.accept_languages.best_match(LANGUAGES.keys())
コード例 #33
0
ファイル: __init__.py プロジェクト: 10280588/viaduct
def get_locale():
    # if a user is logged in, use the locale from the user settings
    if current_user and current_user.locale is not None and \
            not current_user.is_anonymous():
        return current_user.locale
    return request.accept_languages.best_match(LANGUAGES.keys())
コード例 #34
0
def get_locale():
    # 返回最匹配浏览器发送的request请求中指定的语言
    # print(request.accept_languages.best_match(LANGUAGES.keys()))
    return request.accept_languages.best_match(LANGUAGES.keys())
コード例 #35
0
ファイル: views.py プロジェクト: Tibodef/PythonBlog
def get_locale():
    if current_user and current_user.is_authenticated():
        return current_user.lang
    return request.accept_languages.best_match(LANGUAGES.keys())
コード例 #36
0
def get_locale():
    # We should get this from the config, but it fails, the same happens with timezone
    #return "es"
    return request.accept_languages.best_match(LANGUAGES.keys())
コード例 #37
0
ファイル: __init__.py プロジェクト: sasxa/mapload
 def locale(self):
   if self.request.get('lang'):
     return self.request.get('lang')
   else:
     return LANGUAGES.get(self.request.headers.get('X-AppEngine-Country')) or 'en'
コード例 #38
0
def get_locale():
    try:
        return request.cookies["selected_lang"]
    except:
        return request.accept_languages.best_match(LANGUAGES.keys())
コード例 #39
0
def get_locale():
    best_math_lang = request.accept_languages.best_match(LANGUAGES.keys())
    # app.logger.debug('best_math_lang: %s', best_math_lang)
    return best_math_lang
コード例 #40
0
ファイル: __init__.py プロジェクト: mndore/nsvki.nl
def get_locale():
    lang = request.cookies.get('lang')
    if not lang:
        lang = request.accept_languages.best_match(list(LANGUAGES.keys()))
    return lang
コード例 #41
0
ファイル: kant.py プロジェクト: Bytespeicher/KANT
def get_locale():
    # if a user is logged in, use the locale from the user settings
    user = getattr(g, 'user', None)
    if user is not None:
        return user.locale
    return request.accept_languages.best_match(LANGUAGES.keys())
コード例 #42
0
def get_locale():
    lang = request.accept_languages.best_match(LANGUAGES.keys())
    if g.user.is_authenticated():
        lang = g.user.language
    return lang
コード例 #43
0
ファイル: pybabel_init.py プロジェクト: zky001/me
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import sys

if sys.platform == 'win32':
    pybabel = r"C:\Python27\Scripts\pybabel.exe"
else:
    pybabel = "pybabel"

from config import LANGUAGES
os.system(pybabel + ' extract -F babel.cfg -k lazy_gettext -k T -o messages.pot ..\\')

for lang in LANGUAGES.keys():
    os.system('%s init -i messages.pot -d . -l "%s"' % (pybabel, lang.replace("-","_")))

os.system("pause")
os.unlink('messages.pot')

コード例 #44
0
ファイル: views.py プロジェクト: nankej/microblog_v2
def get_locale():
    return request.accept_languages.best_match(LANGUAGES.keys())
コード例 #45
0
ファイル: application.py プロジェクト: vicngtor/SilverWeb
def get_locale():
  if 'locale' in session:
    return session['locale']
  return request.accept_languages.best_match(LANGUAGES.keys())
コード例 #46
0
ファイル: lotg.py プロジェクト: tojaku/lotg
def get_locale():
    if g.user is not None:
        return g.user.language
    return request.accept_languages.best_match(LANGUAGES.keys())
コード例 #47
0
ファイル: app.py プロジェクト: rootart/aat-reinigung
def set_language_code(language=None):
    session[LANGUAGE_KEY] = language if language in LANGUAGES.keys(
    ) else BABEL_DEFAULT_LOCALE
    return redirect('/')