• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python localedata.exists函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中babel.localedata.exists函数的典型用法代码示例。如果您正苦于以下问题:Python exists函数的具体用法?Python exists怎么用?Python exists使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了exists函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_locale_argument_acceptance

def test_locale_argument_acceptance():
    # Testing None input.
    normalized_locale = localedata.normalize_locale(None)
    assert normalized_locale == None
    locale_exist = localedata.exists(None)
    assert locale_exist == False

    # # Testing list input.
    normalized_locale = localedata.normalize_locale(['en_us', None])
    assert normalized_locale == None
    locale_exist = localedata.exists(['en_us', None])
    assert locale_exist == False
开发者ID:cloudera,项目名称:hue,代码行数:12,代码来源:test_localedata.py


示例2: get_locale

def get_locale():
  locale = flask.request.cookies.get('locale', config.LOCALE_DEFAULT)
  if locale not in config.LOCALE:
    locale = config.LOCALE_DEFAULT
  if not localedata.exists(locale):
    locale = 'en'
  return locale
开发者ID:NamPNQ,项目名称:gae-init-babel,代码行数:7,代码来源:auth.py


示例3: __init__

    def __init__(self, language, territory=None, script=None, variant=None):
        """Initialize the locale object from the given identifier components.

        >>> locale = Locale('en', 'US')
        >>> locale.language
        'en'
        >>> locale.territory
        'US'

        :param language: the language code
        :param territory: the territory (country or region) code
        :param script: the script code
        :param variant: the variant code
        :raise `UnknownLocaleError`: if no locale data is available for the
                                     requested locale
        """
        self.language = language
        self.territory = territory
        self.script = script
        self.variant = variant
        self.__data = None

        identifier = str(self)
        if not localedata.exists(identifier):
            raise UnknownLocaleError(identifier)
开发者ID:keitheis,项目名称:babel,代码行数:25,代码来源:core.py


示例4: get_jinja_env

def get_jinja_env(template_loader, locale):
    """
    Set up the Jinja environment, 

    (In the future we may have another system for providing theming;
    for now this is good enough.)
    """
    setup_gettext(locale)

    # If we have a jinja environment set up with this locale, just
    # return that one.
    if SETUP_JINJA_ENVS.has_key(locale):
        return SETUP_JINJA_ENVS[locale]

    template_env = jinja2.Environment(
        loader=template_loader, autoescape=True,
        extensions=['jinja2.ext.i18n', 'jinja2.ext.autoescape'])

    template_env.install_gettext_callables(
        mg_globals.translations.gettext,
        mg_globals.translations.ngettext)

    # All templates will know how to ...
    # ... fetch all waiting messages and remove them from the queue
    template_env.globals['fetch_messages'] = messages.fetch_messages

    if exists(locale):
        SETUP_JINJA_ENVS[locale] = template_env

    return template_env
开发者ID:OpenSourceInternetV2,项目名称:mediagoblin,代码行数:30,代码来源:util.py


示例5: _contextual_locale

def _contextual_locale(context):
    """Return locale from the context, falling back to a default if invalid."""
    request = context.get("request")
    locale = request.LANGUAGE_CODE
    if not localedata.exists(locale):
        locale = settings.LANGUAGE_CODE
    return locale
开发者ID:rivaxel,项目名称:kitsune,代码行数:7,代码来源:helpers.py


示例6: __init__

 def __init__(self, language, territory = None, script = None, variant = None):
     self.language = language
     self.territory = territory
     self.script = script
     self.variant = variant
     self.__data = None
     identifier = str(self)
     if not localedata.exists(identifier):
         raise UnknownLocaleError(identifier)
开发者ID:bizonix,项目名称:DropBoxLibrarySRC,代码行数:9,代码来源:core.py


示例7: _format_decimal

def _format_decimal(num, format=None):
    """Returns the string of a number formatted for the current language.

    Uses django's translation.get_language() to find the current language from
    the request.
    Falls back to the default language if babel does not support the current.

    """
    lang = translation.get_language()
    if not localedata.exists(lang):
        lang = settings.LANGUAGE_CODE
    locale = Locale(translation.to_locale(lang))
    return Format(locale).decimal(num, format)
开发者ID:Acidburn0zzz,项目名称:kitsune,代码行数:13,代码来源:form_fields.py


示例8: get_jinja_env

def get_jinja_env(template_loader, locale):
    """
    Set up the Jinja environment,

    (In the future we may have another system for providing theming;
    for now this is good enough.)
    """
    set_thread_locale(locale)

    # If we have a jinja environment set up with this locale, just
    # return that one.
    if locale in SETUP_JINJA_ENVS:
        return SETUP_JINJA_ENVS[locale]

    # jinja2.StrictUndefined will give exceptions on references
    # to undefined/unknown variables in templates.
    template_env = jinja2.Environment(
        loader=template_loader,
        autoescape=True,
        undefined=jinja2.StrictUndefined,
        extensions=["jinja2.ext.i18n", "jinja2.ext.autoescape", TemplateHookExtension],
    )

    template_env.install_gettext_callables(
        mg_globals.thread_scope.translations.ugettext, mg_globals.thread_scope.translations.ungettext
    )

    # All templates will know how to ...
    # ... fetch all waiting messages and remove them from the queue
    # ... construct a grid of thumbnails or other media
    # ... have access to the global and app config
    template_env.globals["fetch_messages"] = messages.fetch_messages
    template_env.globals["app_config"] = mg_globals.app_config
    template_env.globals["global_config"] = mg_globals.global_config
    template_env.globals["version"] = _version.__version__
    template_env.globals["auth"] = mg_globals.app.auth

    template_env.filters["urlencode"] = url_quote_plus

    # add human readable fuzzy date time
    template_env.globals["timesince"] = timesince

    # allow for hooking up plugin templates
    template_env.globals["get_hook_templates"] = get_hook_templates

    template_env.globals = hook_transform("template_global_context", template_env.globals)

    if exists(locale):
        SETUP_JINJA_ENVS[locale] = template_env

    return template_env
开发者ID:RichoHan,项目名称:MediaGoblin,代码行数:51,代码来源:template.py


示例9: __init__

    def __init__(self):
        from pylons import config

        # Get names of the locales
        # (must be a better way than scanning for i18n directory?)
        known_locales = ["en"] + [
            locale_name for locale_name in os.listdir(i18n_path) if localedata.exists(locale_name)
        ]
        self._locale_names, self._default_locale_name = self._work_out_locales(known_locales, config)
        self._locale_objects = map(Locale.parse, self._locale_names)
        self._default_locale_object = Locale.parse(self._default_locale_name)

        self._aliases = LOCALE_ALIASES
        self._aliases["pt"] = "pt_BR"  # Default Portuguese language to
开发者ID:jasonzou,项目名称:ckan,代码行数:14,代码来源:i18n.py


示例10: _get_locales

def _get_locales():
    # FIXME this wants cleaning up and merging with get_locales_from_config()
    assert not config.get('lang'), \
        ('"lang" config option not supported - please use ckan.locale_default '
         'instead.')
    locales_offered = config.get('ckan.locales_offered', '').split()
    filtered_out = config.get('ckan.locales_filtered_out', '').split()
    locale_default = config.get('ckan.locale_default', 'en')
    locale_order = config.get('ckan.locale_order', '').split()

    locales = ['en']
    if config.get('ckan.i18n_directory'):
        i18n_path = os.path.join(config.get('ckan.i18n_directory'), 'i18n')
    else:
        i18n_path = os.path.dirname(ckan.i18n.__file__)
    locales += [l for l in os.listdir(i18n_path) if localedata.exists(l)]

    assert locale_default in locales, \
        'default language "%s" not available' % locale_default

    locale_list = []
    for locale in locales:
        # no duplicates
        if locale in locale_list:
            continue
        # if offered locales then check locale is offered
        if locales_offered and locale not in locales_offered:
            continue
        # remove if filtered out
        if locale in filtered_out:
            continue
        # ignore the default as it will be added first
        if locale == locale_default:
            continue
        locale_list.append(locale)
    # order the list if specified
    ordered_list = [locale_default]
    for locale in locale_order:
        if locale in locale_list:
            ordered_list.append(locale)
            # added so remove from our list
            locale_list.remove(locale)
    # add any remaining locales not ordered
    ordered_list += locale_list

    return ordered_list
开发者ID:HatemAlSum,项目名称:ckan,代码行数:46,代码来源:i18n.py


示例11: get_gettext_translation

def get_gettext_translation(locale):
    """
    Return the gettext instance based on this locale
    """
    # Later on when we have plugins we may want to enable the
    # multi-translations system they have so we can handle plugin
    # translations too

    # TODO: fallback nicely on translations from pt_PT to pt if not
    # available, etc.
    if locale in SETUP_GETTEXTS:
        this_gettext = SETUP_GETTEXTS[locale]
    else:
        this_gettext = gettext.translation(
            'mediagoblin', TRANSLATIONS_PATH, [locale], fallback=True)
        if localedata.exists(locale):
            SETUP_GETTEXTS[locale] = this_gettext
    return this_gettext
开发者ID:sebastiansam55,项目名称:mediagoblin,代码行数:18,代码来源:translate.py


示例12: setup_gettext

def setup_gettext(locale):
    """
    Setup the gettext instance based on this locale
    """
    # Later on when we have plugins we may want to enable the
    # multi-translations system they have so we can handle plugin
    # translations too

    # TODO: fallback nicely on translations from pt_PT to pt if not
    # available, etc.
    if SETUP_GETTEXTS.has_key(locale):
        this_gettext = SETUP_GETTEXTS[locale]
    else:
        this_gettext = gettext.translation(
            'mediagoblin', TRANSLATIONS_PATH, [locale], fallback=True)
        if exists(locale):
            SETUP_GETTEXTS[locale] = this_gettext

    mg_globals.setup_globals(
        translations=this_gettext)
开发者ID:OpenSourceInternetV2,项目名称:mediagoblin,代码行数:20,代码来源:util.py


示例13: format_price

def format_price(value, currency):
    """
    Format decimal value as currency
    """
    try:
        value = Decimal(value)
    except (TypeError, InvalidOperation):
        return ''
    language = get_language()
    if not language:
        language = settings.LANGUAGE_CODE
    locale_code = to_locale(language)
    if not localedata.exists(locale_code):
        localedata.load(locale_code)
    locale = Locale(locale_code)
    currency_format = locale.currency_formats.get('standard')
    pattern = currency_format.pattern
    pattern = re.sub(
        '(\xa4+)', '<span class="currency">\\1</span>', pattern)
    result = format_currency(value, currency, pattern, locale=locale_code)
    return mark_safe(result)
开发者ID:pcompassion,项目名称:django-prices,代码行数:21,代码来源:prices_i18n.py


示例14: get_jinja_env

def get_jinja_env(template_loader, locale):
    """
    Set up the Jinja environment,

    (In the future we may have another system for providing theming;
    for now this is good enough.)
    """
    mg_globals.thread_scope.translations = get_gettext_translation(locale)

    # If we have a jinja environment set up with this locale, just
    # return that one.
    if SETUP_JINJA_ENVS.has_key(locale):
        return SETUP_JINJA_ENVS[locale]

    # jinja2.StrictUndefined will give exceptions on references
    # to undefined/unknown variables in templates.
    template_env = jinja2.Environment(
        loader=template_loader, autoescape=True,
        undefined=jinja2.StrictUndefined,
        extensions=['jinja2.ext.i18n', 'jinja2.ext.autoescape'])

    template_env.install_gettext_callables(
        mg_globals.thread_scope.translations.ugettext,
        mg_globals.thread_scope.translations.ungettext)

    # All templates will know how to ...
    # ... fetch all waiting messages and remove them from the queue
    # ... construct a grid of thumbnails or other media
    # ... have access to the global and app config
    template_env.globals['fetch_messages'] = messages.fetch_messages
    template_env.globals['app_config'] = mg_globals.app_config
    template_env.globals['global_config'] = mg_globals.global_config

    template_env.filters['urlencode'] = url_quote_plus

    if exists(locale):
        SETUP_JINJA_ENVS[locale] = template_env

    return template_env
开发者ID:imclab,项目名称:mediagoblin,代码行数:39,代码来源:template.py


示例15: entry

def entry():
    if not request.args.get('id'):
        return jsonerror("Missing required argument 'id'.", 400)
    if request.args['id'] not in db['entries']:
        return jsonerror('Undefined entry.', 404)
    if 'locale' in request.args and \
       not localedata.exists(request.args['locale']):
        return jsonerror('Invalid locale.', 400)

    entry = db['entries'][request.args['id']]
    data = dict(id=entry.id, type=entry.type)
    if hasattr(entry, 'affixes'):
        data['affixes'] = [affix.encode('utf-8') for affix in entry.affixes]
    if hasattr(entry, 'class_'):
        data['class'] = entry.class_

    locale = request.args.get('locale')
    if entry.history(locale):
        definition = entry.history(locale).newest.object
        data['definition'] = definition.definition
        data['notes'] = definition.notes
    return jsonify(data)
开发者ID:dag,项目名称:stutuz,代码行数:22,代码来源:api.py


示例16: datetimeformat

def datetimeformat(context, value, format='shortdatetime'):
    """
    Returns date/time formatted using babel's locale settings. Uses the
    timezone from settings.py
    """
    if not isinstance(value, datetime.datetime):
        # Expecting date value
        raise ValueError

    tzinfo = timezone(settings.TIME_ZONE)
    tzvalue = tzinfo.localize(value)
    # Babel uses underscore as separator.
    locale = context['request'].locale
    if not localedata.exists(locale):
        locale = settings.LANGUAGE_CODE
    locale = locale.replace('-', '_')

    # If within a day, 24 * 60 * 60 = 86400s
    if format == 'shortdatetime':
        # Check if the date is today
        if value.toordinal() == datetime.date.today().toordinal():
            formatted = _lazy('Today at %s') % format_time(
                                    tzvalue, format='short', locale=locale)
        else:
            formatted = format_datetime(tzvalue, format='short', locale=locale)
    elif format == 'longdatetime':
        formatted = format_datetime(tzvalue, format='long', locale=locale)
    elif format == 'date':
        formatted = format_date(tzvalue, locale=locale)
    elif format == 'time':
        formatted = format_time(tzvalue, locale=locale)
    elif format == 'datetime':
        formatted = format_datetime(tzvalue, locale=locale)
    else:
        # Unknown format
        raise DateTimeFormatError

    return jinja2.Markup('<time datetime="%s">%s</time>' % \
                         (tzvalue.isoformat(), formatted))
开发者ID:chowse,项目名称:kitsune,代码行数:39,代码来源:helpers.py


示例17: get_jinja_env

def get_jinja_env(app, template_loader, locale):
    """
    Set up the Jinja environment,

    (In the future we may have another system for providing theming;
    for now this is good enough.)
    """
    set_thread_locale(locale)

    # If we have a jinja environment set up with this locale, just
    # return that one.
    if locale in SETUP_JINJA_ENVS:
        return SETUP_JINJA_ENVS[locale]

    # The default config does not require a [jinja2] block.
    # You may create one if you wish to enable additional jinja2 extensions,
    # see example in config_spec.ini 
    jinja2_config = app.global_config.get('jinja2', {})
    local_exts = jinja2_config.get('extensions', [])

    # jinja2.StrictUndefined will give exceptions on references
    # to undefined/unknown variables in templates.
    template_env = jinja2.Environment(
        loader=template_loader, autoescape=True,
        undefined=jinja2.StrictUndefined,
        extensions=[
            'jinja2.ext.i18n', 'jinja2.ext.autoescape',
            TemplateHookExtension] + local_exts)

    if six.PY2:
        template_env.install_gettext_callables(mg_globals.thread_scope.translations.ugettext,
                                           mg_globals.thread_scope.translations.ungettext)
    else:
        template_env.install_gettext_callables(mg_globals.thread_scope.translations.gettext,
                                           mg_globals.thread_scope.translations.ngettext)

    # All templates will know how to ...
    # ... fetch all waiting messages and remove them from the queue
    # ... construct a grid of thumbnails or other media
    # ... have access to the global and app config
    # ... determine if the language is rtl or ltr
    template_env.globals['fetch_messages'] = messages.fetch_messages
    template_env.globals['app_config'] = app.app_config
    template_env.globals['global_config'] = app.global_config
    template_env.globals['version'] = _version.__version__
    template_env.globals['auth'] = app.auth
    template_env.globals['is_rtl'] = is_rtl(locale)
    template_env.filters['urlencode'] = url_quote_plus

    # add human readable fuzzy date time
    template_env.globals['timesince'] = timesince

    # allow for hooking up plugin templates
    template_env.globals['get_hook_templates'] = get_hook_templates

    template_env.globals = hook_transform(
        'template_global_context', template_env.globals)

    #### THIS IS TEMPORARY, PLEASE FIX IT
    ## Notifications stuff is not yet a plugin (and we're not sure it will be),
    ## but it needs to add stuff to the context.  This is THE WRONG WAY TO DO IT
    from mediagoblin import notifications
    template_env.globals['get_notifications'] = notifications.get_notifications
    template_env.globals[
        'get_notification_count'] = notifications.get_notification_count
    template_env.globals[
        'get_comment_subscription'] = notifications.get_comment_subscription

    if exists(locale):
        SETUP_JINJA_ENVS[locale] = template_env

    return template_env
开发者ID:ausbin,项目名称:mediagoblin,代码行数:72,代码来源:template.py


示例18: translate

def translate():
    '''
    Edita la traducción a un idioma
    '''
    def fix_values(entry,sample=False):
        '''
        Si la traduccion contiene campos de valores los sustituimos por ______[X] y ponemos un ejemplo de uso,
        además se eliminan los saltos de linea
        '''
        result=re.finditer(r'(%\(([^\)]+)\)([s|d]))', entry.msgstr)
        subs=dict()
        # se cargan los ejemplos si es necesario
        if entry.msgid in samples:
            subs=samples[entry.msgid]

        # para cada valor encontrado se sustituye por _____[X]
        for i,item in enumerate(result):
            entry.msgstr=entry.msgstr.replace(item.group(1),"_____["+str(i+1)+"]")
            # para los ejemplos numericos se utiliza uno aleatorio
            if item.group(3)=="d":
                subs[item.group(2)]=random.randint(2,10)

        if sample:
            if subs!={}:
                return (entry.msgid,(entry.msgstr,_(entry.msgid,**subs)))
            else:
                return (entry.msgid,(entry.msgstr,False))

        # se sustituyen los saltos de linea html y se devuelve todo
        return (entry.msgid,entry.msgstr.replace("<br>","\n").replace("<br />","\n").replace("<br/>","\n") if "<br" in entry.msgstr else entry.msgstr)

    languages = localedata.load(g.lang)["languages"]
    keystrcoll = cmp_to_key(locale.strcoll)
    form = None
    forml = SelectLanguageForm(request.form)
    forml.lang.choices = [("", "-- "+_("choose_language")+" --")] + sorted(
        ((code, localedata.load(code)["languages"][code].capitalize()+" ("+languages[code].capitalize()+")")
            for code, language in languages.items()
            if code in current_app.config["TRANSLATE_LANGS"] and not code in current_app.config["LANGS"] and localedata.exists(code) and code in localedata.load(code)["languages"]),
        key=lambda x: keystrcoll(x[1]))

    total=99999
    no_translation=0
    msgids=[]
    lang_edit = request.args.get("lang")
    if not lang_edit in languages:
        lang_edit = None

    formfields = {}
    # mostrar el idioma a traducir
    if lang_edit is not None:
        forml.lang.default=lang_edit
        # cargar idioma actual
        current_lang = dict(fix_values(entry,True) for entry in polib.pofile(lang_path(g.lang)))

        # si existe el idioma se carga, sino vacio
        lpath = lang_path(lang_edit)
        new_lang = dict(fix_values(entry) for entry in polib.pofile(lpath)) if lpath else {}

        # recorre los ids en ingles y los coge el mensaje del idioma actual y el valor del nuevo
        for i, (msgid, msgstr) in enumerate(fix_values(entry,True) for entry in polib.pofile(lang_path("en"))):
            # se excluyen los textos legales que concluyen con safe_
            if not msgid.startswith(("safe_","admin_")):
                # si no esta traducida la cadena en el idioma actual se deja vacio
                if not msgid in new_lang:
                    no_translation+=1
                    new_lang[msgid]=""

                # si el mensaje esta traducido al idioma actual se usa, sino se usa el ingles
                if msgid in current_lang:
                    msg=current_lang[msgid][0]
                    description=current_lang[msgid][1]
                else:
                    msg=msgstr[0]
                    description=msgstr[1]

                # si la traduccion es mayor de 80 caracteres se utiliza un textarea en vez de un input text
                length=len(new_lang[msgid] or msg)
                if length>80:
                    formfields[msgid]=TextAreaField(msg,default=new_lang[msgid],description=description)
                    # se le establecen las filas al text area dependiendo del tamaño de la traduccion
                    formfields["_args_%s" % msgid]={"rows":length/50}
                else:
                    formfields[msgid]=TextField(msg,default=new_lang[msgid],description=description)
                    formfields["_args_%s" % msgid]={}

                #se añade a la lista que se le envia al formulario
                msgids.append(msgid)

        total=float(len(msgids))
        form=expanded_instance(TranslateForm, formfields, request.form, prefix="translate_")
        # si es el envio de la traducción
        if request.method == 'POST' and form.validate():
            pagesdb.create_translation({"ip":request.remote_addr,"user_lang":g.lang,"dest_lang":lang_edit,"texts":{field.short_name: field.data for field in form if not field.short_name in ("captcha", "submit_form") and field.data!=new_lang[field.short_name]}})
            flash("translation_sent")
            return redirect(url_for('index.home'))

    if lang_edit: forml.lang.data = lang_edit
    # sino se muestra la seleccion de idioma a traducir
    g.title+=_("translate_to_your_language")
#.........这里部分代码省略.........
开发者ID:aesedepece,项目名称:foofind-web,代码行数:101,代码来源:page.py


示例19: _get_request_locale

def _get_request_locale(request):
    """Return locale from the request, falling back to a default if invalid."""
    locale = request.LANGUAGE_CODE
    if not localedata.exists(locale):
        locale = settings.LANGUAGE_CODE
    return locale
开发者ID:Elchi3,项目名称:kuma,代码行数:6,代码来源:utils.py


示例20: _validate

 def _validate(self, val):
     if not localedata.exists(val):
         raise db.BadValueError('Not a valid locale')
开发者ID:Outernet-Project,项目名称:outernet-csds,代码行数:3,代码来源:properties.py



注:本文中的babel.localedata.exists函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python localedata.load函数代码示例发布时间:2022-05-24
下一篇:
Python dates.parse_pattern函数代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap