Пример #1
0
    def __init__(self, search_path=None, auto_reload=True, cache_dir=None,
                method=method):
        """Initialise le moteur de rendu."""

        super(RumGenshiRenderer, self).__init__(
            search_path, auto_reload, cache_dir, method)

        # La classe GenshiRenderer définit cette variable avec un chargeur
        # de modèles qui comporte un filtre pour ajouter l'attribut "lang".
        # On écrase ce chargeur pour le remplacer par un qui a le même
        # traitement mais qui ajoute aussi un traducteur.
        self.loader = TemplateLoader(
            search_path=self.search_path,
            auto_reload=self.auto_reload,
            callback=self.__setup_filters,
        )

        # On configure la classe pour que les traductions
        # de vigilo.themes soient utilisées pour traduire
        # les templates utilisés par Rum.
        i18n_dir = resource_filename('vigilo.themes.i18n', '')
        lang = get_lang()

        if lang is None:
            self.__tpl_translator = gettext.NullTranslations()
        else:
            self.__tpl_translator = gettext.translation(
                'vigilo-themes', i18n_dir, lang, fallback=True)
Пример #2
0
    def index(self, sc_type='list', sc_parent=None):
        curr_lang = get_lang()

        # connected user
        user = dbs.query(SapnsUser).get(request.identity['user'].user_id)

        # get children shortcuts (shortcuts.parent_id = sc_parent) of the this user
        shortcuts = user.get_shortcuts(id_parent=sc_parent)

        params = {}
        if sc_parent:
            params = dict(sc_parent=sc_parent)
        came_from = url('/dashboard/', params=params)

        if sc_parent:
            sc_parent = dbs.query(SapnsShortcut).get(sc_parent).parent_id

        else:
            sc_parent = None

        return dict(page='dashboard',
                    shortcuts=shortcuts,
                    sc_type=sc_type,
                    sc_parent=sc_parent,
                    _came_from=came_from)
Пример #3
0
def init_lang():
    default_lang = extract_lang(get_lang(), r'^[a-z]{2}$')
    _language = config.get('app.language_cookie', 'sp_language') 
    lang = request.cookies.get(_language)
    if not lang:
        lang = default_lang
        save_language(lang)
        
    set_lang(lang)
    
    return lang
Пример #4
0
def get_locale():
    locales = get_lang()
    if locales is not None:
        for locale in locales:
            try:
                locale = Locale.parse(locale)
                return locale
            except UnknownLocaleError:
                pass

    return Locale('en')
Пример #5
0
def init_lang():
    default_lang = extract_lang(get_lang(), r'^[a-z]{2}$')
    _language = config.get('app.language_cookie', 'sp_language')
    lang = request.cookies.get(_language)
    if not lang:
        lang = default_lang
        save_language(lang)

    set_lang(lang)

    return lang
Пример #6
0
def translated_pages(lang=None):
    """Returns all the flat pages that are translated in the given language.

    a page is considered translated if it's slug (url) ends in `-it` `-es` and so on
    if `lang` is not provided then the language of the browser of the user is used
    """
    from flatpages.model import FlatPage
    if not lang:
        from tg.i18n import get_lang
        lang = get_lang(all=False)[0]
    pages = FlatPage.all_pages()
    # p[0] -> title  # p[1] -> url
    return ((p[0], p[1]) for p in pages if p[1].endswith('-' + lang))
Пример #7
0
    def _add_middleware(self, conf, app):
        """Configure the ToscaWidgets2 middleware"""
        if not conf['tw2.enabled']:
            return app

        from tw2.core.middleware import Config, TwMiddleware
        from tg.i18n import ugettext, get_lang

        available_renderers = set(conf.get('renderers', []))
        shared_engines = list(available_renderers
                              & set(Config.preferred_rendering_engines))
        if not shared_engines:
            raise TGConfigError(
                'None of the configured rendering engines %s is supported '
                'by ToscaWidgets2, unable to configure ToscaWidgets.' %
                available_renderers)

        default_renderer = conf.get('default_renderer', None)
        if default_renderer in shared_engines:
            tw2_engines = [default_renderer] + shared_engines
            tw2_default_engine = default_renderer
        else:
            # If preferred rendering engine is not available in TW2, fallback to another one
            tw2_engines = shared_engines
            tw2_default_engine = shared_engines[0]

        default_tw2_config = dict(default_engine=tw2_default_engine,
                                  preferred_rendering_engines=tw2_engines,
                                  translator=ugettext,
                                  get_lang=lambda: get_lang(all=False),
                                  auto_reload_templates=conf.get(
                                      'auto_reload_templates', False),
                                  controller_prefix='/tw2/controllers/',
                                  res_prefix='/tw2/resources/',
                                  debug=conf['debug'],
                                  rendering_extension_lookup={
                                      'mako': ['mak', 'mako'],
                                      'genshi': ['genshi', 'html'],
                                      'jinja': ['jinja', 'jinja2'],
                                      'kajiki': ['kajiki', 'xhtml', 'xml']
                                  })

        default_tw2_config.update(conf.get('custom_tw2_config', {}))
        app = TwMiddleware(app, **default_tw2_config)
        return app
Пример #8
0
def get_calendar_lang():
    from tg.i18n import get_lang
    import tg

    # TODO: Utiliser le champ "language" du modèle pour cet utilisateur ?
    # On récupère la langue du navigateur de l'utilisateur
    lang = get_lang()
    if not lang:
        lang = tg.config['lang']
    else:
        lang = lang[0]

    # TODO: Il faudrait gérer les cas où tout nous intéresse dans "lang".
    # Si l'identifiant de langage est composé (ex: "fr_FR"),
    # on ne récupère que la 1ère partie.
    lang = lang.replace('_', '-')
    lang = lang.split('-')[0]
    return lang
Пример #9
0
    def _add_middleware(self, conf, app):
        """Configure the ToscaWidgets2 middleware"""
        if not conf['tw2.enabled']:
            return app

        from tw2.core.middleware import Config, TwMiddleware
        from tg.i18n import ugettext, get_lang

        available_renderers = set(conf.get('renderers', []))
        shared_engines = list(available_renderers & set(Config.preferred_rendering_engines))
        if not shared_engines:
            raise TGConfigError(
                'None of the configured rendering engines %s is supported '
                'by ToscaWidgets2, unable to configure ToscaWidgets.' % available_renderers
            )

        default_renderer = conf.get('default_renderer', None)
        if default_renderer in shared_engines:
            tw2_engines = [default_renderer] + shared_engines
            tw2_default_engine = default_renderer
        else:
            # If preferred rendering engine is not available in TW2, fallback to another one
            tw2_engines = shared_engines
            tw2_default_engine = shared_engines[0]

        default_tw2_config = dict(default_engine=tw2_default_engine,
                                  preferred_rendering_engines=tw2_engines,
                                  translator=ugettext,
                                  get_lang=lambda: get_lang(all=False),
                                  auto_reload_templates=conf.get('auto_reload_templates', False),
                                  controller_prefix='/tw2/controllers/',
                                  res_prefix='/tw2/resources/',
                                  debug=conf['debug'],
                                  rendering_extension_lookup={
                                       'mako': ['mak', 'mako'],
                                       'genshi': ['genshi', 'html'],
                                       'jinja': ['jinja', 'jinja2'],
                                       'kajiki': ['kajiki', 'xhtml', 'xml']
                                  })

        default_tw2_config.update(conf.get('custom_tw2_config', {}))
        app = TwMiddleware(app, **default_tw2_config)
        return app
Пример #10
0
        def get_primary_languages():
            available = [lang['language_code'] for lang in languages()]
            requested = distinct(get_lang() or ['en'])

            # add primary languages
            primary = []
            for language in requested:
                if language in available:
                    primary.append(language)
                else:
                    try:
                        locale = parse_locale(language)
                    except:
                        continue

                    if locale[0] in available:
                        primary.append(locale[0])

            if len(primary) == 0:
                return [language_info('en')]

            return [language_info(lang) for lang in distinct(primary)]
Пример #11
0
    def index(self, sc_type='list', sc_parent=None):
        curr_lang = get_lang()

        # connected user
        user = dbs.query(SapnsUser).get(request.identity['user'].user_id)

        # get children shortcuts (shortcuts.parent_id = sc_parent) of the this user
        shortcuts = user.get_shortcuts(id_parent=sc_parent)

        params = {}
        if sc_parent:
            params = dict(sc_parent=sc_parent)
        came_from = url('/dashboard/', params=params)

        if sc_parent:
            sc_parent = dbs.query(SapnsShortcut).get(sc_parent).parent_id

        else:
            sc_parent = None

        return dict(page='dashboard', shortcuts=shortcuts, sc_type=sc_type,
                    sc_parent=sc_parent, _came_from=came_from)
Пример #12
0
 def get_supported_lang(self, **kw):
     return dict(lang=i18n.get_lang(all=False))
Пример #13
0
 def get_lang(self, **kw):
     return dict(lang=i18n.get_lang())
Пример #14
0
 def get_supported_lang(self, **kw):
     return dict(lang=i18n.get_lang(all=False))
Пример #15
0
 def get_lang(self, **kw):
     return dict(lang=i18n.get_lang())
Пример #16
0
    def save(self, **kw):
        if not is_valid_sn(kw['user_name']):
            flash(
                _('Inserisci il tuo numero di matricola nel formato indicato.'
                  ), 'error')
            return redirect('/form/edit')
        user = User.by_user_name(kw['user_name'])
        if user:
            flash(_('Matricola già in uso!'), 'error')
            return redirect('/form/edit')

        token = generate_password()
        passwd = generate_password()

        user = User()
        user.user_name = kw['user_name'].lower()
        user.email_address = user.user_name + \
                             ('@studenti.polito.it' if user.user_name[0] == 's' else '@polito.it')
        user.display_name = user.user_name
        user.first_name = kw['first_name']
        user.last_name = kw['last_name']
        user.study_course = kw['cdl']
        user.year = kw['year']
        user.interest = kw['interest']
        user.lang = ('it' if not get_lang(all=False)[0] else get_lang(
            all=False)[0])
        user.letter = kw['letter']
        user.token = token
        user.password = passwd
        user.created = datetime.now()
        DBSession.add(user)
        DBSession.flush()

        status_link = url('/form/status?m=', None, True) + user.user_name
        status_link += '&auth=' + token

        noreply_email = Option.get_value('no_reply_email')
        mailer = get_mailer(request)
        message = Message(subject=_("Reclutamento WEEE Open"),
                          sender=noreply_email,
                          recipients=[user.email_address],
                          body=(_("""Ciao!
Abbiamo ricevuto la tua candidatura per il team WEEE Open, questa è la pagina da cui potrai verificare lo stato della tua domanda:

%s

Se la domanda sarà approvata, riceverai un'email sempre a questo indirizzo con scritto chi contattare per passare al colloquio. Le stesse informazioni saranno visibili anche alla pagina di cui sopra.

Buona fortuna ;)
Il software WEEEHire per conto del team WEEE Open
""") % status_link))
        mailer.send(message)

        if Option.get_value('new_request_notify'):
            admin_email = User.by_user_id(1).email_address
            message = Message(subject="WEEEhire - Nuova richiesta ricevuta",
                              sender=noreply_email,
                              recipients=[admin_email],
                              body=(url('/soviet/read?uid=', None, True) +
                                    str(user.user_id)))
            mailer.send(message)
        flash(
            _("Candidatura inviata con successo!\nSalva questa pagina nei preferiti per controllare lo stato. Ti abbiamo inviato lo stesso link anche a %s"
              ) % user.email_address)
        return redirect(status_link)