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

Python i18n.set_lang函数代码示例

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

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



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

示例1: __before__

    def __before__(self):
        @cache.beaker_cache(**config['cache_options_nonpage'])
        def get_categories():
            return model.Category.all()

        @cache.beaker_cache(**config['cache_options_nonpage'])
        def get_user():
            try:
                return model.User.by_id(session['userid']).one()
            except (KeyError, NoResultFound):
                try:
                    del session['userid']
                    session.save()
                except KeyError:
                    pass
                return model.Guest()
        try:
            set_lang(request.GET['language'])
        except KeyError:
            pass
        c.blog_title = config['blog.title']
        c.blog_tagline = config['blog.tagline']
        c.breadcrumbs = []
        c.categories = get_categories()
        c.csrf_token = h.secure_form.auth_token_hidden_field()
        c.user = get_user()
开发者ID:chrisrsantiago,项目名称:muse,代码行数:26,代码来源:base.py


示例2: __call__

    def __call__(self, environ, start_response):
        """Invoke the Controller."""
        # set the language fallback to english
        add_fallback("en")
        # define the language based on browser preference
        user_agent_language = request.languages[0][0:2]
        set_lang(user_agent_language)
        formencode.api.set_stdtranslation(user_agent_language)

        # common values mostly inherited from config file
        c.version = __version__ # TODO move this into the development.ini file
        c.site_full_name = config["site_full_name"] # TODO move this into the development.ini file
        c.site_short_name = config["site_short_name"] # TODO move this into the development.ini file

        # controler and action named for use in templates
        #c.controller = request.environ['pylons.routes_dict']['controller']
        #c.action = request.environ['pylons.routes_dict']['action']

        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']
        try:
            return WSGIController.__call__(self, environ, start_response)
        finally:
            meta.Session.remove()
开发者ID:lazaret,项目名称:archeobases,代码行数:25,代码来源:base.py


示例3: locale

 def locale(self): 
     locale = request.params.get('locale')
     if locale is not None:
         try:
             set_session_locale(locale)
         except ValueError:
             abort(400, _('Invalid language specified'))
         try:
             set_lang(locale)
             # NOTE: When translating this string, substitute the word
             # 'English' for the language being translated into.
             # We do it this way because some Babel locales don't contain
             # a display_name!
             # e.g. babel.Locale.parse('no').get_display_name() returns None
             h.flash_notice(_("Language has been set to: English"))
         except:
             h.flash_notice(_("Language has been set to: English"))
     else:
         abort(400, _("No language given!"))
     return_to = get_redirect()
     if not return_to:
         # no need for error, just don't redirect
         return 
     return_to += '&' if '?' in return_to else '?'
     # hack to prevent next page being cached
     return_to += '__cache=%s' %  int(random.random()*100000000)
     redirect_to(return_to)
开发者ID:ciudadanointeligente,项目名称:ckan,代码行数:27,代码来源:home.py


示例4: user_language

def user_language(user, fallbacks=[]):
    # find out the locale
    locale = None
    if user and user.locale:
        locale = user.locale

    if locale is None:
        locales = map(str, LOCALES)
        locale = Locale.parse(Locale.negotiate(fallbacks, locales)) \
                 or get_default_locale()

    # determinate from which path we load the translations
    translations_module = config.get('adhocracy.translations', 'adhocracy')
    translations_module_loader = pkgutil.get_loader(translations_module)
    if translations_module_loader is None:
        raise ValueError(('Cannot import the module "%s" configured for '
                          '"adhocracy.translations". Make sure it is an '
                          'importable module (and contains the '
                          'translation files in a subdirectory '
                          '"i18n"') % translations_module)

    translations_root = translations_module_loader.filename
    translations_config = {'pylons.paths': {'root': translations_root},
                           'pylons.package': config.get('pylons.package')}

    # set language and fallback
    set_lang(locale.language, pylons_config=translations_config)
    add_fallback(get_default_locale().language,
                 pylons_config=translations_config)
    formencode.api.set_stdtranslation(domain="FormEncode",
                                      languages=[locale.language])
    return locale
开发者ID:JonnyWalker,项目名称:adhocracy,代码行数:32,代码来源:__init__.py


示例5: no_lang

 def no_lang(self):
     resp = Response()
     set_lang(None)
     resp.write(_("No language"))
     set_lang([])
     resp.write(_("No languages"))
     return resp
开发者ID:scbarber,项目名称:horriblepoems,代码行数:7,代码来源:controller_sample.py


示例6: handle_request

def handle_request(request, tmpl_context):
    from pylons import session

    tmpl_context.language = locale = None
    if 'locale' in session:
        locale = Locale.parse(session.get('locale'))
    else:
        requested = [l.replace('-', '_') for l in request.languages]
        locale = Locale.parse(Locale.negotiate(get_available_languages(), requested))

    if locale is None:
        locale = get_default_locale()

    tmpl_context.locale = locale

    options = [str(locale), locale.language, str(get_default_locale()),
        get_default_locale().language]
    for language in options:
        try:
            set_lang(language)
            # Lose the territory part of the locale string
            tmpl_context.language = get_lang()[0].split('_')[0]
            break
        except:
            pass
开发者ID:RandyMoore,项目名称:openspending,代码行数:25,代码来源:__init__.py


示例7: setup_i18n

def setup_i18n(languages=None):
    if not languages:
        languages = pylons.request.accept_language.best_matches()
    if languages:
        for lang in languages[:]:
            try:
                add_fallback(lang)
            except LanguageError:
                # if there is no resource bundle for this language
                # remove the language from the list
                languages.remove(lang)
                log.debug("Skip language %s: not supported", lang)
        # if any language is left, set the best match as a default
        if languages:
            try:
                set_lang(languages[0])
            except LanguageError:
                log.debug("Language %s: not supported", languages[0])
            else:
                log.debug("Set request language to %s", languages[0])

            try:
                set_formencode_translation(languages)
            except LanguageError:
                log.debug("Language %s: not supported by FormEncode",
                        languages[0])
            else:
                log.debug("Set request language for FormEncode to %s",
                        languages[0])
开发者ID:TimmGit,项目名称:posy,代码行数:29,代码来源:base.py


示例8: __init__

    def __init__(self):

        lang = request.params.get('lang')
        if lang:
            if is_valid_string(lang):
                try:
                    set_lang(os.path.basename(lang))
                except LanguageError:
                    pass
        else:
            for lang in request.languages:
                if is_valid_string(lang):
                    try:
                        set_lang(lang)
                    except LanguageError:
                        continue
        try:
            add_fallback('en')
        except LanguageError:
            pass

        self.PREFIXES = {
            'mime': "m:",
            'group': "g:",
            'category': "c:",
            'license': "l:",
            'useflag': "u:",
            'library': "so:",
            'provided_library': "sop:",
        }
开发者ID:Sabayon,项目名称:packages-website,代码行数:30,代码来源:base.py


示例9: localize

def localize(f, *args, **kwargs):
    if 'lang' in session:
        lang = session['lang']
        set_lang(lang)
    else:
        suport_lang = ['ru','en','uk']
        suport_domain = ['cleverad.yt:5000','10.0.0.8:5000']
        default_lang = 'ru'
        lang_cookie = request.cookies.get('lang', None)
        if not lang_cookie in suport_lang:
            lang_cookie = None
        domain = request.environ.get('HTTP_HOST', None)
        if not domain in suport_domain:
            domain = None
        if lang_cookie != None:
            lang = lang_cookie
        else:
            if domain == 'cleverad.yt:5000':
                lang = 'en'
            elif domain == '10.0.0.8:5000':
                lang = 'uk'
            elif domain == '10.0.0.8':
                lang = 'ru'
            else:
                lang = default_lang
        session['lang'] = lang
        session.save()
        set_lang(lang)
    response.set_cookie('lang', lang, max_age=360*24*3600 )
    return f(*args, **kwargs)
开发者ID:testTemtProj,项目名称:OLD_PROJECT,代码行数:30,代码来源:helpers.py


示例10: handle_request

def handle_request(request, tmpl_context):
    ''' Set the language for the request '''
    lang = request.environ.get('CKAN_LANG',
                               config.get('ckan.locale_default', 'en'))
    if lang != 'en':
        i18n.set_lang(lang)
    tmpl_context.language = lang
    return lang
开发者ID:zydio,项目名称:ckan,代码行数:8,代码来源:i18n.py


示例11: __before__

 def __before__(self):
     set_lang(request.environ['app.lang'])
     h.setMenuItems(_('menus.dat'))
     self.menu_items = session[_('menus.dat')]
     if 'site_settings' not in session:
         settingsf = file(config['settings_file'],'rb')        
         session['site_settings'] = pickle.load(settingsf)        
         session.save()
开发者ID:vickyi,项目名称:PylonsSimpleCMS,代码行数:8,代码来源:application.py


示例12: __before__

 def __before__(self):
     if 'lang' in session:
         set_lang(session['lang'])
     else:
         set_lang('fa')
         session['lang']='fa'
         session.save()
     h.setMenuItems(_('menus.dat'))
     self.menu_items = session[_('menus.dat')]
开发者ID:vickyi,项目名称:PylonsSimpleCMS,代码行数:9,代码来源:invoice.py


示例13: __before__

    def __before__(self):
        if 'lang' in session:
            set_lang(session['lang'])
            set_stdtranslation(languages=['en','fa'])
        else:
            set_lang('fa')
            session['lang']='fa'
            session.save()

        h.setMenuItems(_('menus.dat'))
        self.menu_items = session[_('menus.dat')]
开发者ID:vickyi,项目名称:PylonsSimpleCMS,代码行数:11,代码来源:product.py


示例14: __before__

 def __before__(self):        
     #if 'lang' in session:
         #set_lang(session['lang'])
     #else:
         #set_lang('fa')
         #session['lang']='fa'
         #session.save()
     set_lang(request.environ['app.lang'])
         
     h.setMenuItems(_('menus.dat'))
     h.setPageContents(_('pages.dat'))
     self.menu_items = session[_('menus.dat')]     
开发者ID:vickyi,项目名称:PylonsSimpleCMS,代码行数:12,代码来源:error.py


示例15: _set_lang

def _set_lang(lang):
    ''' Allows a custom i18n directory to be specified.
    Creates a fake config file to pass to pylons.i18n.set_lang, which
    sets the Pylons root path to desired i18n_directory.
    This is needed as Pylons will only look for an i18n directory in
    the application root.'''
    if config.get('ckan.i18n_directory'):
        fake_config = {'pylons.paths': {'root': config['ckan.i18n_directory']},
                       'pylons.package': config['pylons.package']}
        i18n.set_lang(lang, pylons_config=fake_config)
    else:
        i18n.set_lang(lang)
开发者ID:tbalaz,项目名称:test,代码行数:12,代码来源:i18n.py


示例16: __before__

    def __before__(self):
        default_lang = 'de'
        for lang in request.languages:
            if lang[:2] in ['de','fr','rm','it','en']:
                default_lang = lang[:2]
                break
        self.lang = request.params.get('lang', default_lang)
        if self.lang == 'rm':
            set_lang('fi', fallback=True)
        else:
           set_lang(self.lang, fallback=True)

        c.lang = self.lang
开发者ID:gjn,项目名称:mf-chsdi,代码行数:13,代码来源:base.py


示例17: __before__

	def __before__(self, action, **params):
		self.user = None
		try:
			user = session.get('user')
			if user:
				request.environ['REMOTE_USER'] = user
				request.environ['REMOTE_USER_NAME'] = session.get('user_name')
				self.user = user
		except:
			pass

		if 'lang' in session:
			set_lang(session['lang'])
开发者ID:Administrator37157192201,项目名称:DevContest,代码行数:13,代码来源:base.py


示例18: __call__

    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']
        

        lang = request.params.get('language', None) 
        if lang and lang == 'de':
            session['lang'] = lang
        elif lang and lang == 'en':
            session['lang'] = lang

        if 'lang' in session: 
            if session['lang'] == 'de':
                set_lang(session['lang'])
        else:
            for ua_lang in request.languages:
                if ua_lang[0:2] == 'de':
                    session['lang'] = 'de'
                    break
                
                if ua_lang[0:2] == 'en':
                    session['lang'] = 'en'
                    
            if not 'lang' in session:
                session['lang'] = 'en'
                
            if session['lang'] == 'de':
                set_lang(session['lang'])
            
        try:
            c.user = session['user']
        except:
            pass


        #~ if asbool(config['debug']) and c.user:
            #~ query = meta.Session.query(model.User)
            #~ tmp = query.filter_by(id=c.user.id).first()
            #~ if not tmp:
                #~ log.debug('FOOOOOOO')
                #~ c.user = None
                #~ session['user'] = None
                #~ #redirect_to(controller='login', action='signout')
            
        try:
            return WSGIController.__call__(self, environ, start_response)
        finally:
            meta.Session.remove()
开发者ID:dummy3k,项目名称:truthmaschine,代码行数:50,代码来源:base.py


示例19: _set_lang

def _set_lang(lang):
    """ Allows a custom i18n directory to be specified.
    Creates a fake config file to pass to pylons.i18n.set_lang, which
    sets the Pylons root path to desired i18n_directory.
    This is needed as Pylons will only look for an i18n directory in
    the application root."""
    if config.get("ckan.i18n_directory"):
        fake_config = {
            "pylons.paths": {"root": config["ckan.i18n_directory"]},
            "pylons.package": config["pylons.package"],
        }
        i18n.set_lang(lang, pylons_config=fake_config)
    else:
        i18n.set_lang(lang)
开发者ID:BigOpenData,项目名称:ckan,代码行数:14,代码来源:i18n.py


示例20: __before__

    def __before__(self):
        if "photos" not in session:
            session["photos"] = {}
            session["photos"]["files"] = []

        if "lang" in session:
            set_lang(session["lang"])
            set_stdtranslation(languages=["en", "fa"])
        else:
            set_lang("fa")
            session["lang"] = "fa"
            session.save()

        h.setMenuItems(_("menus.dat"))
        self.menu_items = session[_("menus.dat")]
开发者ID:vickyi,项目名称:PylonsSimpleCMS,代码行数:15,代码来源:photo.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python i18n.ungettext函数代码示例发布时间:2022-05-25
下一篇:
Python i18n.gettext函数代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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