Пример #1
0
def test_force_locale():
    pytest.skip("This test needs to be run with --assert=reinterp or --assert=plain flag")
    app = Flask(__name__)
    b = babel.Babel(app)

    @b.localeselector
    def select_locale():
        return 'de_DE'

    with app.test_request_context():
        assert str(babel.get_locale()) == 'de_DE'
        with force_locale('en_US'):
            assert str(babel.get_locale()) == 'en_US'
        assert str(babel.get_locale()) == 'de_DE'
Пример #2
0
def login():
    print(get_locale())
    print(request.user_agent.platform)
    print(request.user_agent.language)
    print(request.user_agent.browser)
    print(request.user_agent.version)
    print(request.headers.get('User-Agent'))
    print(request.accept_languages.best_match(['en', 'fr']))
    print("============")
    fform = LoginForm(request.form)
    if request.method == 'POST' and fform.validate():
        with app.db.session_scope():
            if app.db.authenticate(request.form["user"],
                                   request.form["passwd"]):
                user = app.db.get_user_account_by_login(request.form["user"])
                if user.is_admin:
                    login_user(user)
                    flash(gettext("Login successfull"), "success")
                    return redirect('/')
                else:
                    flash(gettext("This user is not an admin"), "warning")
            else:
                flash(gettext("Combination of username and password wrong"),
                      "warning")
    return render_template('login.html', form=fform, nonav=True)
Пример #3
0
    def append_session_globals():
        """ Add two-character and three-char session locale to global
        template contexts: session_locale, session_locale_long_iso.
        """

        loc = get_locale()
        app.jinja_env.globals['session_locale'] = loc
Пример #4
0
    def inject_active_locale():
        g.available_locales = available_locales.values()
        g.active_locale = get_locale()

        g.primary_locales = _get_primary_locales()
        g.secondary_locales = \
            [l for l in g.available_locales if l not in g.primary_locales]
Пример #5
0
def get_translations():
    """ Search the Application directory and the Flask-User directory for the
        Flask-User translations file and return a Translations() object."""
    ctx = _request_ctx_stack.top
    if ctx is None:
        return None
    translations = getattr(ctx, 'flask_user_translations', None)
    if translations is None:
        # Prepare settings
        domain = 'flask_user'
        locales = [get_locale()]
        languages = [str(locale) for locale in locales]
        # Search Application directory
        app_dir = os.path.join(current_app.root_path, 'translations')
        filename = python_gettext.find(domain, app_dir, languages)
        if filename:
            translations = support.Translations.load(app_dir, locales, domain=domain)
        else:
            # Search Flask-User directory
            flask_user_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'translations')
            translations = support.Translations.load(flask_user_dir, locales, domain=domain)

        ctx.flask_user_translations = translations

    return ctx.flask_user_translations
Пример #6
0
def before_request():
    if request.method == 'GET':
        if request.args.get(
                'lang') is not None and request.args.get('lang') != '':
            current_user.locale = request.args.get('lang')
            g.current_locale = request.args.get('lang')

            @after_this_request
            def remember_locale(response):
                response.set_cookie('locale',
                                    current_user.locale,
                                    expires=datetime.datetime.utcnow() +
                                    datetime.timedelta(days=365))
                return response
        if request.args.get('tz') is not None and \
                        request.args.get('tz') in pytz.common_timezones:
            current_user.timezone = request.args.get('tz')
            g.current_timezone = request.args.get('tz')

            @after_this_request
            def remember_timezone(response):
                response.set_cookie('timezone', current_user.timezone)
                return response

    refresh()
    request.current_locale = get_locale()
    request.current_timezone = str(get_timezone())
Пример #7
0
def timedelta_filter(delta_or_date):
    """Format :class:`~datetime.datetime` or :class:`~datetime.timedelta`
    into localized string.

    If given parameter is a :class:`~datetime.datetime`,
    it will be subtracted by :func:`railgun.common.dateutil.utcnow` to
    get the :class:`~datetime.timedelta`.

    Usage:

    .. code-block:: html

        {{ handin.get_ctime() | timedelta }}

    :param delta_or_date: A :class:`~datetime.datetime` or a
        :class:`~datetime.timedelta` object.
    :return: :data:`None` if `delta_or_date` is :data:`None`, otherwise the
        localized timedelta string.
    """

    if not delta_or_date:
        return None
    if isinstance(delta_or_date, datetime):
        delta_or_date = delta_or_date - g.utcnow
    return format_timedelta(delta_or_date, locale=get_locale())
Пример #8
0
class SearchForm(Form):
    '''
    Form for searching the user database.
    '''

    questionnaire_area = CallableChoicesSelectField(choices=lambda: [
        ('ZZ', lazy_gettext('Choose an expertise area'))
    ] + [(q['id'], lazy_gettext(q['name'])) for q in QUESTIONNAIRES
         if q['questions']],
                                                    default='ZZ')
    country = CountryField()
    locale = CallableChoicesSelectField(choices=lambda: [
        ('ZZ', lazy_gettext('Choose a language'))
    ] + [(l.language, l.get_language_name(get_locale())) for l in LOCALES],
                                        default='ZZ')
    expertise_domain_name = CallableChoicesSelectField(choices=lambda: [
        ('ZZ', lazy_gettext('Choose a field of work'))
    ] + [(v, lazy_gettext(v)) for v in current_app.config['DOMAINS']],
                                                       default='ZZ')

    # This doesn't actually appear as a field in a form, but as a tab
    # in a result set, so it's a bit unusual.
    skill_level = SelectField(choices=[(level['score'], '')
                                       for level in LEVELS.values()],
                              coerce=int,
                              default=LEVELS['LEVEL_I_CAN_DO_IT']['score'])

    fulltext = StringField()
Пример #9
0
def money(i, currency="JOD "):
    return format_currency(
        number=int(i),
        currency=currency,
        locale=get_locale(),
        format=app.config.get('CURRENCY_FORMAT')
    )
Пример #10
0
  def __call__(self, field, **kwargs):
    kwargs.setdefault('id', field.id)
    field_id = kwargs.pop('id')
    value = kwargs.pop('value', None)
    if value is None:
      value = field._value()
    if not value:
      value = ''

    time_fmt = get_locale().time_formats['short'].format
    is_h12 = ('%(h)s' in time_fmt or '%(K)s' in time_fmt)

    input_params = {
      'data-template': self.widget_mode,
      'data-show-meridian': is_h12,
      'data-minute-step': self.minuteStep,
      'data-show-seconds': self.showSeconds,
      'data-second-step': self.secondStep,
      'data-show-inputs': self.showInputs,
      'data-disable-focus': self.disableFocus,
      'data-modal-backdrop': self.modalBackdrop
      }

    input_params = {k: Markup(json.dumps(v)) for k, v in input_params.items()}

    return Markup(render_template(self.template,
                                  id=field_id, value=value,
                                  field=field,
                                  required=False,
                                  timepicker_attributes=input_params))
Пример #11
0
def get_translations():
    """ Load .po file, cache .mo file repr in memory and return
    a Babel Translations object. This function is meant for monkey patching
    into Flask-Babel."""
    ctx = _request_ctx_stack.top
    if ctx is None:
        return None
    translations_dict = ctx.app.babel_translations_dict
    lock = ctx.app.babel_translations_lock
    locale = str(get_locale())
    lock.acquire()
    if translations_dict.get(locale) is None:
        mo_file = StringIO()
        dirname = os.path.join(ctx.app.root_path, 'translations')
        transfilename = os.path.join(dirname, taint_filename(locale),
                                     'LC_MESSAGES', "messages.po")
        if os.path.exists(transfilename):
            catalog = read_po(file(transfilename, "r"))
            write_mo(mo_file, catalog)
            mo_file.seek(0)
            translations = Translations(fp=mo_file)
        else:
            translations = gettext.NullTranslations()
        translations_dict[locale] = translations
    else:
        translations = translations_dict[locale]
    lock.release()
    return translations
Пример #12
0
  def __call__(self, field, **kwargs):
    kwargs.setdefault('id', field.id)
    field_id = kwargs.pop('id')
    kwargs.setdefault('name', field.name)
    field_name = kwargs.pop('name')
    kwargs.pop('type', None)
    value = kwargs.pop('value', None)
    if value is None:
      value = field._value()
    if not value:
      value = ''

    date_fmt = kwargs.pop('format', None)
    if date_fmt is not None:
      date_fmt = date_fmt.replace("%", "")\
        .replace("d", "dd")\
        .replace("m", "mm")\
        .replace("Y", "yyyy")
    else:
      date_fmt = get_locale().date_formats['short'].pattern
      date_fmt = babel2datepicker(date_fmt)
      date_fmt = date_fmt.replace('M', 'm')  # force numerical months

    s = u'<div {}>\n'.format(html_params(
      **{'class': "input-group date",
         'data-provide': 'datepicker',
         'data-date': value,
         'data-date-format': date_fmt}))

    s += u'  <input size="13" type="text" class="form-control" {} />\n'.format(
        html_params(name=field_name, id=field_id, value=value))
    s += u'  <span class="input-group-addon"><i class="icon-calendar"></i></span>\n'
    s += u'</div>\n'
    return Markup(s)
Пример #13
0
    def fill_i18n_from_request(self):
        """Fill :attr:`locale` and :attr:`timezone` according to current
        browser request.

        This method only works if it is called in a request context.
        """
        self.locale = str(get_locale())
Пример #14
0
def test_force_locale():
    pytest.skip(
        "This test needs to be run with --assert=reinterp or --assert=plain flag"
    )
    app = Flask(__name__)
    b = babel.Babel(app)

    @b.localeselector
    def select_locale():
        return 'de_DE'

    with app.test_request_context():
        assert str(babel.get_locale()) == 'de_DE'
        with force_locale('en_US'):
            assert str(babel.get_locale()) == 'en_US'
        assert str(babel.get_locale()) == 'de_DE'
Пример #15
0
def add():

    if not current_user.is_admin:
        abort(401)

    form = NewUserForm()

    if form.validate_on_submit():

        user = User(
            login=form.login.data,
            email=form.email.data,
            password = hash_password(form.login.data, form.password.data)
        )

        user.active = form.active.data
        user.account_type = form.account_type.data

        user.locale = form.locale.data
        user.timezone = form.timezone.data

        user.first_name = form.first_name.data
        user.last_name = form.last_name.data

        db.session.add(user)
        db.session.commit()

        flash(gettext(u'User added successfully'))

        return redirect(url_for('users.index'))
    else:
        form.timezone.data = str(get_timezone())
        form.locale.data = str(get_locale())

    return render_template('users/new.html', form=form)
Пример #16
0
def get_article(article_id, parse=False):
    locale = get_locale()
    contr = ArticleController(current_user.id)
    article = contr.get(id=article_id)
    if not article.readed:
        article['readed'] = True
        contr.update({'id': article_id}, {'readed': True})
    article['category_id'] = article.category_id or 0
    feed = FeedController(current_user.id).get(id=article.feed_id)
    article['icon_url'] = url_for('icon.icon', url=feed.icon_url) \
            if feed.icon_url else None
    readability_available = bool(current_user.readability_key
                                 or conf.PLUGINS_READABILITY_KEY)
    article['date'] = format_datetime(localize(article.date), locale=locale)
    article['readability_available'] = readability_available
    if parse or (not article.readability_parsed
            and feed.readability_auto_parse and readability_available):
        try:
            new_content = readability.parse(article.link,
                    current_user.readability_key
                    or conf.PLUGINS_READABILITY_KEY)
        except Exception as error:
            flash("Readability failed with %r" % error, "error")
            article['readability_parsed'] = False
        else:
            article['readability_parsed'] = True
            article['content'] = clean_urls(new_content, article['link'])
            new_attr = {'readability_parsed': True, 'content': new_content}
            contr.update({'id': article['id']}, new_attr)
    return article
Пример #17
0
def get_article(article_id, parse=False):
    locale = get_locale()
    contr = ArticleController(current_user.id)
    article = contr.get(id=article_id)
    if not article.readed:
        article['readed'] = True
        contr.update({'id': article_id}, {'readed': True})
    article['category_id'] = article.category_id or 0
    feed = FeedController(current_user.id).get(id=article.feed_id)
    article['icon_url'] = url_for('icon.icon', url=feed.icon_url) \
            if feed.icon_url else None
    readability_available = bool(current_user.readability_key
                                 or conf.PLUGINS_READABILITY_KEY)
    article['date'] = format_datetime(localize(article.date), locale=locale)
    article['readability_available'] = readability_available
    if parse or (not article.readability_parsed and feed.readability_auto_parse
                 and readability_available):
        try:
            new_content = readability.parse(
                article.link, current_user.readability_key
                or conf.PLUGINS_READABILITY_KEY)
        except Exception as error:
            flash("Readability failed with %r" % error, "error")
            article['readability_parsed'] = False
        else:
            article['readability_parsed'] = True
            article['content'] = clean_urls(new_content, article['link'])
            new_attr = {'readability_parsed': True, 'content': new_content}
            contr.update({'id': article['id']}, new_attr)
    return article
Пример #18
0
def login():
    print(get_locale())
    print(request.user_agent.platform)
    print(request.user_agent.language)
    print(request.user_agent.browser)
    print(request.user_agent.version)
    print(request.headers.get('User-Agent'))
    print(request.accept_languages.best_match(['en', 'fr']))
    print("============")
    fform = LoginForm(request.form)
    if request.method == 'POST' and fform.validate():
        with app.db.session_scope():
            if app.db.authenticate(request.form["user"], request.form["passwd"]):
                user = app.db.get_user_account_by_login(request.form["user"])
                if user.is_admin:
                    login_user(user)
                    flash(gettext("Login successfull"), "success")
                    return redirect('/')
                else:
                    flash(gettext("This user is not an admin"), "warning")
            else:
                flash(gettext("Combination of username and password wrong"), "warning")
    return render_template('login.html',
        form=fform,
        nonav = True)
Пример #19
0
    def fill_i18n_from_request(self):
        """Fill :attr:`locale` and :attr:`timezone` according to current
        browser request.

        This method only works if it is called in a request context.
        """
        self.locale = str(get_locale())
Пример #20
0
def invite():
    """Send invitations for this particular project"""

    form = InviteForm()

    if request.method == "POST":
        if form.validate():
            # send the email

            message_body = render_template("invitation_mail.%s" %
                                           get_locale().language)

            message_title = _(
                "You have been invited to share your "
                "expenses for %(project)s",
                project=g.project.name)
            msg = Message(message_title,
                          body=message_body,
                          recipients=[
                              email.strip()
                              for email in form.emails.data.split(",")
                          ])
            mail.send(msg)
            flash(_("Your invitations have been sent"))
            return redirect(url_for(".list_bills"))

    return render_template("send_invites.html", form=form)
Пример #21
0
def timedelta_filter(delta_or_date):
    """Format :class:`~datetime.datetime` or :class:`~datetime.timedelta`
    into localized string.

    If given parameter is a :class:`~datetime.datetime`,
    it will be subtracted by :func:`railgun.common.dateutil.utcnow` to
    get the :class:`~datetime.timedelta`.

    Usage:

    .. code-block:: html

        {{ handin.get_ctime() | timedelta }}

    :param delta_or_date: A :class:`~datetime.datetime` or a
        :class:`~datetime.timedelta` object.
    :return: :data:`None` if `delta_or_date` is :data:`None`, otherwise the
        localized timedelta string.
    """

    if not delta_or_date:
        return None
    if isinstance(delta_or_date, datetime):
        delta_or_date = delta_or_date - g.utcnow
    return format_timedelta(delta_or_date, locale=get_locale())
Пример #22
0
def add():

    if not current_user.is_admin:
        abort(401)

    form = NewUserForm()

    if form.validate_on_submit():

        user = User(login=form.login.data,
                    email=form.email.data,
                    password=hash_password(form.login.data,
                                           form.password.data))

        user.active = form.active.data
        user.account_type = form.account_type.data

        user.locale = form.locale.data
        user.timezone = form.timezone.data

        user.first_name = form.first_name.data
        user.last_name = form.last_name.data

        db.session.add(user)
        db.session.commit()

        flash(gettext(u'User added successfully'))

        return redirect(url_for('users.index'))
    else:
        form.timezone.data = str(get_timezone())
        form.locale.data = str(get_locale())

    return render_template('users/new.html', form=form)
Пример #23
0
def multilingual(cls):

    locale = get_locale()
    if locale is None:
        lang = unicode(settings.BABEL_DEFAULT_LOCALE)
    else:
        lang = unicode(locale.language)

    def create_property(cls, localized, columns, field):

        def getter(self):
            instance = localized.query.filter_by(id=self.id,
                                                 locale=lang).first()
            return instance and getattr(instance, field) or None

        def setter(self, value):
            from_db = localized.query.filter_by(id=self.id,
                                                locale=lang).first()

            instance = from_db or localized(parent=self, locale=lang)
            setattr(instance, field, value)
            instance.save()

        def expression(self):
            return db.Query(columns[field]) \
                .filter(localized.parent_id == self.id,
                        localized.locale == lang).as_scalar()

        setattr(cls, field, hybrid_property(getter, setter, expr=expression))

    def closure(cls):
        class_name = cls.__name__ + 'Localized'
        tablename = plural_underscored(class_name)

        if db.metadata.tables.get(tablename) is not None:
            return cls

        cls_columns = cls.__table__.get_children()
        columns = dict([(c.name, c.copy()) for c in cls_columns
                        if isinstance(c.type, (db.Unicode, db.UnicodeText))])
        localized_names = columns.keys()

        columns.update({
            'parent_id': db.Column(db.Integer,
                                   db.ForeignKey(cls.__tablename__ + '.id',
                                                 ondelete="CASCADE",
                                                 onupdate="CASCADE"),
                                   nullable=True),
            'parent': db.relationship(cls, backref='localized_ref'),
            'locale': db.Column(db.Unicode(255), default=lang, index=True)
        })

        cls_localized = type(class_name, (db.Model, CRUDMixin), columns)

        for field in localized_names:
            create_property(cls, cls_localized, columns, field)

        return cls

    return closure(cls)
Пример #24
0
def setup_caching():
    """Set some request attributes at the beginning of the request.
    By default, caching will be disabled."""
    locale = get_locale()
    request._app_locale = str(locale)
    request._http_cache = False
    request._http_private = False
    request._http_etag = None
Пример #25
0
def mdtemplate(filename):
    try:
        source, _, _ = current_app.jinja_loader.get_source(
            current_app.jinja_env, '%s/%s' % (get_locale(), filename))
        output = Markup(markdown(source))
    except TemplateNotFound:
        output = gettext('File not found!')
    return output
Пример #26
0
def inject_locales():
    # TODO: caching
    locale_links = {
        locale: request.url.replace(request.host, host(locale))
        for locale in cur_app.LOCALES
    }

    return dict(locale_links=locale_links, locale=str(get_locale()))
Пример #27
0
 def _value(self):
   if self.raw_data:
     return ' '.join(self.raw_data)
   else:
     date_fmt = get_locale().date_formats['short'].pattern
     date_fmt = date_fmt.replace('MMMM', 'MM')\
                        .replace('MMM', 'MM')  # force numerical months
     return format_date(self.data, date_fmt) if self.data else ''
Пример #28
0
def settings(page=None):
    if not session.get("uid"):
        return redirect(url_for("signin", next=get_path(request)))

    if page not in ("identity", "regional", "password"):
        return redirect(url_for("settings", page="identity"))

    if request.method == "POST":
        if request.form.get("validate"):
            if page == "password":
                backend = UserBackend()

                if not backend.authenticate(session.get("login"), request.form.get("password-current")):
                    flash(_("Current password is invalid."), "error")
                elif request.form.get("password-new") != request.form.get("password-repeat"):
                    flash(_("Passwords don't match."), "error")
                else:
                    try:
                        backend.set(modify=True, login=session.get("login"), password=request.form.get("password-new"))
                        flash(_("Password successfuly changed."), "info")
                    except PasswordTooShort:
                        flash(
                            _(
                                "Password is too short. Must be a least %(length)d characters long.",
                                length=PASSWORD_MIN_LENGTH,
                            ),
                            "error",
                        )
            else:
                settings = dict((x, request.form.get(x)) for x in SETTINGS_LIST if x in request.form)

                if settings:
                    user = UserBackend().set(modify=True, login=session.get("login"), **settings)

                    session.update(
                        {
                            "name": user.fullname,
                            "avatar": "//gravatar.com/avatar/%s" % hashlib.md5(user.email.lower()).hexdigest(),
                        }
                    )

                    if "locale" in settings:
                        g.user.locale = settings.get("locale")

                    flash(_("Settings successfuly saved."), "info")

        return redirect(url_for("settings", page=page))

    locales = [(x.language, x.display_name.capitalize()) for x in app.babel_instance.list_translations()]

    return render_template(
        "settings.html",
        page=page,
        locales=locales,
        timezones=common_timezones,
        current_locale=get_locale().language,
        current_timezone=get_timezone().zone,
    )
Пример #29
0
def _get_translations():
    ctx = _request_ctx_stack.top
    root = os.path.dirname(os.path.abspath(__file__))
    translations_path = os.path.join(root, 'translations')
    translations = support.Translations.load(translations_path,
                                             [babel.get_locale()],
                                             domain='messages')
    ctx.wtforms_translations = translations
    return translations
Пример #30
0
def template_context_processor():
    locale = get_locale()
    data = {
        'DEBUG': current_app.config.get('DEBUG'),
        'current_language': locale.language,
        'current_locale': get_locale(),
        'reserved_terms': RESERVED_TERMS,
        'url_for': url_for,
        'site_url': url_for('home.index').rstrip('/'),
        'number_symbols_group': locale.number_symbols.get('group'),
        'number_symbols_decimal': locale.number_symbols.get('decimal'),
        'site_title': current_app.config.get('SITE_TITLE'),
        'languages': languages(),
        'logged_in': auth.account.logged_in(),
        'current_user': current_user,
        'can': auth
    }
    return data
Пример #31
0
def inject_locales():
    # TODO: caching
    locale_links = {
            locale: request.url.replace(request.host, host(locale))
            for locale in cur_app.LOCALES
        }

    return dict(locale_links=locale_links,
            locale=str(get_locale()))
Пример #32
0
def _get_translations():
  ctx = _request_ctx_stack.top
  root = os.path.dirname(os.path.abspath(__file__))
  translations_path = os.path.join(root, 'translations')
  translations = support.Translations.load(
      translations_path, [babel.get_locale()], domain='messages'
    )
  ctx.wtforms_translations = translations
  return translations
Пример #33
0
class ChangeLocaleForm(Form):
    '''
    Form that allows the user to change the locale of the site.
    '''

    locale = SelectField(label=lazy_gettext('Language'),
                         default=lambda: str(get_locale()),
                         choices=[(str(l), l.get_display_name()
                                   or l.english_name or str(l))
                                  for l in l10n.VALID_LOCALES])
Пример #34
0
def languages():
    current_locale = get_locale()

    def details(locale):
        return {
            "lang_code": locale.language,
            "lang_name": locale.language_name,
            "current_locale": locale == current_locale
        }
    return [details(l) for l in get_available_locales()]
Пример #35
0
    class RegistrationForm(UserForm):
        LANGUAGES = [get_locale().language]

        password = PasswordField(lazy_gettext('login.placeholder.password'), [
            validators.Required(),
            validators.EqualTo(
                'confirm', message=lazy_gettext('signup.error.passwordsmatch'))
        ])
        confirm = PasswordField(
            lazy_gettext('signup.placeholder.confirmpassword'))
Пример #36
0
def filter_translit(*args, **kwargs):
    locale = str(get_locale())
    _type = kwargs.get('type')
    if len(args) == 1:
        string = args[0]
        return translit(string, 'ko', locale, _type) if locale != 'ko' else string
    elif args:
        raise Exception('filter_translit() only accepts one or zero argument')
    else:
        return lambda x: filter_translit(x, type=_type)
Пример #37
0
def register():

    if not app.config.get('ALLOW_REGISTRATIONS'):
        abort(404)

    form = NewUserForm()

    if form.validate_on_submit():

        try:
            exists = User.query.filter(User.email == form.email.data).first()

            if exists:
                flash(gettext('Email address already registered'))
            else:
                user = User(
                    login=form.login.data,
                    email=form.email.data,
                    password = hash_password(form.login.data, form.password.data),
                    active = ACCOUNT_DISABLED
                )

                user.first_name = form.first_name.data
                user.last_name = form.last_name.data

                user.locale = str(get_locale())
                user.timezone = str(get_timezone())

                db.session.add(user)
                db.session.commit()

                # Send email
                sent = send_email(
                    gettext('Welcome to %(appname)s', appname = app.config.get('APP_TITLE')),
                    app.config.get('MAIL_SENDER'),
                    [form.email.data],
                    render_template('users/mail_register.txt', user=user),
                    render_template('users/mail_register.html', user=user),
                )

                if sent:
                    flash(gettext('Account created successfully. Please check your email for instructions on activating your account'))
                else:
                    flash(gettext('Account created successfully but there were server-side errors while sending the email activation code. Your account needs to be manually activated.'))

                return redirect(url_for('users.login'))

        except OperationalError:
            if app.config.get('DEBUG'):
                flash(gettext('Error creating user. Database not set'))
                return redirect(url_for('users.login'))
            else:
                abort(500)

    return render_template('users/register.html', form=form, hide_sidebar=True, hide_header=True, class_body='bg-black', class_html ='bg-black')
Пример #38
0
 def formersector(self):
     return db.engine.execute("""
         SELECT sector.code AS "sector.code", 
                sector.percentage AS "sector.percentage",
                sector.assumed AS "sector.assumed",
                dacsector.description_%s AS "dacsector.description"
         FROM sector
         JOIN dacsector ON sector.code = dacsector.code
         WHERE sector.id = '%s';
         """ % (str(get_locale()).upper(),
                self.formersector_id)).first()
Пример #39
0
def inject():
    from dudel.views import get_locale
    return dict(
        ICONS=ICONS,
        login_form=LoginForm(),
        lang_form=LanguageForm(),
        enumerate=enumerate,
        lang=get_locale(),
        current_timezone=get_current_timezone(),
        default_timezone=default_timezone
        )
Пример #40
0
 def _value(self):
   if self.raw_data:
     return ' '.join(self.raw_data)
   else:
     locale = get_locale()
     date_fmt = locale.date_formats['short'].pattern
     date_fmt = date_fmt.replace('MMMM', 'MM')\
                        .replace('MMM', 'MM')  # force numerical months
     time_fmt = locale.time_formats['short']
     dt_fmt = locale.datetime_formats['short'].format(time_fmt, date_fmt)
     return format_datetime(self.data, dt_fmt) if self.data else ''
Пример #41
0
def etag_cache_keygen(*keys):
    if not request._http_cache:
        return

    args = sorted(set(request.args.items()))
    # jquery where is your god now?!?
    args = filter(lambda (k, v): k != '_', args)

    request._http_etag = cache_hash(args, current_user, keys, get_locale())
    if request.if_none_match == request._http_etag:
        raise NotModified()
Пример #42
0
    def get(self, short=None):
        locale = get_locale()
        objects = []
        for short, name in current_app.config['LANGUAGES'].items():
            objects.append({
                'name': name,
                'short': short,
                'is_set': locale.language == short
            })

        return jsonify_status_code({'objects': objects})
Пример #43
0
def filter_translit(*args, **kwargs):
    locale = str(get_locale())
    _type = kwargs.get('type')
    if len(args) == 1:
        string = args[0]
        return translit(string, 'ko', locale,
                        _type) if locale != 'ko' else string
    elif args:
        raise Exception('filter_translit() only accepts one or zero argument')
    else:
        return lambda x: filter_translit(x, type=_type)
Пример #44
0
 def title(self):
     current_locale = get_locale()
     if current_locale is None:
         current_locale = babel.Locale('en')
     # Special case possesive form in English
     if current_locale.language.lower() == 'en' and \
             current_user.name[:-1] == u's':
         return u"{}' Requests".format(current_user.name)
     else:
         # TRANS: The title of the page listing all requests an individual
         # TRANS: user has made.
         return gettext(u"%(name)s's Requests", name=current_user.name)
Пример #45
0
def locale_preferences():
    main_locale = get_locale()
    locales = [main_locale]

    def to_locale(language):
        try:
            return Locale(language)
        except UnknownLocaleError:
            return main_locale

    locales.extend(map(to_locale, iter(request.accept_languages.values())))
    return locales
Пример #46
0
def etag_cache_keygen(*keys):
    if not request._http_cache:
        return

    args = sorted(set(request.args.items()))
    # jquery where is your god now?!?
    args = filter(lambda (k, v): k != '_', args)

    request._http_etag = cache_hash(args, current_user,
                                    keys, get_locale())
    if request.if_none_match == request._http_etag:
        raise NotModified()
Пример #47
0
def model(id):
    model = models.index[id](str(get_locale()))
    img_url = url_for('static', filename='models/%i.gif' % id)
    form = None
    if len(model.args) > 0:
        form = render_template('additional_form.html', form = model.args)
    return jsonify(
        name = model.get('name'),
        description = model.get('description'),
        img = img_url,
        form = form
    )
Пример #48
0
def template_context_processor():
    locale = get_locale()
    data = {
        'current_language': locale.language,
        'url_for': url_for,
        'reserved_terms': RESERVED_TERMS,
        'site_url': url_for('home.index').rstrip('/'),
        'number_symbols_group': locale.number_symbols.get('group'),
        'number_symbols_decimal': locale.number_symbols.get('decimal'),
        'site_title': current_app.config.get('SITE_TITLE')
    }
    return data
Пример #49
0
def create_project():
    form = ProjectForm()
    if request.method == "GET" and 'project_id' in request.values:
        form.name.data = request.values['project_id']

    if request.method == "POST":
        # At first, we don't want the user to bother with the identifier
        # so it will automatically be missing because not displayed into
        # the form
        # Thus we fill it with the same value as the filled name,
        # the validation will take care of the slug
        if not form.id.data:
            form.id.data = form.name.data
        if form.validate():
            # save the object in the db
            project = form.save()
            db.session.add(project)
            db.session.commit()

            # create the session object (authenticate)
            session[project.id] = project.password
            session.update()

            # send reminder email
            g.project = project

            message_title = _(
                "You have just created '%(project)s' "
                "to share your expenses",
                project=g.project.name)

            message_body = render_template("reminder_mail.%s" %
                                           get_locale().language)

            msg = Message(message_title,
                          body=message_body,
                          recipients=[project.contact_email])
            try:
                mail.send(msg)
            except SMTPRecipientsRefused:
                msg_compl = 'Problem sending mail. '
                # TODO: destroy the project and cancel instead?
            else:
                msg_compl = ''

            # redirect the user to the next step (invite)
            flash(
                _("%(msg_compl)sThe project identifier is %(project)s",
                  msg_compl=msg_compl,
                  project=project.id))
            return redirect(url_for(".invite", project_id=project.id))

    return render_template("create_project.html", form=form)
Пример #50
0
def inject():
    from dudel.views import get_locale
    return dict(
        ICONS=ICONS,
        login_form=LoginForm(),
        lang_form=LanguageForm(),
        enumerate=enumerate,
        lang=get_locale(),
        current_timezone=get_current_timezone(),
        default_timezone=default_timezone,
        PollType=PollType
        )
Пример #51
0
def datepicker(*args, **kwargs):
    today = date.today()
    return _txtinput(*args, **kwargs) + """
<script type="text/javascript">
  $(function() {$('#%(id)s').datepicker({autoclose: true, weekStart: "1", date: "%(today)s", format: "%(format)s", language: "%(language)s"});});
</script>
""" % {
        "id": args[0].id,
        "today": today.isoformat(),
        "format": "yyyy-mm-dd",
        "language": get_locale().language
    }
Пример #52
0
    class SettingsForm(Form, wtforms.ext.i18n.form.Form):
        LANGUAGES = [get_locale().language]

        language = SelectField(
            lazy_gettext('settings.language'),
            default=current_user.config.language,
            choices=[('auto', lazy_gettext('settings.language.autodetect')),
                     ('en', u'English'), ('fr', u'Français')])
        episodesPerShow = IntegerField(
            lazy_gettext('settings.episodesPerShow'),
            default=current_user.config.episodesPerShow,
            validators=[validators.NumberRange(min=1)])
Пример #53
0
def myget_translations():
    """Returns the correct gettext translations that should be used for
    this request.  This will never fail and return a dummy translation
    object if used outside of the request or if a translation cannot be
    found.
    """
    ctx = _request_ctx_stack.top
    if ctx is None:
        return None
    translations = getattr(ctx, 'babel_translations', None)
    dirname = os.path.join(ctx.app.root_path, ctx.app.config.get('LANGUAGE_DIR'))  # base translations
    files = []

    if os.path.exists(dirname):
        try:
            for mo in [f[:-3] for f in os.listdir(os.path.join(dirname, str(get_locale()) + '/LC_MESSAGES')) if f.endswith('.mo')]:
                files.append(support.Translations.load(dirname, [get_locale()], domain=mo))
        except:
            pass

    # load translations of blueprints
    for bp_name in ctx.app.blueprints:
        dirname = os.path.join(ctx.app.blueprints[bp_name].root_path, 'translations')
        if not os.path.exists(dirname):
            continue
        files.append(support.Translations.load(dirname, [get_locale()], domain=bp_name))

    for f in files:
        if not translations:
            translations = f
        else:
            try:
                if f.files[0] not in translations.files:
                    translations.files.extend(f.files)
                    translations._catalog.update(f._catalog)
            except:
                pass

    ctx.babel_translations = translations
    return translations
Пример #54
0
class SearchForm(Form):
    '''
    Form for searching the user database.
    '''
    country = CountryField()
    locales = CallableChoicesSelectMultipleField(
        widget=Select(multiple=True),
        choices=lambda: [(l.language, l.get_language_name(get_locale()))
                         for l in LOCALES])
    expertise_domain_names = CallableChoicesSelectMultipleField(
        widget=Select(multiple=True),
        choices=lambda: [(v, lazy_gettext(v))
                         for v in current_app.config['DOMAINS']])
Пример #55
0
def site_js():
    l = get_locale()
    js_i18n = cache.get('site_js_%s' % (l, ))
    if not js_i18n:
        js_i18n = render_template('site.js')
        cache.set('site_js_%s' % (l, ), js_i18n, timeout=60 * 60)
    r = Response(js_i18n,
                 headers={
                     'Content-type': 'application/javascript',
                     'Cache-control': 'private, max-age=3600'
                 })
    r.add_etag()
    r.make_conditional(request)
    return r
Пример #56
0
def age(dt, now=None, add_direction=True, date_threshold=None):
  """
  :param dt: :class:`datetime<datetime.datetime>` instance to format

  :param now: :class:`datetime<datetime.datetime>` instance to compare to `dt`

  :param add_direction: if `True`, will add "in" or "ago" (example for `en`
       locale) to time difference `dt - now`, i.e "in 9 min." or " 9min. ago"

  :param date_threshold: above threshold, will use a formated date instead of
       elapsed time indication. Supported values: "day".
  """
  # Fail silently for now XXX
  if not dt:
    return ""

  if not now:
    now = datetime.datetime.utcnow()

  locale = babel.get_locale()
  dt = utc_dt(dt)
  now = utc_dt(now)
  delta = dt - now

  if date_threshold is not None:
    dy, dw, dd = dt_cal = dt.isocalendar()
    ny, nw, nd = now_cal =now.isocalendar()

    if dt_cal != now_cal:
      # not same day
      remove_year = (dy == ny)
      date_fmt = locale.date_formats['long'].pattern
      time_fmt = locale.time_formats['short'].pattern
      fmt = locale.datetime_formats['medium']

      if remove_year:
        date_fmt = date_fmt.replace('y', '').strip()
        # remove leading or trailing spaces, comma, etc...
        date_fmt = re.sub(u'^[^A-Za-z]*|[^A-Za-z]*$', u'', date_fmt)

      fmt = fmt.format(time_fmt, date_fmt)
      return babel.format_datetime(dt, format=fmt)

  # don't use (flask.ext.)babel.format_timedelta: as of Flask-Babel 0.9 it
  # doesn't support "threshold" arg.
  return format_timedelta(delta,
                          locale=locale,
                          granularity='minute',
                          threshold=0.9,
                          add_direction=add_direction)