Example #1
0
    def validate_recaptcha(self, field):
        if 'need_verify' not in session or not session['need_verify']:
            return

        if 'verify' not in session or session['verify'] != str(
                field.data).upper():
            raise ValidationError, gettext("This captcha is not matching")
Example #2
0
 def validate_nickname(self, field):
     # todo
     #        # 昵称不允许重复
     #        if not UserService.count_by_nickname(field.data):
     #            raise ValidationError, gettext("This nickname is taken")
     if not WordReservedService.word_allowed(field.data):
         raise ValidationError, gettext("This nickname is taken")
Example #3
0
    def add_contacts(self):
        if request.method == 'POST':
            if not request.form.get('conference') or not request.form.get(
                    'profile'):
                flash('You must select Conference and Profile')
                if current_user.has_role('admin'):
                    return redirect(url_for('contact_admin.index_view'))
                else:
                    return redirect(url_for('contact_user.index_view'))

            conference = Conference.query.filter_by(
                id=request.form['conference']).first_or_404()

            profile = ParticipantProfile.query.filter_by(
                id=request.form['profile']).first_or_404()

            contacts = Contact.query.filter(
                Contact.id.in_(request.form['ids'].split(',')))

            for c in contacts:
                if Participant.query.filter_by(phone=c.phone,
                                               conference=conference).first():
                    flash(gettext('%(contact)s is already there.', contact=c))
                    continue
                p = Participant(phone=c.phone,
                                name=c.name,
                                user=current_user,
                                profile=profile,
                                conference=conference)
                flash(gettext('%(contact)s added.', contact=c))

                db.session.add(p)
            db.session.commit()

        return redirect(url_for('.edit_view', id=conference.id))
Example #4
0
    def delete(self, pid, user):
        """
        Delete photo
        Params:
            user: the User instance that pass authentication (logged user)

        Request params:

        Response:
        {
            "id": 111,
        }
        """
        # Update photo
        photo = Photo.findById(pid)
        if not photo:
            abort(404, message=gettext("NOT_FOUND"))

        if photo.isOwner(user.id):
            abort(403, message=gettext("PERMISSION_DENIE"))

        # Commit query and write to db
        db.session.delete(photo)
        db.session.commit()
        return {"id": pid}
Example #5
0
def error_404(e):
	g.lang_code = get_locale()
	return render_template('error.html',
		page={'title' : 'Page not found'},
		title=gettext('Page not found (404)'),
		message=gettext('The page you are looking for does not exist. Maybe you made a mistake while typing the URL')
	), 404
Example #6
0
def error_500(e):
	g.lang_code = get_locale()
	return render_template('error.html',
		page={'title' : 'Server Error'},
		title=gettext('Something went wrong (500)'),
		message=gettext('An error happened while processing your request. This should not happen, we are very sorry. Please tell us about the this problem by sending a mail to [email protected] and include the URL you were trying to access.')
	), 500
Example #7
0
    def add_contacts(self):
        if request.method == 'POST':
            if not request.form.get('conference') or not request.form.get(
                'profile'):
                    flash(
                        'You must select Conference and Profile')
                    if current_user.has_role('admin'):
                        return redirect(url_for('contact_admin.index_view'))
                    else:
                        return redirect(url_for('contact_user.index_view'))

            conference = Conference.query.filter_by(
                id=request.form['conference']).first_or_404()

            profile = ParticipantProfile.query.filter_by(
                id=request.form['profile']).first_or_404()

            contacts = Contact.query.filter(
                    Contact.id.in_(request.form['ids'].split(',')))

            for c in contacts:
                if Participant.query.filter_by(phone=c.phone,
                                               conference=conference).first():
                    flash(gettext(
                        '%(contact)s is already there.', contact=c))
                    continue
                p = Participant(phone=c.phone, name=c.name, user=current_user,
                                profile=profile, conference=conference)
                flash(gettext(
                    '%(contact)s added.', contact=c))

                db.session.add(p)
            db.session.commit()

        return redirect(url_for('.edit_view', id=conference.id))
Example #8
0
 def index(self):
     form = CredentialForm(request.form)
     ttl = get_option("credential_code.ttl",
             20,
     gettext("Durée de validité en minutes d'un code"
     " d'authentification."))
     if request.method == 'POST' and form.validate() and form.code.data :
         try:
             user = User.objects(credential_code =
                     form.code.data.strip()).get()
             delta = datetime.now() - user.credential_code_date
             if delta < timedelta(minutes = ttl) :
                 login.login_user(user)
                 return redirect(url_for('account.index'))
             else:
                 flash(gettext("Le code saisi n'est plus valide, vous"
                     " devez recommencer la procédure."), "error")
                 return redirect("/")
         except labresult.model.db.DoesNotExist:
             labresult.app.logger.warning("Invalid credential code")
             flash(gettext("Le code saisi n'est pas valide"), 'error')
         except :
             labresult.app.logger.error(traceback.format_exc())
             flash(gettext("Le système à rencontrer un problème, veuillez"
                 " recommencer la procédure."), 'error')
             return redirect("/")
     return self.render("credential/form.html", form=form, ttl=ttl)
Example #9
0
 def validate_nickname(self, field):
     # todo
 #        # 昵称不允许重复
 #        if not UserService.count_by_nickname(field.data):
 #            raise ValidationError, gettext("This nickname is taken")
     if not WordReservedService.word_allowed(field.data):
         raise ValidationError, gettext("This nickname is taken")
Example #10
0
 def inaccessible_callback(self, name, **kwargs):
     if not login.current_user.is_authenticated:
         flash(gettext("Vous devez vous identifier pour accéder à la ressource"
             " demandée."), "error")
     else:
         flash(gettext("Vous n'avez pas les droits nécessaires pour accéder à"
            " la page demandée."), "error")
     return redirect(url_for("admin.index"), 307)
Example #11
0
    def test_as_default(self):
        app = flask.Flask(__name__)
        b = babel.Babel(app, default_locale='de_DE')
        domain = babel.Domain(domain='test')

        with app.test_request_context():
            assert babel.gettext('first') == 'first'
            domain.as_default()
            assert babel.gettext('first') == 'erste'
Example #12
0
 def func(value):
     try:
         id = int(value)
         instance = cls.query.filter(getattr(cls, field) == id).first()
         if instance is not None:
             return True, instance
         return False, gettext("VALIDATION_INVALID_MODEL %(model)s %(id)s", model=str(cls), id=value)
     except ValueError:
         return False, gettext("VALIDATION_INVALID_INTEGER %(type)s", type=type(value))
Example #13
0
    def test_as_default(self):
        app = flask.Flask(__name__)
        b = babel.Babel(app, default_locale='de_DE')
        domain = babel.Domain(domain='test')

        with app.test_request_context():
            assert babel.gettext('first') == 'first'
            domain.as_default()
            assert babel.gettext('first') == 'erste'
Example #14
0
def password_check(form, field):
    if not field.data:
        return
    min = get_option('password_min_lenth', 8,
    gettext('Nombre de caractères minimum pour un mot de passe'))
    if len(field.data) < min:
        msg = gettext('Le mot de passe doit faire plus de %s caractères')
        raise WTFValError(msg.format(min))
    if form.confirm.data != field.data :
        raise WTFValError(gettext('La confirmation du mot de passe ne'
        ' correspond pas'))
Example #15
0
def doAuth(*args, **kwargs):
    access_token = request.headers.get("X-Access-Token")
    device_id = request.headers.get("X-Device-Id")

    if not access_token or not device_id:
        abort(404, message=gettext("NOT_FOUND"))

    token = UserToken.findByTokenAndDevice(access_token, device_id)

    if not token or not token.user:
        abort(403, message=gettext("PERMISSION_DENIE"))
    return token.user
Example #16
0
def legend_formatter(view, context, model, name):
    """Formatter for legend columns for profiles"""
    glyph = '<span title="%s" class="glyphicon glyphicon-%s"></span> '
    legend = ''
    if isinstance(model, ParticipantProfile):
        if model.admin:
            legend += (glyph % (gettext('Admin'), 'text-color'))
        if model.marked:
            legend += (glyph % (gettext('Marked'), 'king'))
        if model.pin:
            legend += (glyph % (gettext('PIN is set'), 'lock'))
        if model.startmuted:
            legend += (glyph % (gettext('PIN is set'), 'volume-off'))
        if model.wait_marked:
            legend += (glyph % (gettext('Wait for marked user to join'),
                                '       glyphicon-log-in'))
        if model.end_marked:
            legend += (glyph % (gettext('End when marked user leaves'),
                                '       glyphicon-log-out'))

    elif isinstance(model, Conference):
        if model.is_public:
            legend += (glyph % (gettext('Guests (not from participant '
                                        'list) can join'), 'plus-sign'))
        else:
            legend += (glyph % (gettext('Only for participants '
                                        'specified'), 'ban-circle'))
    return Markup(legend)
Example #17
0
def legend_formatter(view, context, model, name):
        """Formatter for legend columns for profiles"""
        glyph = '<span title="%s" class="glyphicon glyphicon-%s"></span> '
        legend = ''
        if isinstance(model, ParticipantProfile):
            if model.admin:
                legend += (glyph % (gettext('Admin'), 'text-color'))
            if model.marked:
                legend += (glyph % (gettext('Marked'), 'king'))
            if model.pin:
                legend += (glyph % (gettext('PIN is set'), 'lock'))
            if model.startmuted:
                legend += (glyph % (gettext('PIN is set'), 'volume-off'))
            if model.wait_marked:
                legend += (glyph % (gettext('Wait for marked user to join'),
                                    '       glyphicon-log-in'))
            if model.end_marked:
                legend += (glyph % (gettext('End when marked user leaves'),
                                    '       glyphicon-log-out'))

        elif isinstance(model, Conference):
            if model.is_public:
                legend += (glyph % (gettext('Guests (not from participant '
                                            'list) can join'), 'plus-sign'))
            else:
                legend += (glyph % (gettext('Only for participants '
                                            'specified'), 'ban-circle'))
        return Markup(legend)
Example #18
0
 def kick(self, conf_id, channel=None):
     conf = Conference.query.filter_by(id=conf_id).first_or_404()
     if channel:
         confbridge_kick(conf.number, channel)
         msg = gettext('Channel %(channel)s is kicked.', channel=channel)
         flash(msg)
         conf.log(msg)
     else:
         confbridge_kick_all(conf.number)
         msg = gettext('All participants have been kicked from the conference.')
         conf.log(msg)
         flash(msg)
     sse_notify(conf.id, 'update_participants')
     time.sleep(1)
     return redirect(url_for('.details_view', id=conf.id))
Example #19
0
    def __init__(self):
        # Validation rules for params
        self.postParser = reqparse.RequestParser()

        self.postParser.add_argument(
            "username", required=True, type=unicode, location="form",
            help=gettext("%(field)s VALIDATION_REQUIRED_ERROR", field="username"))

        self.postParser.add_argument(
            "password", required=True, type=unicode, location="form",
            help=gettext("%(field)s VALIDATION_REQUIRED_ERROR", field="password"))

        self.postParser.add_argument(
            "device_id", required=True, type=unicode, location="form",
            help=gettext("%(field)s VALIDATION_REQUIRED_ERROR", field="device_id"))
Example #20
0
 def kick(self, conf_id, channel=None):
     conf = Conference.query.filter_by(id=conf_id).first_or_404()
     if channel:
         confbridge_kick(conf.number, channel)
         msg = gettext('Channel %(channel)s is kicked.', channel=channel)
         flash(msg)
         conf.log(msg)
     else:
         confbridge_kick_all(conf.number)
         msg = gettext(
             'All participants have been kicked from the conference.')
         conf.log(msg)
         flash(msg)
     sse_notify(conf.id, 'update_participants')
     time.sleep(1)
     return redirect(url_for('.details_view', id=conf.id))
Example #21
0
def datetime(value):
    try:
        dt.datetime.strptime(value, "%Y-%m-%dT%H:%M:%S+0000")
        result = parse_time(value)
        return True, result
    except ValueError:
        return False, gettext("VALIDATION_INVALID_DATETIME I.E: 2014-12-11T08:23:01+0000")
Example #22
0
def is_participant_uniq(form, field):
    p = Participant.query.filter_by(conference=form.data['conference'],
                                    phone=form.data['phone']).first()
    if p:
        raise ValidationError(
            gettext('Participant with phone number %(num)s already there.',
                    num=form.data['phone']))
Example #23
0
 def __call__(self, field, **kwargs):
     kwargs.setdefault('id', field.id)
     likp = len(self.inner_kwarg_prefix)
     inner_kwargs = {fix_param_name(k[likp:]):v for k,v in kwargs.iteritems() if k.startswith(self.inner_kwarg_prefix)}
     outer_kwargs = {fix_param_name(k):v for k,v in kwargs.iteritems() if not k.startswith(self.inner_kwarg_prefix)}
     return HTMLString(u'<%s %s data-status_unknown="%s" data-status_loading="%s" data-status_processing="%s">%s</%s>' % (
         self.html_tag,
         html_params(**outer_kwargs),
         gettext("admin_status_unknown"),
         gettext("admin_status_loading"),
         gettext("admin_status_processing"),
         u''.join(u'<li><span>%s%s</span></li>' % (
             subfield(**inner_kwargs),
             subfield.label
             ) for subfield in field),
         self.html_tag))
Example #24
0
 def record_stop(self, conf_id):
     conf = Conference.query.get_or_404(conf_id)
     confbridge_record_stop(conf.number)
     msg = gettext('The conference recording has been stopped.')
     flash(msg)
     conf.log(msg)
     return redirect(url_for('.details_view', id=conf_id))
Example #25
0
 def invite_participants(self, conf_id):
     conf = Conference.query.get_or_404(conf_id)
     conf.invite_participants()
     flash(gettext(
             'All the participants where invited to the conference'))
     time.sleep(1)
     return redirect(url_for('.details_view', id=conf.id))
Example #26
0
def frmt_doc_type(v,c,m,n):
    """
    Callback function for BaseModelView column_formatters technique.
    Create a link to edit user and set a return url.
    :param v: current administrative view
    :param c: instance of jinja2.runtime.Context
    :param m: model instance
    :param n: property name
    """
    mapping = {}
    if "User.Administrator" in login.current_user._cls :
        mapping = dict(
            CR_DOCTOR = 'Compte rendu médecin',
            CR_PATIENT = 'Compte rendu patient',
            CR_CORRES = 'Compte rendu correspondant',
            )
        if m.signed :
            icon = ' <span class="itemic {}" title="{}"></span>'.format(
                    'flaticon-verified9',
                    gettext("Document signé numériquement")
                    )
            mapping = { k : Markup(v + icon) for k, v in mapping.items()}
    else :
        mapping = dict(
            CR_DOCTOR = "Compte rendu d'analyse",
            CR_PATIENT = "Compte rendu d'analyse",
            CR_CORRES = "Compte rendu d'analyse",
            )
    return mapping.get(m.doc_type, m.doc_type)
Example #27
0
 def record_stop(self, conf_id):
     conf = Conference.query.get_or_404(conf_id)
     confbridge_record_stop(conf.number)
     msg = gettext('The conference recording has been stopped.')
     flash(msg)
     conf.log(msg)
     return redirect(url_for('.details_view', id=conf_id))
Example #28
0
def collection(id):
	coll = repo.collections[id]
	names = []
	for name, in repo.iternames(filter_collection=coll):
		names.append({
			'name' : name.name.get_nice(),
			'id' : name.get_id(),
			'description' : name.description
		})
	standards = []
	for std, in repo.iterstandards(filter_collection=coll):
		standards.append({
			'standard' : std.standard.get_nice(),
			'id' : std.get_id(),
			'description' : std.description
		})
	page = {"title" : "Part list"}

	#Properties
	props = []
	props.append(format_author_prop(coll.author_names))
	props.append((gettext('License'),html.a(coll.license_name,href=coll.license_url)))
	props.append(('ID',coll.id))
	return render_template("parts/collection.html",
		page=page,
		coll=coll,
		standards=standards,
		names=names,
		props=html.properties(props)
	)
Example #29
0
def configure_logging(app):
    context_provider = ContextualFilter()
    app.logger.setLevel(app.config['LOG_LEVEL'])
    app.logger.addFilter(context_provider)
    del app.logger.handlers[:]
    handler = logging.StreamHandler()
    log_format =  "%(asctime)s %(ip)s %(levelname)s %(user_name)s(%(user_id)s) %(method)s %(url)s %(reqargs)s %(message)s"
    formatter = logging.Formatter(log_format)
    handler.setFormatter(formatter)
    app.logger.addHandler(handler)
    #smtp option
    smtp_login = get_option('smtp_login', '*****@*****.**',
            visible=False)
    smtp_password = get_option('smtp_password','pacman9732', visible=False)
    smtp_port = get_option('smtp_port', 587)
    smtp_server = get_option('smtp_server', 'mail.gandi.net',
            gettext("Serveur SMTP"), visible=False)
    smtp_error_sender = get_option('smtp_error_sender', '*****@*****.**',
            gettext("Email envoyeur pour les erreurs."))
    smtp_error_recipients = get_option("smtp_error_recipients",
    "['*****@*****.**']",
            gettext("Emails destinataires pour l'envoi des erreurs du"
            " serveur"))
    if not app.debug:
        logging.getLogger('werkzeug').setLevel(logging.ERROR)
        # Use a multi-line format for this logger, for easier scanning
        mail_formatter = logging.Formatter("""
Time: %(asctime)s
IP: %(ip)s
User: %(user_name)s (%(user_id)s)
Level: %(levelname)s
Method: %(method)s
Path: %(url)s
Args: %(reqargs)s
Message: %(message)s
---------------------""")

        mail_handler = SMTPHandler_unicode((smtp_server, smtp_port),
                                   smtp_error_sender,
                                   smtp_error_recipients,
                                   gettext('Anomalie serveur LabResult'),
                                   (smtp_login, smtp_password),
                                   secure=(),
                                   )
        mail_handler.setLevel(logging.ERROR)
        mail_handler.setFormatter(mail_formatter)
        app.logger.addHandler(mail_handler)
Example #30
0
def unmute_request(conf_number, callerid):
    if not asterisk_is_authenticated():
        return 'NOTAUTH'
    message = gettext('Unmute request from number %(num)s.', num=callerid)
    conference = Conference.query.filter_by(number=conf_number).first_or_404()
    conference.log(message)
    sse_notify(conference.id, 'unmute_request', callerid)
    return 'OK'
Example #31
0
def is_participant_uniq(form, field):
    #
    p = Participant.query.filter_by(conference=form.data['conference'],
                                    phone=form.data['phone']).first()
    if p:
        raise ValidationError(
            gettext('Participant with phone number %(num)s already there.',
                    num=form.data['phone']))
Example #32
0
 def unmute(self, conf_id, channel=None):
     conf = Conference.query.get_or_404(conf_id)
     if channel:
         confbridge_unmute(conf.number, channel)
         msg = gettext('Participant %(channel)s unmuted.', channel=channel)
         flash(msg)
         conf.log(msg)
     else:
         # Mute all
         for p in confbridge_list_participants(conf.number):
             confbridge_unmute(conf.number, p['channel'])
         msg = gettext('Conference unmuted.')
         flash(msg)
         conf.log(msg)
     sse_notify(conf.id, 'update_participants')
     time.sleep(1)
     return redirect(url_for('.details_view', id=conf_id))
Example #33
0
def leave_conference(conf_number, callerid):
    if not asterisk_is_authenticated():
        return 'NOTAUTH'
    message = gettext('Number %(num)s has left the conference.', num=callerid)
    conference = Conference.query.filter_by(number=conf_number).first_or_404()
    conference.log(message)
    sse_notify(conference.id, 'update_participants')
    return 'OK'
Example #34
0
    def test_basics(self):
        app = flask.Flask(__name__)
        b = babel.Babel(app, default_locale='de_DE')

        with app.test_request_context():
            assert gettext(u'Hello %(name)s!', name='Peter') == 'Hallo Peter!'
            assert ngettext(u'%(num)s Apple', u'%(num)s Apples', 3) == u'3 Äpfel'
            assert ngettext(u'%(num)s Apple', u'%(num)s Apples', 1) == u'1 Apfel'
Example #35
0
def leave_conference(conf_number, callerid):
    if not asterisk_is_authenticated():
        return 'NOTAUTH'
    message = gettext('Number %(num)s has left the conference.', num=callerid)
    conference = Conference.query.filter_by(number=conf_number).first_or_404()
    conference.log(message)
    sse_notify(conference.id, 'update_participants')
    return 'OK'
Example #36
0
def unmute_request(conf_number, callerid):
    if not asterisk_is_authenticated():
        return 'NOTAUTH'
    message = gettext('Unmute request from number %(num)s.', num=callerid)
    conference = Conference.query.filter_by(number=conf_number).first_or_404()
    conference.log(message)
    sse_notify(conference.id, 'unmute_request', callerid)
    return 'OK'
Example #37
0
def dial_status(conf_number, callerid, status):
    if not asterisk_is_authenticated():
        return 'NOTAUTH'
    message = gettext('Could not invite number %(num)s: %(status)s', num=callerid,
                status=status.capitalize())
    conference = Conference.query.filter_by(number=conf_number).first_or_404()
    conference.log(message)
    return 'OK'
Example #38
0
 def unmute(self, conf_id, channel=None):
     conf = Conference.query.get_or_404(conf_id)
     if channel:
         confbridge_unmute(conf.number, channel)
         msg = gettext('Participant %(channel)s unmuted.', channel=channel)
         flash(msg)
         conf.log(msg)
     else:
         # Mute all
         for p in confbridge_list_participants(conf.number):
             confbridge_unmute(conf.number, p['channel'])
         msg = gettext('Conference unmuted.')
         flash(msg)
         conf.log(msg)
     sse_notify(conf.id, 'update_participants')
     time.sleep(1)
     return redirect(url_for('.details_view', id=conf_id))
Example #39
0
def fruits_json(number=1):
    # duplicating the strings already set in the first view, to test how babel handles duplication

    # NOTE: this is a comment the translators will see; directing them to not translate the replacement string
    singular = gettext(u'Here is a basic string to translate')
    # however comments without the 'NOTE:' comment tag will not be processed into the POT file

    # notice that singular strings that use gettext() are aliased to _() for brevity
    singular_replacement = _(u'Here is a string that has a %(replacement)s string', replacement=u'replacement')

    # when we have a plural, we have to use ngettext()
    num_pears = random.randint(1, 10)
    plural = ngettext(u'Here is %(num)s pear', u'Here are %(num)s pears', num=num_pears)

    # we can also send a context to the translator to give them more info on what they are translating
    singular_context = pgettext(u'This text is part of a button used for exiting a pop-up', u'Cancel')

    plural_context = npgettext(u'This is part of a spinner on a fruit wheel',
                               u'%(num)s orange',
                               u'%(num)s oranges',
                               num=(number or 1))

    data = {
           'fruits': [
               {
                   'fruit': _(u'lime'),
                   'type': _(u'continental')
               },
               {
                   'fruit': _(u'starfruit'),
                   'type': _(u'exotic')
               },
               {
                   'fruit': _(u'strawberry'),
                   'type': _(u'native')
               }
           ],
            'list': [
                {
                    'string': singular
                },
                {
                    'string': singular_replacement
                },
                {
                    'string': plural
                },
                {
                    'string': singular_context
                },
                {
                    'string': plural_context
                }
            ]
       }

    # JSON Response
    return jsonify(data)
Example #40
0
 def unlock(self, conf_id):
     conf = Conference.query.get_or_404(conf_id)
     confbridge_unlock(conf.number)
     msg = gettext('The conference has been unlocked.')
     flash(msg)
     conf.log(msg)
     sse_notify(conf.id, 'update_participants')
     time.sleep(1)
     return redirect(url_for('.details_view', id=conf_id))
Example #41
0
 def unlock(self, conf_id):
     conf = Conference.query.get_or_404(conf_id)
     confbridge_unlock(conf.number)
     msg = gettext('The conference has been unlocked.')
     flash(msg)
     conf.log(msg)
     sse_notify(conf.id, 'update_participants')
     time.sleep(1)
     return redirect(url_for('.details_view', id=conf_id))
Example #42
0
def dial_status(conf_number, callerid, status):
    if not asterisk_is_authenticated():
        return 'NOTAUTH'
    message = gettext('Could not invite number %(num)s: %(status)s',
                      num=callerid,
                      status=status.capitalize())
    conference = Conference.query.filter_by(number=conf_number).first_or_404()
    conference.log(message)
    return 'OK'
Example #43
0
 def _update_access(self, access, rules, fails):
     """
     :param access: HealthWorkerAccess
     :param rules: rules applied
     :param fails: rules who failed
     """
     access.read = True
     role = access.role if hasattr(access, "role") else "patient"
     if not rules :
         access.comment = gettext("No rules for %s").format(gettext(role))
         access.read = False
         return
     for rule in fails:
             access.read = False
             if not access.comment :
                 access.comment = rule.msg_error
             else :
                 access.comment += '\n' + rule.msg_error
Example #44
0
    def test_basics(self):
        app = flask.Flask(__name__)
        b = babel.Babel(app, default_locale='de_DE')

        with app.test_request_context():
            assert gettext(u'Hello %(name)s!', name='Peter') == 'Hallo Peter!'
            assert ngettext(u'%(num)s Apple', u'%(num)s Apples',
                            3) == u'3 Äpfel'
            assert ngettext(u'%(num)s Apple', u'%(num)s Apples',
                            1) == u'1 Apfel'
Example #45
0
def fruits_json(number=1):
    # duplicating the strings already set in the first view, to test how babel handles duplication

    # NOTE: this is a comment the translators will see; directing them to not translate the replacement string
    singular = gettext(u'Here is a basic string to translate')
    # however comments without the 'NOTE:' comment tag will not be processed into the POT file

    # notice that singular strings that use gettext() are aliased to _() for brevity
    singular_replacement = _(
        u'Here is a string that has a %(replacement)s string',
        replacement=u'replacement')

    # when we have a plural, we have to use ngettext()
    num_pears = random.randint(1, 10)
    plural = ngettext(u'Here is %(num)s pear',
                      u'Here are %(num)s pears',
                      num=num_pears)

    # we can also send a context to the translator to give them more info on what they are translating
    singular_context = pgettext(
        u'This text is part of a button used for exiting a pop-up', u'Cancel')

    plural_context = npgettext(u'This is part of a spinner on a fruit wheel',
                               u'%(num)s orange',
                               u'%(num)s oranges',
                               num=(number or 1))

    data = {
        'fruits': [{
            'fruit': _(u'lime'),
            'type': _(u'continental')
        }, {
            'fruit': _(u'starfruit'),
            'type': _(u'exotic')
        }, {
            'fruit': _(u'strawberry'),
            'type': _(u'native')
        }],
        'list': [{
            'string': singular
        }, {
            'string': singular_replacement
        }, {
            'string': plural
        }, {
            'string': singular_context
        }, {
            'string': plural_context
        }]
    }

    # JSON Response
    return jsonify(data)
Example #46
0
 def install(self):
     flask_cron = CronTab(user=True)
     flask_cron.remove_all()
     for conference_schedule in ConferenceSchedule.query.all():
         job = flask_cron.new(command=join(
             dirname(__file__),
             'cron_job.sh %s' % conference_schedule.conference.number),
                              comment='%s' % conference_schedule.conference)
         job.setall(conference_schedule.entry)
     flask_cron.write_to_user()
     flash(gettext('Crontab has been installed successfully.'))
     return redirect(url_for('.index_view'))
Example #47
0
def is_crontab_valid(form, field):
    item = CronItem(field.data + ' /bin/echo # Just a test', cron=CronTab())
    # May be I will refactor to this:
    #item = cron.new(command='/bin/echo', comment='Aaaaa')
    #item.hour.every(4)
    #item.minute.during(5,50).every(2)
    #item.day.on(4,5,6)
    #item.dow.on(1)
    #item.month.during(1,2)
    if not item.is_valid():
        raise ValidationError(gettext('%(job)s is not a correct crontab entry.',
                              job=field.data))
Example #48
0
    def test_multiple_apps(self):
        app1 = flask.Flask(__name__)
        b1 = babel.Babel(app1, default_locale='de_DE')

        app2 = flask.Flask(__name__)
        b2 = babel.Babel(app2, default_locale='de_DE')

        with app1.test_request_context():
            assert babel.gettext('Yes') == 'Ja'

            assert 'de_DE' in b1._default_domain.cache

        with app2.test_request_context():
            assert 'de_DE' not in b2._default_domain.cache
Example #49
0
 def invite_guest(self, conf_id):
     conf = Conference.query.get_or_404(conf_id)
     phone = request.args.get('phone', None)
     if phone and phone.isdigit():
         originate(conf.number,
                   phone,
                   bridge_options=conf.conference_profile.
                   get_confbridge_options(),
                   user_options=conf.public_participant_profile.
                   get_confbridge_options())
         flash(
             gettext('Number %(phone)s is called for conference.',
                     phone=phone))
     time.sleep(1)
     return redirect(url_for('.details_view', id=conf_id))
Example #50
0
    def validate_username(self, field):
        # todo
        # 用户名不允许重复
        if UserService.count_by_username(field.data) > 0:
            raise ValidationError, gettext("This username is taken")

        # 不能有敏感词、保留词
        if not WordReservedService.word_allowed(field.data):
            raise ValidationError, gettext("This username is taken")

        if not WordForbiddenService.word_allowed(field.data):
            raise ValidationError, gettext("This username is taken")
Example #51
0
def check(conf_number, callerid):
    if not asterisk_is_authenticated():
        return 'NOTAUTH'
    conf = Conference.query.filter_by(number=conf_number).first()

    if not conf:
        return 'NOCONF'

    elif callerid not in [k.phone
                          for k in conf.participants] and not conf.is_public:
        message = gettext(
            'Attempt to enter non-public conference from %(phone)s.',
            phone=callerid)
        conf.log(message)
        return 'NOTPUBLIC'

    else:
        return 'OK'
Example #52
0
    def import_contacts(self):
        form = ContactImportForm()
        if request.method == 'GET':
            return self.render('contact_import.html', form=form)

        else:
            form = ContactImportForm()
            if form.validate_on_submit():
                data = form.filename.data.readlines()
                imported = 0
                for line in data:
                    line = line.split(',')
                    c = Contact()
                    c.phone = line[0]
                    c.name = line[1].decode('utf-8')
                    c.user = current_user
                    db.session.add(c)
                    imported += 1
                db.session.commit()
                flash(gettext('Imported %(num)s contacts.', num=imported))
                return redirect(url_for('.index_view'))

            else:
                return self.render('contact_import.html', form=form)
Example #53
0
def index():
    page = {"title": gettext("Home")}

    return render_template("home.html",
                           page=page,
                           stats=stats.get_statistics())
Example #54
0
 def test_non_initialized(self):
     app = flask.Flask(__name__)
     with app.test_request_context():
         assert babel.gettext('first') == 'first'
Example #55
0
def is_number(form, field):
    if field.data and not field.data.isdigit():
        raise ValidationError(gettext('Must be a number!'))
Example #56
0
 def validate_password_old(self, field):
     # 验证旧密码是否正确
     if not UserService.check_pwd_by_id(int(self.id.data), field.data):
         raise ValidationError, gettext("This old password is error")
Example #57
0
def fruits(number=1):
    # some server side data (analogous to title strings in card_generators)

    # NOTE: this is a comment the translators will see; directing them to not translate the replacement string
    singular = gettext(u'Here is a basic string to translate')
    # however comments without the 'NOTE:' comment tag will not be processed into the POT file

    # notice that singular strings that use gettext() are aliased to _() for brevity
    singular_replacement = _(
        u'Here is a string that has a %(replacement)s string',
        replacement=u'replacement')

    # when we have a plural, we have to use ngettext()
    num_pears = random.randint(1, 10)
    plural = ngettext(u'Here is %(num)s pear',
                      u'Here are %(num)s pears',
                      num=num_pears)

    # we can also send a context to the translator to give them more info on what they are translating
    singular_context = pgettext(
        u'This text is part of a button used for exiting a pop-up', u'Cancel')

    plural_context = npgettext(u'This is part of a spinner on a fruit wheel',
                               u'%(num)s orange',
                               u'%(num)s oranges',
                               num=(number or 1))

    # NOTE: part a
    comment_test = _(u'first part')

    # NOTE: part b
    comment_test_2 = _(u'second part')

    context_test = pgettext(u'One', u'first part')
    context_test2 = pgettext(u'Two', u'second part')

    data = {
        'fruits': [{
            'fruit': _(u'lime'),
            'type': _(u'continental')
        }, {
            'fruit': _(u'starfruit'),
            'type': _(u'exotic')
        }, {
            'fruit': _(u'strawberry'),
            'type': _(u'native')
        }],
        'list': [{
            'string': singular
        }, {
            'string': singular_replacement
        }, {
            'string': plural
        }, {
            'string': singular_context
        }, {
            'string': plural_context
        }]
    }

    return render_template('fruits.html', number=number, data=data)