コード例 #1
0
ファイル: main.py プロジェクト: wisperwinter/pali
    def get(self):
        locale = getUserLocale(self.request.GET.get("locale"), self.request.headers.get("accept_language"))
        i18n.get_i18n().set_locale(locale)

        titleword = u""
        mainviewDivInnerHTML = None
        if self.request.path.startswith("/canon"):
            if isValidCanonUrl(self.request.path):
                titleword = getTitleInfo(self.request.path)
                mainviewDivInnerHTML = getMainViewInnerHTML(self.request.path)
            else:
                self.error(404)
                self.response.out.write("Page Not Found!")
                return

        devjs = self.request.GET.get("devjs")
        if devjs not in ["yes", "no"]:
            devjs = None
        if devjs == None:
            if os.environ["SERVER_SOFTWARE"].startswith("Development"):
                devjs = "yes"
            else:
                devjs = "no"

        template_values = {
            "titleword": titleword,
            "locale": "%s~%s" % (locale, self.request.headers.get("accept_language")),
            "mainviewDivInnerHTML": mainviewDivInnerHTML,
            "devjs": devjs,
        }

        template = jinja_environment.get_template("index.html")
        self.response.out.write(template.render(template_values))
コード例 #2
0
    def test_format_datetime(self):
        value = datetime.datetime(2009, 11, 10, 16, 36, 5)

        self.assertEqual(
            i18n.format_datetime(value, format="short"), "11/10/09, 4:36 PM"
        )
        self.assertEqual(
            i18n.format_datetime(value, format="medium"), "Nov 10, 2009, 4:36:05 PM"
        )
        self.assertEqual(
            i18n.format_datetime(value, format="long"),
            "November 10, 2009 at 4:36:05 PM +0000",
        )

        # self.assertEqual(i18n.format_datetime(value, format='full'),
        # u'Tuesday, November 10, 2009 4:36:05 PM World (GMT) Time')

        self.assertEqual(
            i18n.format_datetime(value, format="full"),
            "Tuesday, November 10, 2009 at 4:36:05 PM GMT+00:00",
        )

        i18n.get_i18n().set_timezone("America/Chicago")
        self.assertEqual(
            i18n.format_datetime(value, format="short"), "11/10/09, 10:36 AM"
        )
コード例 #3
0
ファイル: __init__.py プロジェクト: sashkent3/thehat
    def draw_page(self, template_name, **render_data):
        if (get_application_id() == "the-hat-international") or (get_application_id() == "the-hat-dev"):
            dev = True
        else:
            dev = None
        template = self.jinja2().environment.get_template('{}.html'.format(template_name))
        render_data['dev'] = dev
        render_data['user_link'] = (users.create_logout_url('/') if self.user
                                    else users.create_login_url(self.request.url))
        if self.user:
            render_data['user_email'] = users.get_current_user().email()
        else:
            render_data['user_email'] = None
        render_data['is_admin'] = users.is_current_user_admin()
        curr_channel = ndb.Key(NotificationChannel,
                               "notifications").get()
        render_data['token'] = curr_channel.channel_token if curr_channel else None

        if self.user:
            locale = self.user_key.get().localization
        else:
            locale = 'ru_RU'

        i18n.get_i18n().set_locale(locale)

        self.response.write(template.render(render_data))
コード例 #4
0
    def test_format_datetime(self):
        value = datetime.datetime(2009, 11, 10, 16, 36, 5)

        self.assertEqual(
            i18n.format_datetime(value, format='short'),
            u'11/10/09, 4:36 PM'
        )
        self.assertEqual(
            i18n.format_datetime(value, format='medium'),
            u'Nov 10, 2009, 4:36:05 PM'
        )
        self.assertEqual(
            i18n.format_datetime(value, format='long'),
            u'November 10, 2009 at 4:36:05 PM +0000'
        )

        # self.assertEqual(i18n.format_datetime(value, format='full'),
        # u'Tuesday, November 10, 2009 4:36:05 PM World (GMT) Time')

        self.assertEqual(
            i18n.format_datetime(value, format='full'),
            u'Tuesday, November 10, 2009 at 4:36:05 PM GMT+00:00'
        )

        i18n.get_i18n().set_timezone('America/Chicago')
        self.assertEqual(
            i18n.format_datetime(value, format='short'),
            u'11/10/09, 10:36 AM'
        )
コード例 #5
0
ファイル: index.py プロジェクト: helmuthb/devfest-at-site
 def get(self):
   # work depending on locale
   locale = self.session['locale']
   if self.request.get('locale'):
     locale = self.request.get('locale')
     i18n.get_i18n().set_locale(locale)
   self.prep_html_response('call.html')
コード例 #6
0
ファイル: index.py プロジェクト: helmuthb/devfest-at-site
 def get(self, url, event='2012'):
   session = model.SessionTalk.query(ndb.AND(model.SessionTalk.event == event, model.SessionTalk.url == url)).fetch(1)[0]
   speakers = [ sp.get() for sp in session.speaker ]
   # work depending on locale
   locale = self.session['locale']
   if self.request.get('locale'):
     locale = self.request.get('locale')
     i18n.get_i18n().set_locale(locale)
   if locale[0:2] == "de":
     session.title = session.title_de
     session.abstract = session.abstract_de
     session.requirements = session.requirements_de
     for sp in speakers:
       sp.bio = sp.bio_de
     for link in session.link:
       link.text = link.text_de
     if session.language:
       session.languagetext = languagetext_de[session.language]
     if session.level:
       session.leveltext = leveltext_de[session.level]
   else:
     session.title = session.title_en
     session.abstract = session.abstract_en
     session.requirements = session.requirements_en
     for sp in speakers:
       sp.bio = sp.bio_en
     for link in session.link:
       link.text = link.text_en
     if session.language:
       session.languagetext = languagetext_en[session.language]
     if session.level:
       session.leveltext = leveltext_en[session.level]
   self.prep_html_response('session.html', {'event':event, 'session':session, 'speakers':speakers})
コード例 #7
0
ファイル: __init__.py プロジェクト: parallel-p/thehat
    def draw_page(self, template_name, **render_data):
        if (get_application_id() == "the-hat-international") or (get_application_id() == "the-hat-dev"):
            dev = True
        else:
            dev = None
        template = self.jinja2().environment.get_template("{}.html".format(template_name))
        render_data["dev"] = dev
        render_data["user_link"] = (
            users.create_logout_url("/") if self.user else users.create_login_url(self.request.url)
        )
        if self.user:
            render_data["user_email"] = users.get_current_user().email()
        else:
            render_data["user_email"] = None
        render_data["is_admin"] = users.is_current_user_admin()
        curr_channel = ndb.Key(NotificationChannel, "notifications").get()
        render_data["token"] = curr_channel.channel_token if curr_channel else None

        if self.user:
            locale = self.user_key.get().localization
        else:
            locale = "ru_RU"

        i18n.get_i18n().set_locale(locale)

        self.response.write(template.render(render_data))
コード例 #8
0
ファイル: index.py プロジェクト: helmuthb/devfest-at-site
 def get(self, event='2012'):
   sessions = model.SessionTalk.query(model.SessionTalk.event == event).fetch()
   # work depending on locale
   locale = self.session['locale']
   if self.request.get('locale'):
     locale = self.request.get('locale')
     i18n.get_i18n().set_locale(locale)
   for session in sessions:
     session.speakers = [ sp.get() for sp in session.speaker ]
   if locale[0:2] == "de":
     for session in sessions:
       session.title = session.title_de
       session.abstract = session.abstract_de
       session.requirements = session.requirements_de
       if session.language:
         session.languagetext = languagetext_de[session.language]
       if session.level:
         session.leveltext = leveltext_de[session.level]
   else:
     for session in sessions:
       session.title = session.title_en
       session.abstract = session.abstract_en
       session.requirements = session.requirements_en
       if session.language:
         session.languagetext = languagetext_en[session.language]
       if session.level:
         session.leveltext = leveltext_en[session.level]
   self.prep_html_response('sessions.html', {'event':event,'sessions':sessions})
コード例 #9
0
    def init_model(self):
        # Set the requested locale.        
        locale = self.request.GET.get('locale')
        if locale:
            logging.debug("locale provided as parameter: %s", locale)
            i18n.get_i18n().set_locale(locale)
        else:
            i18n.get_i18n().set_locale(self.get_requested_locale())
            
        logging.info("locale set to %s", i18n.get_i18n().locale)
        
        user = users.get_current_user()

        modl = dict()
        strings.add_to_model(modl)
        operations.add_to_model(modl)
                    
        if user:
            modl['user'] = {
                'email': user.email(),
                'nickname': user.nickname(),
                'id': user.user_id()
            }
            modl['email'] = user.email()
            modl['login_url'] = '#'
            modl['logout_url'] = users.create_logout_url(self.request.uri)

        else :
            modl['user'] = '******'
            modl['email'] = ''
            modl['login_url'] = users.create_login_url(self.request.uri)
            modl['logout_url'] = '#'

        return modl;
コード例 #10
0
    def get(self):
        locale = self.request.GET.get('locale', 'en_US')
        i18n.get_i18n().set_locale(locale)

        #would be nicer to get a dict with translation keys from i18n if possible...
        template_values = {
            'locale' : locale,
            'title' : i18n.gettext('Wordbank search aggregator'),
            'Search' : i18n.gettext('Search'),
            'exact' : i18n.gettext('exact'),
            'searchLink' : i18n.gettext('searchLink'),
            'On' : i18n.gettext('On'),
            'Off' : i18n.gettext('Off'),
            'About' : i18n.gettext('About'),
            'titleAbout' : i18n.gettext('About the wordbank search aggregator'),
            'aboutContents1' : i18n.gettext('aboutContents1'),
            'aboutContents2' : i18n.gettext('aboutContents2'),
            'aboutContents3' : i18n.gettext('aboutContents3'),
            'aboutContents4' : i18n.gettext('aboutContents4'),
            
            'titleSettings' : i18n.gettext('titleSettings'),
            'legendInterfaceLanguage' : i18n.gettext('legendInterfaceLanguage'),
            'English' : i18n.gettext('English'),
            'Icelandic' : i18n.gettext('Icelandic'),
            'Continue' : i18n.gettext('Continue'),
            'titleCharges' : i18n.gettext('titleCharges'),
            'chargesHeading' : i18n.gettext('chargesHeading'),
            'chargesContents' : i18n.gettext('chargesContents')
        }
        path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, template_values))
コード例 #11
0
    def get(self):
        locale = self.request.GET.get('locale', 'en_US')
        i18n.get_i18n().set_locale(locale)

        template_values = {}
        template = JINJA_ENVIRONMENT.get_template('index.html')
        self.response.write(template.render(template_values))
コード例 #12
0
    def test_format_datetime_pt_BR(self):
        i18n.get_i18n().set_locale('pt_BR')
        value = datetime.datetime(2009, 11, 10, 16, 36, 5)

        self.assertEqual(
            i18n.format_datetime(value, format='short'),
            u'10/11/09 16:36'
        )
        self.assertEqual(
            i18n.format_datetime(value, format='medium'),
            u'10 de nov de 2009 16:36:05'
        )
        # self.assertEqual(i18n.format_datetime(value, format='long'),
        # u'10 de novembro de 2009 16:36:05 +0000')
        self.assertEqual(
            i18n.format_datetime(value, format='long'),
            u'10 de novembro de 2009 16:36:05 +0000'
        )
        # self.assertEqual(i18n.format_datetime(value, format='full'),
        # u'terça-feira, 10 de novembro de 2009
        # 16h36min05s Horário Mundo (GMT)')
        self.assertEqual(
            i18n.format_datetime(value, format='full'),
            u'ter\xe7a-feira, 10 de novembro de 2009 16:36:05 GMT+00:00'
        )
コード例 #13
0
ファイル: i18n.py プロジェクト: StackGeek/stackgeek-gaeb
def set_locale(cls, force=None):
    """
    retrieve locale from a prioritized list of sources and then set locale and save it
    cls: self object
    force: a locale to force set (ie 'en_US')
    return: locale as string or None if i18n should be disabled
    """
    # disable i18n if config.locales array is empty or None
    if not config.locales:
        return None
    # 1. force locale if provided
    locale = force
    if locale not in config.locales:
        # 2. retrieve locale from url query string
        locale = cls.request.get("hl", None)
        if locale not in config.locales:
            # 3. retrieve locale from cookie
            locale = cls.request.cookies.get('hl', None)
            if locale not in config.locales:
                # 4. retrieve locale from accept language header
                locale = get_locale_from_accept_header(cls.request)
                if locale not in config.locales:
                    # 5. detect locale from IP address location
                    territory = get_territory_from_ip(cls) or 'ZZ'
                    locale = str(Locale.negotiate(territory, config.locales))
                    if locale not in config.locales:
                        # 6. use default locale
                        locale = i18n.get_store().default_locale
    i18n.get_i18n().set_locale(locale)
    # save locale in cookie with 26 weeks expiration (in seconds)
    cls.response.set_cookie('hl', locale, max_age = 15724800)
    return locale
コード例 #14
0
def create_jinja_environment(loader, locale=None):
    """Create proper jinja environment."""

    cache = None
    if CAN_USE_JINJA2_TEMPLATE_CACHE.value:
        prefix = 'jinja2:bytecode:%s:/' % models.MemcacheManager.get_namespace(
        )
        cache = jinja2.MemcachedBytecodeCache(
            models.MemcacheManager,
            timeout=models.DEFAULT_CACHE_TTL_SECS,
            prefix=prefix)

    jinja_environment = jinja2.Environment(autoescape=True,
                                           finalize=finalize,
                                           extensions=['jinja2.ext.i18n'],
                                           bytecode_cache=cache,
                                           loader=loader)

    jinja_environment.filters['js_string'] = js_string

    if locale:
        i18n.get_i18n().set_locale(locale)
        jinja_environment.install_gettext_translations(i18n)

    return jinja_environment
コード例 #15
0
    def render_template(self, filename, params=None):
        if not params:
            params = {}

        # override locale if set in params
        if params and 'locale' in params.keys():
            i18n.get_i18n().set_locale(params['locale'])

        is_superuser = False
        if self.user:
            is_superuser = self.user.is_superuser

        is_betatester = False
        if self.user:
            is_betatester = self.user.is_betatester

        params['the_user'] = self.user
        params['the_user_is_superuser'] = is_superuser
        params['the_user_is_betatester'] = is_betatester
        if self.user:
            params['the_user_addgigbandlist'] = self.user.get_add_gig_band_list(self, self.user.key)
        params['logout_link'] = self.uri_for('logout')
        if self.user is not None and not self.user.seen_welcome:
            params['welcome'] = True

        # handle MOTD
        if self.user is not None:
            motd = motd_db.get_motd_object()
            if motd and (self.user.seen_motd_time is None or self.user.seen_motd_time < motd.last_update):
                params['motd'] = motd.value
        

        self.render_response(filename, params)
コード例 #16
0
ファイル: main.py プロジェクト: siongui/obsoleted-pali
  def get(self):
    locale = self.request.GET.get('locale', 'en_US')
    i18n.get_i18n().set_locale(locale)

    template_values = {}
    template = jinja_environment.get_template('index.html')
    self.response.out.write(template.render(template_values))
コード例 #17
0
    def render_template(self, filename, params=None):
        if not params:
            params = {}

        # override locale if set in params
        if params and 'locale' in params.keys():
            i18n.get_i18n().set_locale(params['locale'])

        is_superuser = False
        if self.user:
            is_superuser = self.user.is_superuser

        is_betatester = False
        if self.user:
            is_betatester = self.user.is_betatester

        params['the_user'] = self.user
        params['the_user_is_superuser'] = is_superuser
        params['the_user_is_betatester'] = is_betatester
        if self.user:
            params[
                'the_user_addgigbandlist'] = self.user.get_add_gig_band_list(
                    self, self.user.key)
            params['the_user_forumslist'] = self.user.get_forums(
                self, self.user.key)
        params['logout_link'] = self.uri_for('logout')
        if self.user is not None and not self.user.seen_welcome:
            params['welcome'] = True
        if self.user is not None and not self.user.seen_motd:
            params['motd'] = motd_db.get_motd()
        self.render_response(filename, params)
コード例 #18
0
def create_jinja_environment(loader, locale=None, autoescape=True):
    """Create proper jinja environment."""

    cache = None
    if CAN_USE_JINJA2_TEMPLATE_CACHE.value:
        prefix = 'jinja2:bytecode:%s:/' % models.MemcacheManager.get_namespace(
        )
        cache = JinjaBytecodeCache(prefix)

    jinja_environment = jinja2.Environment(autoescape=autoescape,
                                           finalize=finalize,
                                           extensions=['jinja2.ext.i18n'],
                                           bytecode_cache=cache,
                                           loader=loader)

    jinja_environment.filters['js_string'] = js_string
    jinja_environment.filters['to_json'] = _to_json_jinja

    if locale:
        i18n.get_i18n().set_locale(locale)
        jinja_environment.install_gettext_translations(i18n)

    old_handle_exception = jinja_environment.handle_exception

    def _handle_exception(exc_info=None, rendered=False, source_hint=None):
        """Handle template exception."""
        traceback.print_exc(exc_info)
        result = old_handle_exception(exc_info, rendered, source_hint)
        return result

    jinja_environment.handle_exception = _handle_exception

    return jinja_environment
コード例 #19
0
ファイル: goemail.py プロジェクト: ChaoticNoise/GO2
def send_the_new_member_email(the_locale, the_email_address, new_member, the_band):

    if not mail.is_email_valid(the_email_address):
        return False
        
    i18n.get_i18n().set_locale(the_locale)
        
    message = mail.EmailMessage()
    message.sender = SENDER_EMAIL
    message.to = the_email_address
    message.subject = _('Gig-o-Matic New Member for band {0})').format(the_band.name)
#     message.body = u"""
# Hello! A new member {0} has signed up for your band {1}. Please log in and
# confirm the membership.
# 
# http://gig-o-matic.appspot.com/band_info.html?bk={2}
# 
# Thanks,
# The Gig-o-Matic Team
# 
#     """.format(new_member.name, the_band.name, the_band.key.urlsafe())
    message.body = _('new_member_email').format(new_member.name, the_band.name, the_band.key.urlsafe())

    try:
        message.send()
    except:
        logging.error('failed to send email!')
        
    return True        
コード例 #20
0
ファイル: i18n.py プロジェクト: grisaitis/gae-puns
def set_locale(cls, force=None):
    """
    retrieve locale from a prioritized list of sources and then set locale and save it
    cls: self object
    force: a locale to force set (ie 'en_US')
    return: locale
    """
    # 1. force locale if provided
    locale = force
    if locale not in AVAILABLE_LOCALES:
        # 2. retrieve locale from url query string
        locale = cls.request.get("hl", None)
        if locale not in AVAILABLE_LOCALES:
            # 3. retrieve locale from cookie
            locale = utils.read_cookie(cls, "hl")
            if locale not in AVAILABLE_LOCALES:
                # 4. retrieve locale from accept language header
                locale = get_locale_from_accept_header(cls)
                if locale not in AVAILABLE_LOCALES:
                    # 5. detect locale from IP address location
                    locale = get_locale_from_territory(get_territory_from_ip(cls))
                    if locale not in AVAILABLE_LOCALES:
                        # 6. use default locale
                        locale = AVAILABLE_LOCALES[0]
    # convert unicode locale to string for headers
    locale = str(locale)
    i18n.get_i18n().set_locale(locale)
    # save locale in cookie with 26 weeks expiration (in seconds)
    utils.write_cookie(cls, "hl", locale, "/", 15724800)
    return locale
コード例 #21
0
ファイル: main.py プロジェクト: softsprocket/adaythere
    def __init__(self, request, response):
        self.initialize(request, response)
        
        locale = self.request.GET.get ('locale', 'en_US')
        i18n.get_i18n ().set_locale (locale)

        self.user = users.get_current_user ()

        self.adaythere = ADayThere ()
        self.adaythere.add_meta_tags ([
            { "charset":"UTF-8" },
            { "http-equiv":"X-UA-Compatible", "content":"IE=edge" },
            { "name":"description", "content":"A social media site that celebrates the joys of place." },
            { "name":"viewport", "content":"initial-scale=1"}
        ])

        self.adaythere.add_links ([
            { "rel":"stylesheet", "href":"css/bootstrap.css" },
            { "rel":"stylesheet", "href":"css/adaythere.css" }
        ])


        maps = Maps ()

        self.adaythere.add_script_tags_for_body ([
            { "src":"js/jquery-1.11.0-beta2.js" },
            { "src":"js/angular/angular.min.js" },
            { "src":"js/angular/angular-route.min.js" },
            { "src":"js/ui-bootstrap-tpls-0.10.0.min.js" },
            { "src": maps.get_script_src () },
            { "src":"js/adaythere.js" },
            { "src":"https://apis.google.com/js/platform.js", "async":None, "defer":None }
        ])
コード例 #22
0
ファイル: requestmodel.py プロジェクト: ChaoticNoise/GO2
    def render_template(self, filename, params=None):

        if params and "locale" in params.keys():
            locale = params["locale"]
        elif self.user:
            if self.user.preferences.locale:
                locale = self.user.preferences.locale
        else:
            locale = None

        i18n.get_i18n().set_locale(locale)

        if not params:
            params = {}

        is_superuser = False
        if self.user:
            is_superuser = self.user.is_superuser

        is_betatester = False
        if self.user:
            is_betatester = self.user.is_betatester

        params["the_user"] = self.user
        params["the_user_is_superuser"] = is_superuser
        params["the_user_is_betatester"] = is_betatester
        if self.user:
            params["the_user_addgigbandlist"] = self.user.get_add_gig_band_list(self, self.user.key)
        params["logout_link"] = self.uri_for("logout")
        if self.user is not None and not self.user.seen_welcome:
            params["welcome"] = True
        if self.user is not None and not self.user.seen_motd:
            params["motd"] = motd_db.get_motd()
        self.render_response(filename, params)
コード例 #23
0
ファイル: base.py プロジェクト: 7kfpun/gae-boilerplate
    def set_locale(self, force=None):
        locales = self.app.config.get('locales')
        # disable i18n if config.locales array is empty or None
        if not locales:
            return None
        # 1. force locale if provided
        locale = force
        if locale not in locales:
            # 2. retrieve locale from url query string
            locale = self.request.get("hl", None)
            if locale not in locales:
                # 3. retrieve locale from cookie
                locale = self.request.cookies.get('hl', None)
                if locale not in locales:
                    # 4. retrieve locale from accept language header
                    #locale = get_locale_from_accept_header(self.request)
                    if locale not in locales:
                        # 5. detect locale from IP address location
                        territory = get_territory_from_ip(self) or 'ZZ'
                        locale = str(Locale.negotiate(territory, locales))
                        if locale not in locales:
                            # 6. use default locale
                            locale = self.request.GET.get('locale', 'en_US')

        i18n.get_i18n().set_locale(locale)
        logger.info('locale is {0}'.format(locale))
        # save locale in cookie with 26 weeks expiration (in seconds)
        self.response.set_cookie('hl', locale, max_age=15724800)
        return locale
コード例 #24
0
ファイル: profile.py プロジェクト: khvilaboa/Calify
    def get(self, teachId):
        if not self.loggedIn():
            self.redirect("/")
            return
        values = self.getValues()
        i18n.get_i18n().set_locale(self.getLanguage())

        teacher = db.Teacher.get_by_id(long(teachId))
        lang = self.request.get("lang", None)
        if lang is not None:
            teacher.setLanguage(lang)
            referrer = self.request.headers.get('referer')
            if referrer:
                return self.redirect(referrer)
            return self.redirect("/")

        if not teachId or not teacher:
            self.redirect("/")
        else:

            own = teachId == str(self.getUserId())
            values["own"] = own
            values["teacher"] = teacher
            values["username"] = self.getUserName()
            values["subjects"] = ", ".join([s.name for s in db.Subject.getSubjectsByTeacher(teacher.key)])

            template = JINJA_ENVIRONMENT.get_template('/view/profile/index.html')
            self.response.write(template.render(values))
コード例 #25
0
ファイル: main.py プロジェクト: rafaelmv/i18n-GAE
    def get(self):
        locale = self.request.GET.get('locale', 'en_US')
        i18n.get_i18n().set_locale(locale)

        template_values = {}
        template = JINJA_ENVIRONMENT.get_template('index.html')
        self.response.write(template.render(template_values))
コード例 #26
0
def create_jinja_environment(loader, locale=None, autoescape=True):
    """Create proper jinja environment."""

    cache = None
    if CAN_USE_JINJA2_TEMPLATE_CACHE.value:
        prefix = 'jinja2:bytecode:%s:/' % models.MemcacheManager.get_namespace()
        cache = JinjaBytecodeCache(prefix)

    jinja_environment = jinja2.Environment(
        autoescape=autoescape, finalize=finalize,
        extensions=['jinja2.ext.i18n'], bytecode_cache=cache, loader=loader)

    jinja_environment.filters['js_string'] = js_string

    if locale:
        i18n.get_i18n().set_locale(locale)
        jinja_environment.install_gettext_translations(i18n)

    old_handle_exception = jinja_environment.handle_exception

    def _handle_exception(exc_info=None, rendered=False, source_hint=None):
        """Handle template exception."""
        traceback.print_exc(exc_info)
        result = old_handle_exception(exc_info, rendered, source_hint)
        return result

    jinja_environment.handle_exception = _handle_exception

    return jinja_environment
コード例 #27
0
ファイル: i18n.py プロジェクト: alexsmx/coto_frictionless
def set_locale(cls, force=None):
    """
    retrieve locale from a prioritized list of sources and then set locale and save it
    cls: self object
    force: a locale to force set (ie 'en_US')
    return: locale as string or None if i18n should be disabled
    """
    # disable i18n if config.locales array is empty or None
    if not config.locales:
        return None
    # 1. force locale if provided
    locale = force
    if locale not in config.locales:
        # 2. retrieve locale from url query string
        locale = cls.request.get("hl", None)
        if locale not in config.locales:
            # 3. retrieve locale from cookie
            locale = cls.request.cookies.get('hl', None)
            if locale not in config.locales:
                # 4. retrieve locale from accept language header
                locale = get_locale_from_accept_header(cls.request)
                if locale not in config.locales:
                    # 5. detect locale from IP address location
                    territory = get_territory_from_ip(cls) or 'ZZ'
                    locale = str(Locale.negotiate(territory, config.locales))
                    if locale not in config.locales:
                        # 6. use default locale
                        locale = i18n.get_store().default_locale
    i18n.get_i18n().set_locale(locale)
    # save locale in cookie with 26 weeks expiration (in seconds)
    cls.response.set_cookie('hl', locale, max_age = 15724800)
    return locale
コード例 #28
0
 def test_format_scientific(self):
     i18n.get_i18n().set_locale('en_US')
     self.assertEqual(i18n.format_scientific(10000), u'1E4')
     self.assertEqual(
         i18n.format_scientific(1234567, u'##0E00'),
         u'1.23E06'
     )
コード例 #29
0
ファイル: main.py プロジェクト: clashboom/nvt
 def render(self, template, locale=None, *a, **params):
     if not locale:
         locale = self.session.get('locale')
     if not locale:
         locale = detectLocale(self.request.headers.get('accept_language'))
     i18n.get_i18n().set_locale(locale)
     self.write(self.render_str(template, locale=locale, *a, **params))
コード例 #30
0
ファイル: requestmodel.py プロジェクト: SecondLiners/GO2
    def render_template(self, filename, params=None):
        if not params:
            params = {}

        # override locale if set in params
        if params and 'locale' in params.keys():
            i18n.get_i18n().set_locale(params['locale'])

        is_superuser = False
        if self.user:
            is_superuser = self.user.is_superuser

        is_betatester = False
        if self.user:
            is_betatester = self.user.is_betatester

        params['the_user'] = self.user
        params['the_user_is_superuser'] = is_superuser
        params['the_user_is_betatester'] = is_betatester
        if self.user:
            params['the_user_addgigbandlist'] = self.user.get_add_gig_band_list(self, self.user.key)
        params['logout_link'] = self.uri_for('logout')
        if self.user is not None and not self.user.seen_welcome:
            params['welcome'] = True

        # handle MOTD
        if self.user is not None:
            motd = motd_db.get_motd_object()
            if motd and (self.user.seen_motd_time is None or self.user.seen_motd_time < motd.last_update):
                params['motd'] = motd.value

        self.render_response(filename, params)
コード例 #31
0
ファイル: index.py プロジェクト: helmuthb/devfest-at-site
 def get(self):
     # work depending on locale
     locale = self.session['locale']
     if self.request.get('locale'):
         locale = self.request.get('locale')
         i18n.get_i18n().set_locale(locale)
     self.prep_html_response('call.html')
コード例 #32
0
ファイル: index.py プロジェクト: helmuthb/devfest-at-site
 def get(self, event='2012'):
     sessions = model.SessionTalk.query(
         model.SessionTalk.event == event).fetch()
     # work depending on locale
     locale = self.session['locale']
     if self.request.get('locale'):
         locale = self.request.get('locale')
         i18n.get_i18n().set_locale(locale)
     for session in sessions:
         session.speakers = [sp.get() for sp in session.speaker]
     if locale[0:2] == "de":
         for session in sessions:
             session.title = session.title_de
             session.abstract = session.abstract_de
             session.requirements = session.requirements_de
             if session.language:
                 session.languagetext = languagetext_de[session.language]
             if session.level:
                 session.leveltext = leveltext_de[session.level]
     else:
         for session in sessions:
             session.title = session.title_en
             session.abstract = session.abstract_en
             session.requirements = session.requirements_en
             if session.language:
                 session.languagetext = languagetext_en[session.language]
             if session.level:
                 session.leveltext = leveltext_en[session.level]
     self.prep_html_response('sessions.html', {
         'event': event,
         'sessions': sessions
     })
コード例 #33
0
ファイル: i18n_test.py プロジェクト: mark0978/webapp-improved
    def test_format_percent(self):
        i18n.get_i18n().set_locale('en_US')
        self.assertEqual(i18n.format_percent(0.34), u'34%')
        self.assertEqual(i18n.format_percent(25.1234), u'2,512%')
        self.assertEqual(i18n.format_percent(25.1234, u'#,##0\u2030'), u'25,123\u2030')

        i18n.get_i18n().set_locale('sv_SE')
        self.assertEqual(i18n.format_percent(25.1234), u'2\xa0512\xa0%')
コード例 #34
0
ファイル: i18n_test.py プロジェクト: mark0978/webapp-improved
    def test_format_date_pt_BR(self):
        i18n.get_i18n().set_locale('pt_BR')
        value = datetime.datetime(2009, 11, 10, 16, 36, 05)

        self.assertEqual(i18n.format_date(value, format='short'), u'10/11/09')
        self.assertEqual(i18n.format_date(value, format='medium'), u'10/11/2009')
        self.assertEqual(i18n.format_date(value, format='long'), u'10 de novembro de 2009')
        self.assertEqual(i18n.format_date(value, format='full'), u'terça-feira, 10 de novembro de 2009')
コード例 #35
0
ファイル: goemail.py プロジェクト: SecondLiners/GO2
def send_the_new_member_email(the_locale, the_email_address, new_member, the_band):

    i18n.get_i18n().set_locale(the_locale)

    return _send_admin_mail(the_email_address,
                            _('Gig-o-Matic New Member for band {0}').format(the_band.name),
                            _('new_member_email').format('{0} ({1})'.format(new_member.name, new_member.email_address),
                                                        the_band.name, the_band.key.urlsafe()))
コード例 #36
0
 def __init__(self, request, response):
     """Override the initialiser in order to set the language."""
     self.initialize(request, response)
     # Set language.
     locale_header = self.request.headers.get('Accept-Language')
     locale = self._extract_locale_from_header(locale_header)
     i18n.get_i18n().set_locale(locale)
     self.LANGUAGE = i18n.get_i18n().locale[0:2]
コード例 #37
0
    def test_format_percent(self):
        i18n.get_i18n().set_locale("en_US")
        self.assertEqual(i18n.format_percent(0.34), "34%")
        self.assertEqual(i18n.format_percent(25.1234), "2,512%")
        self.assertEqual(i18n.format_percent(25.1234, "#,##0\u2030"), "25,123\u2030")

        i18n.get_i18n().set_locale("sv_SE")
        self.assertEqual(i18n.format_percent(25.1234), "2\xa0512\xa0%")
コード例 #38
0
 def test_parse_date(self):
     i18n.get_i18n().set_locale('en_US')
     self.assertEqual(i18n.parse_date('4/1/04'), datetime.date(2004, 4, 1))
     i18n.get_i18n().set_locale('de_DE')
     self.assertEqual(
         i18n.parse_date('01.04.2004'),
         datetime.date(2004, 4, 1)
     )
コード例 #39
0
ファイル: main.py プロジェクト: GaGa235/pyladies-tw
    def get(self):
        locale = self.session.get('locale')

        if not locale:
            locale = 'zh_TW'

        i18n.get_i18n().set_locale(locale)
        template_dict = {'locale': locale}
        self.render_template('index.html', template_dict)
コード例 #40
0
ファイル: ime.py プロジェクト: noodlewiz/chineseime-appengine
    def get(self):
        # Set the requested locale.
        locale = self.request.GET.get("lang", "zh_TW")
        i18n.get_i18n().set_locale(locale)

        symbols = u"。,!?;:()【】[]「」『』“”‘’、·《》…—~"

        context = {"symbols": symbols}
        self.render_response("ime.html", **context)
コード例 #41
0
ファイル: main.py プロジェクト: GaGa235/pyladies-tw
 def get(self):
   locale = self.session.get('locale')
   
   if not locale:
     locale = 'zh_TW'
   
   i18n.get_i18n().set_locale(locale)
   template_dict = {'locale':locale}
   self.render_template('index.html', template_dict)
コード例 #42
0
    def test_format_percent(self):
        i18n.get_i18n().set_locale('en_US')
        self.assertEqual(i18n.format_percent(0.34), u'34%')
        self.assertEqual(i18n.format_percent(25.1234), u'2,512%')
        self.assertEqual(i18n.format_percent(25.1234, u'#,##0\u2030'),
                         u'25,123\u2030')

        i18n.get_i18n().set_locale('sv_SE')
        self.assertEqual(i18n.format_percent(25.1234), u'2\xa0512\xa0%')
コード例 #43
0
ファイル: base.py プロジェクト: qyearsley/zh-lyrics
def set_locale(request):
    """Set a the locale based on a request."""
    locale = ""
    if "locale" in request.GET:
        locale = request.GET["locale"]
    elif "locale" in request.cookies:
        locale = request.cookies["locale"]
    if locale not in AVAILABLE_LOCALES:
        locale = AVAILABLE_LOCALES[0]
    i18n.get_i18n().set_locale(locale)
コード例 #44
0
    def get_template_environ(self, locale, additional_dirs):
        """Create and configure jinja template evaluation environment."""
        template_dir = self.get_template_home()
        dirs = [template_dir]
        if additional_dirs:
            dirs += additional_dirs
        jinja_environment = self.fs.get_jinja_environ(dirs)

        i18n.get_i18n().set_locale(locale)
        jinja_environment.install_gettext_translations(i18n)
        return jinja_environment
コード例 #45
0
    def test_format_date_pt_BR(self):
        i18n.get_i18n().set_locale('pt_BR')
        value = datetime.datetime(2009, 11, 10, 16, 36, 05)

        self.assertEqual(i18n.format_date(value, format='short'), u'10/11/09')
        self.assertEqual(i18n.format_date(value, format='medium'),
                         u'10/11/2009')
        self.assertEqual(i18n.format_date(value, format='long'),
                         u'10 de novembro de 2009')
        self.assertEqual(i18n.format_date(value, format='full'),
                         u'terça-feira, 10 de novembro de 2009')
コード例 #46
0
ファイル: main.py プロジェクト: mbchiorean/appengfun
    def get(self):
        
        user = users.get_current_user()
        usrlocale = UserLocale.gql("WHERE user = :u",u=user).get()
        dateformat = ''
        lastaddeddate = None
        qdat = DateS.gql('ORDER BY __key__ DESC').get()
        
        if qdat:
            lastaddeddate = qdat.dat
            
        if usrlocale == None:
            locale=self.browser_locale()
            i18n.get_i18n().set_locale(locale)
            datLoc = I18n(self.request)
            datLoc.set_locale(locale)
            jqdatelocale = locale.replace('_', '-')
            if locale == 'en_US':
                dateformat = 'MM/dd/yyyy'
        else:
            locale = usrlocale.locale
            datelocale = usrlocale.datelocale
            i18n.get_i18n().set_locale(locale)
            jqdatelocale = datelocale.replace('_', '-')
            datLoc = I18n(self.request)       
            datLoc.set_locale(datelocale)
            dateformat = usrlocale.dateformat
            if dateformat == '' and usrlocale.datelocale =='en':
                dateformat = 'MM/dd/yyyy'
            
        if jqdatelocale not in SupportedLocales.locales:
            jqdatelocale = None
            
        if dateformat == '' or dateformat == None:
            dateformat = 'short'
            jqdateformat = None
        elif locale == 'en_US':
            jqdateformat = common.isotojqformat(dateformat)
        else:
            jqdateformat = common.isotojqformat(usrlocale.dateformat)

        message = i18n.gettext('Hello, world!')
        context = {
                    'message': message,
                    'thetime': datLoc.format_datetime(
                                        datetime.now(),
                                        format=dateformat),
                    'locale':jqdatelocale,
                    'dateformat':jqdateformat,
                    'datefromdb':datLoc.format_date(
                                        lastaddeddate,
                                        format=dateformat)
                  }
        self.render_response('tplhello.html', **context)
コード例 #47
0
    def get_template_environ(self, locale, additional_dirs):
        """Create and configure jinja template evaluation environment."""
        template_dir = self.get_template_home()
        dirs = [template_dir]
        if additional_dirs:
            dirs += additional_dirs
        jinja_environment = self.fs.get_jinja_environ(dirs)

        i18n.get_i18n().set_locale(locale)
        jinja_environment.install_gettext_translations(i18n)
        return jinja_environment
コード例 #48
0
ファイル: goemail.py プロジェクト: SecondLiners/GO2
def send_the_new_member_email(the_locale, the_email_address, new_member,
                              the_band):

    i18n.get_i18n().set_locale(the_locale)

    return _send_admin_mail(
        the_email_address,
        _('Gig-o-Matic New Member for band {0}').format(the_band.name),
        _('new_member_email').format(
            '{0} ({1})'.format(new_member.name, new_member.email_address),
            the_band.name, the_band.key.urlsafe()))
コード例 #49
0
    def test_set_timezone(self):
        i18n.get_i18n().set_timezone('UTC')
        self.assertEqual(i18n.get_i18n().tzinfo.zone, 'UTC')

        i18n.get_i18n().set_timezone('America/Chicago')
        self.assertEqual(i18n.get_i18n().tzinfo.zone, 'America/Chicago')

        i18n.get_i18n().set_timezone('America/Sao_Paulo')
        self.assertEqual(i18n.get_i18n().tzinfo.zone, 'America/Sao_Paulo')
コード例 #50
0
    def test_set_timezone(self):
        i18n.get_i18n().set_timezone("UTC")
        self.assertEqual(i18n.get_i18n().tzinfo.zone, "UTC")

        i18n.get_i18n().set_timezone("America/Chicago")
        self.assertEqual(i18n.get_i18n().tzinfo.zone, "America/Chicago")

        i18n.get_i18n().set_timezone("America/Sao_Paulo")
        self.assertEqual(i18n.get_i18n().tzinfo.zone, "America/Sao_Paulo")
コード例 #51
0
ファイル: common.py プロジェクト: helmuthb/devfest-at-site
    def dispatch(self):
        # Get a session store for this request.
        self.session_store = sessions.get_store(request=self.request)

        # Set the loale
        i18n.get_i18n().set_locale(self.locale)

        try:
            # Dispatch the request.
            webapp2.RequestHandler.dispatch(self)
        finally:
            # Save all sessions.
            self.session_store.save_sessions(self.response)
コード例 #52
0
    def test_format_date_pt_BR(self):
        i18n.get_i18n().set_locale("pt_BR")
        value = datetime.datetime(2009, 11, 10, 16, 36, 5)

        self.assertEqual(i18n.format_date(value, format="short"), "10/11/09")
        self.assertEqual(i18n.format_date(value, format="medium"), "10 de nov de 2009")
        self.assertEqual(
            i18n.format_date(value, format="long"), "10 de novembro de 2009"
        )
        self.assertEqual(
            i18n.format_date(value, format="full"),
            "terça-feira, 10 de novembro de 2009",
        )
コード例 #53
0
    def dispatch(self):

        # for requests still going to appspot, redirect
        request = self.request
        if request.host.startswith("gig-o-matic.appspot.com") or request.host.startswith("gig-o-matic.com"):
            import urlparse
            scheme, netloc, path, query, fragment = urlparse.urlsplit(request.url)

            # the cron stuff should not redirect
            if not path.startswith("/admin_"):
                url = urlparse.urlunsplit([scheme, "www.gig-o-matic.com", path, query, fragment])
                # Send redirect
                self.redirect(url, permanent=True, abort=True)

        if request.host.startswith("127.0.0.1"):
            import urlparse
            scheme, netloc, path, query, fragment = urlparse.urlsplit(request.url)

            # the cron stuff should not redirect
            if not path.startswith("/admin_"):
                url = urlparse.urlunsplit([scheme, "localhost:8080", path, query, fragment])
                # Send redirect
                self.redirect(url, permanent=True, abort=True)



        # Get a session store for this request.
        self.session_store = sessions.get_store(request=self.request)

        # Set locale on each request right away, to make it available to both
        # templates and backend Python code
        if self.request.get("locale"):
            locale = self.request.get("locale")
        elif self.user and self.user.preferences.locale:
            locale = self.user.preferences.locale
        else:
            locale = None
        i18n.get_i18n().set_locale(locale)

        try:
            # Dispatch the request.
            webapp2.RequestHandler.dispatch(self)
        except gigoexceptions.GigoException as error:
            logging.error( "Exception: %s" % error )
            self.render_template('error.html', [])
        except gigoexceptions.GigoRestException as error:
            logging.error( "Rest Exception: %s" % error )
            self.abort(401)
        finally:
            # Save all sessions.
            self.session_store.save_sessions(self.response)
コード例 #54
0
ファイル: main.py プロジェクト: sup6/pali
    def get(self, prefix=None, word=None):
        locale = getUserLocale(self.request.GET.get('locale'),
                               self.request.headers.get('accept_language'))
        i18n.get_i18n().set_locale(locale)
        #browser = self.request.headers.get('user_agent')

        titleword = u''
        resultDivInnerHTML = None
        if self.request.path.startswith('/browse'):
            if isValidPrefixAndWord(prefix, word, dicPrefixWordLists):
                if (word == None):
                    if (prefix != None):
                        # build prefix HTML here
                        titleword = u'browse words with prefix ' + prefix.decode(
                            'utf-8') + u' - '
                        resultDivInnerHTML = getPrefixHTML(
                            prefix, dicPrefixWordLists)
                else:
                    # build word HTML here
                    titleword = word.decode(
                        'utf-8') + u' - definition and meaning - '
                    resultDivInnerHTML = getWordHTML(word, jsonpLookup(word),
                                                     i18n)
            else:
                self.error(404)
                self.response.out.write("Page Not Found!")
                return

        compiledBootstrapJS = self.request.GET.get('compiledBootstrapJS')
        if compiledBootstrapJS not in ['yes', 'no']:
            compiledBootstrapJS = None
        if (compiledBootstrapJS == None):
            if os.environ['SERVER_SOFTWARE'].startswith("Development"):
                compiledBootstrapJS = 'no'
            else:
                compiledBootstrapJS = 'yes'

        template_values = {
            'titleword':
            titleword,
            'locale':
            '%s~%s' % (locale, self.request.headers.get('accept_language')),
            'compiledBootstrapJS':
            compiledBootstrapJS,
            'resultDivInnerHTML':
            resultDivInnerHTML
        }

        template = jinja_environment.get_template('index.html')
        self.response.out.write(template.render(template_values))
コード例 #55
0
ファイル: base.py プロジェクト: x1ddos/gae-template-py27
    def dispatch(self):
        # Get a session store for this request.
        # See this for more info on webapp2 sessions:
        # http://webapp-improved.appspot.com/api/webapp2_extras/sessions.html
        self.session_store = sessions.get_store(request=self.request)

        i18n.get_i18n().set_locale('en')

        try:
            # Dispatch the request.
            RequestHandler.dispatch(self)
        finally:
            # Save all sessions.
            self.session_store.save_sessions(self.response)
コード例 #56
0
    def set_up(self):
        handled = self._handle('locale')
        # f*****g Facebook scrapper sending undesired param
        handled = self._handle('fb_locale') or handled
        user = self.dependencies['_logged_user']
        import settings  # this is here to avoid cyclic dependency

        if user:
            locale_obj = i18n.get_i18n()
            locale_obj.set_locale(user.locale or settings.DEFAULT_LOCALE)
            locale_obj.set_timezone(user.timezone or settings.DEFAULT_TIMEZONE)
        elif not handled:
            locale_obj = i18n.get_i18n()
            locale_obj.set_locale(settings.DEFAULT_LOCALE)
            locale_obj.set_timezone(settings.DEFAULT_TIMEZONE)
コード例 #57
0
    def test_format_datetime_pt_BR(self):
        i18n.get_i18n().set_locale('pt_BR')
        value = datetime.datetime(2009, 11, 10, 16, 36, 05)

        self.assertEqual(i18n.format_datetime(value, format='short'),
                         u'10/11/09 16:36')
        self.assertEqual(i18n.format_datetime(value, format='medium'),
                         u'10/11/2009 16:36:05')
        #self.assertEqual(i18n.format_datetime(value, format='long'), u'10 de novembro de 2009 16:36:05 +0000')
        self.assertEqual(i18n.format_datetime(value, format='long'),
                         u'10 de novembro de 2009 16h36min05s +0000')
        #self.assertEqual(i18n.format_datetime(value, format='full'), u'terça-feira, 10 de novembro de 2009 16h36min05s Horário Mundo (GMT)')
        self.assertEqual(
            i18n.format_datetime(value, format='full'),
            u'ter\xe7a-feira, 10 de novembro de 2009 16h36min05s GMT+00:00')
コード例 #58
0
    def test_format_time_pt_BR(self):
        i18n.get_i18n().set_locale('pt_BR')
        value = datetime.datetime(2009, 11, 10, 16, 36, 05)

        self.assertEqual(i18n.format_time(value, format='short'), u'16:36')
        self.assertEqual(i18n.format_time(value, format='medium'), u'16:36:05')
        #self.assertEqual(i18n.format_time(value, format='long'), u'16:36:05 +0000')
        self.assertEqual(i18n.format_time(value, format='long'),
                         u'16h36min05s +0000')
        #self.assertEqual(i18n.format_time(value, format='full'), u'16h36min05s Horário Mundo (GMT)')
        self.assertEqual(i18n.format_time(value, format='full'),
                         u'16h36min05s GMT+00:00')

        i18n.get_i18n().set_timezone('America/Chicago')
        self.assertEqual(i18n.format_time(value, format='short'), u'10:36')
コード例 #59
0
ファイル: sites.py プロジェクト: twiffy/eabooc
    def get_template_environ(self, locale, additional_dirs):
        """Create and configure jinja template evaluation environment."""
        template_dir = self.get_template_home()
        dirs = [template_dir]
        if additional_dirs:
            dirs += additional_dirs
        jinja_environment = self.fs.get_jinja_environ(dirs)

        i18n.get_i18n().set_locale(locale)
        jinja_environment.install_gettext_translations(i18n)
        jinja_environment.filters['gcb_tags'] = jinja_filters.gcb_tags
        jinja_environment.filters['escapejs'] = jinja_filters.escapejs
        jinja_environment.filters['urlencode'] = jinja_filters.do_urlencode

        return jinja_environment