Exemple #1
0
 def validate_locale(form, field):
     """Validate whether the user provided locale is a valid locale."""
     try:
         Locale(field.data)
     except UnknownLocaleError:
         raise ValidationError(
             _("Please select a valid locale from above."))
Exemple #2
0
def list_locales():
    """Get a list of available :class:`babel.core.Locale` objects.

    Whatever translations the system provides, "en" should always
    appear in the list.  The returned list should be sorted in the order
    of display names, which may be vary in different languages.

    :return: :class:`list` of :class:`babel.core.Locale` objects.
    """
    ret = [Locale('en')] + babel.list_translations()
    return sorted(ret, cmp=lambda a, b: cmp(a.display_name, b.display_name))
Exemple #3
0
		def load_meta(path, locale):
			meta = dict()

			meta_path = os.path.join(path, "meta.yaml")
			if os.path.isfile(meta_path):
				import yaml
				try:
					with open(meta_path) as f:
						meta = yaml.safe_load(f)
				except:
					pass
				else:
					import datetime
					if "last_update" in meta and isinstance(meta["last_update"], datetime.datetime):
						meta["last_update"] = (meta["last_update"] - datetime.datetime(1970,1,1)).total_seconds()

			l = Locale.parse(locale)
			meta["locale"] = locale
			meta["locale_display"] = l.display_name
			meta["locale_english"] = l.english_name
			return meta
Exemple #4
0
def init_app(app):
    babel = Babel(app)

    app.config['LANGUAGES'] = {}
    for language in app.config['SUPPORTED_LANGUAGES']:
        app.config['LANGUAGES'][
            language] = Locale.parse(language).language_name

    @app.after_request
    def call_after_request_callbacks(response):
        for callback in getattr(g, 'after_request_callbacks', ()):
            callback(response)
        return response

    def after_this_request(f):
        if not hasattr(g, 'after_request_callbacks'):
            g.after_request_callbacks = []
        g.after_request_callbacks.append(f)
        return f

    @babel.localeselector
    def get_locale():
        supported_languages = app.config['SUPPORTED_LANGUAGES']
        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)
        def load_meta(path, locale):
            meta = dict()

            meta_path = os.path.join(path, "meta.yaml")
            if os.path.isfile(meta_path):
                import yaml
                try:
                    with open(meta_path) as f:
                        meta = yaml.safe_load(f)
                except:
                    pass
                else:
                    import datetime
                    if "last_update" in meta and isinstance(
                            meta["last_update"], datetime.datetime):
                        meta["last_update"] = (
                            meta["last_update"] -
                            datetime.datetime(1970, 1, 1)).total_seconds()

            l = Locale.parse(locale)
            meta["locale"] = locale
            meta["locale_display"] = l.display_name
            meta["locale_english"] = l.english_name
            return meta
Exemple #6
0
def get_best_locale_name(locale_names):
    """Select the best matching locale from `locale_names` according to
    current request.

    The locales are evaluated according to the language, script and territory.
    If no best choice is found, fallback to ``config.DEFAULT_LOCALE``.
    Moreover, if even ``config.DEFAULT_LOCALE`` does not appear in
    `locale_names`, choose the last item in `locale_names`.

    Usage:

    .. code-block:: python

        # If current user prefers zh-CN, or zh-TW.
        >>> get_best_locale_name(['zh-cn', 'en'])
        'zh-cn'

        # If current user prefers en-US.
        >>> get_best_locale_name(['zh-cn', 'en'])
        'en'

        # If current user prefers ja-JP, and default locale is zh-CN.
        >>> get_best_locale_name(['zh-cn', 'en'])
        'zh-cn'

        # If current user prefers ja-JP, and default locale is zh-CN.
        >>> get_best_locale_name(['fr', 'en'])
        'en'

    :param locale_names: List of alternative locale names.
    :type locale_names: :class:`list`

    :return: The best matching or fallback locale name.
    :rtype: :class:`str`
    """

    top_score = 0
    top_name = None
    req_locale = get_locale()

    for name in locale_names:
        l = Locale.parse(name.replace('-', '_'))
        # If locale object is the same, return True at once
        if l == req_locale:
            return name
        # If language not match, give up this locale
        if l.language != req_locale.language:
            continue
        # Exam the matched score
        score = 0
        # script match, give 5
        if l.script == req_locale.script:
            score += 5
        # territory match, give 3
        if l.territory == req_locale.territory:
            score += 3
        # variant match, give 3
        # TODO: check these score weights
        if l.variant == req_locale.variant:
            score += 3
        # Update top_name if > top_score
        if score > top_score:
            top_name = name
            top_score = score

    # Fallback to default locale or last locale
    if top_name is None:
        if app.config['DEFAULT_LOCALE'] in locale_names:
            top_name = app.config['DEFAULT_LOCALE']
        else:
            top_name = locale_names[-1]
    return top_name
Exemple #7
0
def get_best_locale_name(locale_names):
    """Select the best matching locale from `locale_names` according to
    current request.

    The locales are evaluated according to the language, script and territory.
    If no best choice is found, fallback to ``config.DEFAULT_LOCALE``.
    Moreover, if even ``config.DEFAULT_LOCALE`` does not appear in
    `locale_names`, choose the last item in `locale_names`.

    Usage:

    .. code-block:: python

        # If current user prefers zh-CN, or zh-TW.
        >>> get_best_locale_name(['zh-cn', 'en'])
        'zh-cn'

        # If current user prefers en-US.
        >>> get_best_locale_name(['zh-cn', 'en'])
        'en'

        # If current user prefers ja-JP, and default locale is zh-CN.
        >>> get_best_locale_name(['zh-cn', 'en'])
        'zh-cn'

        # If current user prefers ja-JP, and default locale is zh-CN.
        >>> get_best_locale_name(['fr', 'en'])
        'en'

    :param locale_names: List of alternative locale names.
    :type locale_names: :class:`list`

    :return: The best matching or fallback locale name.
    :rtype: :class:`str`
    """

    top_score = 0
    top_name = None
    req_locale = get_locale()

    for name in locale_names:
        l = Locale.parse(name.replace('-', '_'))
        # If locale object is the same, return True at once
        if l == req_locale:
            return name
        # If language not match, give up this locale
        if l.language != req_locale.language:
            continue
        # Exam the matched score
        score = 0
        # script match, give 5
        if l.script == req_locale.script:
            score += 5
        # territory match, give 3
        if l.territory == req_locale.territory:
            score += 3
        # variant match, give 3
        # TODO: check these score weights
        if l.variant == req_locale.variant:
            score += 3
        # Update top_name if > top_score
        if score > top_score:
            top_name = name
            top_score = score

    # Fallback to default locale or last locale
    if top_name is None:
        if app.config['DEFAULT_LOCALE'] in locale_names:
            top_name = app.config['DEFAULT_LOCALE']
        else:
            top_name = locale_names[-1]
    return top_name