示例#1
0
def natural_join(lst):
    l = len(lst);
    if l <= 2:
        return lazy_gettext(' and ').join(lst)
    elif l > 2:
        first =  ', '.join(lst[0:-1])
        return "%s %s %s" % (first, lazy_gettext('and'), lst[-1])
示例#2
0
文件: views.py 项目: adesst/hendpos
def transaction_view(id=None):
    if id == None:
        flash(lazy_gettext('Error: No user ID specified, redirecting to Transaction List'))
        return redirect(url_for('transaction_list'))
    else:
        form = db_session.query(Balance, User).filter(Balance.user_id==User.id, Balance.id == id).first()
        if form:
            return render_template('default/transaction_view.html', form=form)
        else:
            flash(lazy_gettext('Error: Transaction %s is not exists' % id))
            return redirect(url_for('transaction_list'))
示例#3
0
文件: forms.py 项目: bzero/JARR
    def validate(self):
        if not super(RecoverPasswordForm, self).validate():
            return False

        user = User.query.filter(User.email == self.email.data).first()
        if user and user.activation_key == "":
            return True
        elif user and user.activation_key != "":
            flash(lazy_gettext('Account not confirmed.'), 'danger')
            return False
        else:
            flash(lazy_gettext('Invalid email.'), 'danger')
            return False
示例#4
0
文件: forms.py 项目: bzero/JARR
 def validate(self):
     validated = super(ProfileForm, self).validate()
     if self.password.data != self.password_conf.data:
         message = lazy_gettext("Passwords aren't the same.")
         self.password.errors.append(message)
         self.password_conf.errors.append(message)
         validated = False
     if self.nickname.data != User.make_valid_nickname(self.nickname.data):
         self.nickname.errors.append(lazy_gettext('This nickname has '
                 'invalid characters. Please use letters, numbers, dots and'
                 ' underscores only.'))
         validated = False
     return validated
示例#5
0
class BulkTaskEpiCollectPlusImportForm(Form):
    form_name = TextField(label=None, widget=HiddenInput(), default='epicollect')
    msg_required = lazy_gettext("You must provide an EpiCollect Plus "
                                "project name")
    msg_form_required = lazy_gettext("You must provide a Form name "
                                     "for the project")
    epicollect_project = TextField(lazy_gettext('Project Name'),
                                   [validators.Required(message=msg_required)])
    epicollect_form = TextField(lazy_gettext('Form name'),
                                [validators.Required(message=msg_required)])

    def get_import_data(self):
        return {'type': 'epicollect',
                'epicollect_project': self.epicollect_project.data,
                'epicollect_form': self.epicollect_form.data}
示例#6
0
class BulkTaskTwitterImportForm(Form):
    form_name = TextField(label=None, widget=HiddenInput(), default='twitter')
    msg_required = lazy_gettext("You must provide some source for the tweets")
    source = TextField(lazy_gettext('Source'),
                       [validators.Required(message=msg_required)])
    max_tweets = IntegerField(lazy_gettext('Number of tweets'))
    user_credentials = TextField(label=None)

    def get_import_data(self):
        return {
            'type': 'twitter',
            'source': self.source.data,
            'max_tweets': self.max_tweets.data,
            'user_credentials': self.user_credentials.data,
        }
示例#7
0
文件: views.py 项目: adesst/hendpos
def transaction_pre_add(txtype = None):
    if txtype == None:
        flash(lazy_gettext('Error: No user ID specified, redirecting to frontpage'))
        return redirect(url_for('index'))
    else:
        pass
    if txtype == '1':
        str_txtype = lazy_gettext('TopUp')
    elif txtype == '11':
        str_txtype = lazy_gettext('Sell')
    elif txtype == '2':
        str_txtype = lazy_gettext('Attendance')
    else:
        str_txtype = lazy_gettext('Unknown')
    return render_template('default/transaction_pre_add.html', txtype=txtype, str_txtype=str_txtype)
示例#8
0
class ExtendedRegisterForm(RegisterForm):
    all_locales = [('en', 'English')]
    for x in babel.list_translations():
        all_locales.append((x.language, x.display_name))

    email = StringField(lazy_gettext('E-Mail'),
                        validators=[DataRequired(), Email()])
    password = PasswordField(
        lazy_gettext('Password'),
        validators=[DataRequired(),
                    EqualTo("password_confirm")])
    password_confirm = PasswordField(
        lazy_gettext('Retype password'),
        validators=[DataRequired(), EqualTo("password")])
    locale = SelectField(lazy_gettext('Language'), choices=all_locales)
    submit = None
示例#9
0
    def append_language_names_i18n(s):
        from flask import g, current_app
        from flask.ext.babel import lazy_gettext
        NAMES = current_app.config.NAMES

        _n = NAMES.get(s, NAMES.get(g.orig_from, s))
        return lazy_gettext(_n)
示例#10
0
文件: kant.py 项目: Bytespeicher/KANT
def save_admin():
    if not session.get('logged_in'):
        abort(401)

    db = get_db()
    password = pwd_context.encrypt(request.form['password'])

    if 'id' in request.form.keys():
        if request.form['password'] == '******':
            db.execute('UPDATE adminss SET name = ?, mail = ?, password = ? WHERE id = ?',
                       [request.form['name'], request.form['mail'],
                        password, request.form['id']])
        else:
            db.execute('UPDATE users SET name = ?, mail = ? WHERE id = ?',
                       [request.form['name'], request.form['mail'],
                        request.form['id']])
    else:
        db.execute('INSERT INTO admins (name, mail, password) VALUES (?, ?, ?)',
                   [request.form['name'], request.form['mail'],
                    password])

    db.commit()

    flash(lazy_gettext('Changes to the admin where saved successfully!'))
    return redirect(url_for('show_admins'))
示例#11
0
class AvatarUploadForm(Form):
    id = IntegerField(label=None, widget=HiddenInput())
    avatar = FileField(lazy_gettext('Avatar'), validators=[FileRequired()])
    x1 = IntegerField(label=None, widget=HiddenInput(), default=0)
    y1 = IntegerField(label=None, widget=HiddenInput(), default=0)
    x2 = IntegerField(label=None, widget=HiddenInput(), default=0)
    y2 = IntegerField(label=None, widget=HiddenInput(), default=0)
示例#12
0
class Create_quiz(Form):
    question_text = TextAreaField(
        'Question Text',
        [validators.Required("Field Required")])  # Input for question text
    file_field = FileField(lazy_gettext('Avatar'))
    oA = StringField(
        'Option A',
        [validators.Required("Field Required")])  # Input for option A
    oB = StringField(
        'Option B',
        [validators.Required("Field Required")])  # Input for option B
    oC = StringField(
        'Option C',
        [validators.Required("Field Required")])  # Input for option C
    oD = StringField(
        'Option D',
        [validators.Required("Field Required")])  # Input for option D
    #file_path=StringField('file_path',[validators.Required("Field Required")])
    correct_answer = RadioField('Correct Answer',
                                choices=[
                                    ('A', 'A'), ('B', 'B'), ('C', 'C'),
                                    ('D', 'D')
                                ])  # Radio Button to select the correct answer
    category = StringField(
        'Category',
        [validators.Required("Field Required")])  # Input for question category
示例#13
0
 def __init__(self, session, model, field, message=None):
     self.session = session
     self.model = model
     self.field = field
     if not message:
         message = lazy_gettext(u'This item already exists')
     self.message = message
示例#14
0
class Amortizement(Spec):
    key = lazy_gettext(u"Amortizement")

    def __init__(self, value=30, min=2, max=49, show=False):
        key = self.key
        for k, v in vars().items():
            if v != self: setattr(self, k, v)
示例#15
0
文件: login.py 项目: BlueNexus/evesrp
def login():
    """Presents the login form and processes responses from that form.

    When a POST request is recieved, this function passes control to the
    appropriate :py:meth:`login <evesrp.auth.AuthMethod.login>` method.
    """
    # forms is a list of tuples. The tuples are
    # (AuthMethod instance, AuthForm instance)
    forms = []
    for auth_method in current_app.auth_methods:
        prefix = auth_method.safe_name
        form = auth_method.form()
        forms.append((auth_method, form(prefix=prefix)))
    if request.method == 'POST':
        # Find the form that was submitted. The unique prefix for each form
        # means only one form.submit is going to be valid.
        for auth_tuple in forms:
            if auth_tuple[1].submit.data:
                auth_method, form = auth_tuple
                break
        else:
            abort(400)
        if form.validate():
            return auth_method.login(form)
    return render_template('login.html', forms=forms,
            title=lazy_gettext(u'Log In'))
示例#16
0
    def __init__(self, message=None):
        if not message:
            self.message = lazy_gettext(
                u'Only comma separated values are allowed, no spaces')

        else:  # pragma: no cover
            self.message = message
示例#17
0
文件: codelang.py 项目: lzz12/railgun
    def handle_upload(self, handid, hw, form):
        """Handle the uploaded form data submitted to the given homework
        in this programming language.

        :param handid: The submission uuid.
        :type handid: :class:`str`
        :param hw: The homework instance.
        :type hw: :class:`~railgun.common.hw.Homework`
        :param form: The upload form generated by :meth:`upload_form`
        :type form: Derived class of :class:`flask_wtf.Form`
        """
        # save handin into the database
        handin = self.make_db_record(handid, hw)

        # post the job to run queue
        try:
            self.do_handle_upload(handid, hw, form)
        except Exception:
            # if we cannot post to run queue, modify the handin status to error
            handin.state = 'Rejected'
            handin.result = lazy_gettext('Could not commit to run queue.')
            handin.partials = []
            db.session.commit()
            # re-raise this exception
            raise
示例#18
0
文件: forms.py 项目: makai281/pysymo
def flash_form_errors(form):
    for field, errors in form.errors.items():
        for error in errors:
            flash(
                lazy_gettext("Field '%(field)s' - %(errtext)s",
                             field=getattr(form, field).label.text,
                             errtext=error), 'warning')
示例#19
0
class Spec(UV):
    key = lazy_gettext("key")

    def __init__(self, value, min=0, max="Infinity", show=True):
        key = self.key
        for k, v in vars().items():
            if v != self: setattr(self, k, v)
示例#20
0
文件: util.py 项目: fiorda/pybossa
def check_password_strength(
        password, min_len=8, max_len=15,
        uppercase=True, lowercase=True,
        numeric=True, special=True, message=""):
    """Check password strength, return True if passed.
    Otherwise return False with exact failure message.
    """

    required_chars = []
    if uppercase:
        required_chars.append(r'[A-Z]')
    if lowercase:
        required_chars.append(r'[a-z]')
    if numeric:
        required_chars.append(r'[0-9]')
    if special:
        required_chars.append(r'[!@$%^&*#]')

    pwd_len = len(password)
    if pwd_len < min_len or pwd_len > max_len:
        message = lazy_gettext(
                    u'Password must be between {0} and {1} characters'
                    .format(min_len, max_len))
        return False, message

    valid = all(re.search(ch, password) for ch in required_chars)
    if not valid:
        return False, message
    else:
        return True, None
示例#21
0
class Init(Spec):
    key = lazy_gettext(u"Start date")

    def __init__(self, value=2014, min=2004, max=2030, show=False):
        key = self.key
        for k, v in vars().items():
            if v != self: setattr(self, k, v)
示例#22
0
文件: util.py 项目: solonifer/pybossa
def check_password_strength(password,
                            min_len=8,
                            max_len=15,
                            uppercase=True,
                            lowercase=True,
                            numeric=True,
                            special=True,
                            message=""):
    """Check password strength, return True if passed.
    Otherwise return False with exact failure message.
    """

    required_chars = []
    if uppercase:
        required_chars.append(r'[A-Z]')
    if lowercase:
        required_chars.append(r'[a-z]')
    if numeric:
        required_chars.append(r'[0-9]')
    if special:
        required_chars.append(r'[!@$%^&*#]')

    pwd_len = len(password)
    if pwd_len < min_len or pwd_len > max_len:
        message = lazy_gettext(
            u'Password must be between {0} and {1} characters'.format(
                min_len, max_len))
        return False, message

    valid = all(re.search(ch, password) for ch in required_chars)
    if not valid:
        return False, message
    else:
        return True, None
示例#23
0
文件: views.py 项目: adesst/hendpos
def user_view(id=None):
    if id == None:
        flash(lazy_gettext('Error: No user ID specified, redirecting to list'))
        return redirect(url_for('user_list'))
    else:
        try:
            user = User.query.filter_by(id=id).first()
            if user is None:
                raise ValueError(lazy_gettext('Error: User ID is not exists'))
            mutations = Balance.query.filter_by(user_id=id)
            return render_template('default/user_view.html', user=user, mutations=mutations)
        except Exception, e:
            message = "Error: %s %s" %(e, type(e))
            flash(message)
            logging.error('%s %s' %(traceback.print_exc(), message))
            return redirect(url_for('user_list'))
示例#24
0
文件: kant.py 项目: Bytespeicher/KANT
def save_key():
    if not session.get('logged_in'):
        abort(401)

    db = get_db()

    if 'id' in request.form.keys():
        key = {
            'id':   int(request.form['id']),
            'name': str(request.form['name']),
            'user': int(request.form['user'])
        }

        cur = db.execute('SELECT user, name FROM keys WHERE id = ?',
                         [request.form['id']])

        old = cur.fetchone()

        db.execute('INSERT INTO key_history (key, user_before, user_after, '+
                   'name_before, name_after, change_user) ' +
                   'VALUES (?, ?, ?, ?, ?, ?)',
                  [key['id'], old['user'], key['user'], old['name'], key['name'], 0])
        db.commit()

        db.execute('UPDATE keys SET name = ?, user = ? WHERE id = ?',
                   [key['name'], key['user'], key['id']])
        db.commit()
    else:
        db.execute('INSERT INTO keys (name, user, last_update) VALUES (?, ?, ?)',
                   [request.form['name'], request.form['user'],
                   datetime.datetime.now()])
        db.commit()

    flash(lazy_gettext('Changes to the user where saved successfully!'))
    return redirect(url_for('show_keys'))
示例#25
0
文件: admin.py 项目: korepwx/railgun
def runqueue_clear():
    """Stop the runner queue, set the score of all pending and running
    submissions to 0.0, and the state to `Rejected`.
    The visitor will be redirected to :func:`~railgun.website.admin.handins`
    after the operation takes place.

    :route: /admin/runqueue/clear/
    :method: GET
    """

    # We must not use flask.ext.babel.lazy_gettext, because we'll going to
    # store it in the database!
    from railgun.common.lazy_i18n import lazy_gettext

    try:
        runner_app.control.discard_all()
        print db.session.query(Handin) \
            .filter(Handin.state.in_(['Pending', 'Running'])).count()
        db.session.query(Handin) \
            .filter(Handin.state.in_(['Pending', 'Running'])) \
            .update({
                'state': 'Rejected',
                'result': lazy_gettext('Submission discarded by admin.'),
                'partials': [],
                'score': 0.0,
            }, synchronize_session=False)
        db.session.commit()
        flash(_('All pending submissions are cleared.'), 'success')
    except Exception:
        app.logger.exception('Could not discard the pending submissions.')
        flash(_('Could not discard the pending submissions.'), 'danger')
    return redirect(url_for('.handins'))
示例#26
0
 def __init__(self, session, model, field, message=None):
     self.session = session
     self.model = model
     self.field = field
     if not message:  # pragma: no cover
         message = lazy_gettext(u'This item already exists')
     self.message = message
示例#27
0
文件: admin.py 项目: korepwx/railgun
def runqueue_clear():
    """Stop the runner queue, set the score of all pending and running
    submissions to 0.0, and the state to `Rejected`.
    The visitor will be redirected to :func:`~railgun.website.admin.handins`
    after the operation takes place.

    :route: /admin/runqueue/clear/
    :method: GET
    """

    # We must not use flask.ext.babel.lazy_gettext, because we'll going to
    # store it in the database!
    from railgun.common.lazy_i18n import lazy_gettext

    try:
        runner_app.control.discard_all()
        print db.session.query(Handin) \
            .filter(Handin.state.in_(['Pending', 'Running'])).count()
        db.session.query(Handin) \
            .filter(Handin.state.in_(['Pending', 'Running'])) \
            .update({
                'state': 'Rejected',
                'result': lazy_gettext('Submission discarded by admin.'),
                'partials': [],
                'score': 0.0,
            }, synchronize_session=False)
        db.session.commit()
        flash(_('All pending submissions are cleared.'), 'success')
    except Exception:
        app.logger.exception('Could not discard the pending submissions.')
        flash(_('Could not discard the pending submissions.'), 'danger')
    return redirect(url_for('.handins'))
示例#28
0
 def __init__(self, session, model, field, message=None):
     self.session = session
     self.model = model
     self.field = field
     if not message:  # pragma: no cover
         message = lazy_gettext(u"This item already exists")
     self.message = message
示例#29
0
文件: forms.py 项目: ianthe/pybossa
class ProjectUpdateForm(ProjectForm):
    id = IntegerField(label=None, widget=HiddenInput())
    description = TextAreaField(lazy_gettext('Description'), [
        validators.Required(
            message=lazy_gettext("You must provide a description.")),
        validators.Length(max=255)
    ])
    long_description = TextAreaField(lazy_gettext('Long Description'))
    allow_anonymous_contributors = SelectField(
        lazy_gettext('Allow Anonymous Contributors'),
        choices=[('True', lazy_gettext('Yes')), ('False', lazy_gettext('No'))])
    category_id = SelectField(lazy_gettext('Category'), coerce=int)
    hidden = BooleanField(lazy_gettext('Hide?'))
    password = TextField(
        lazy_gettext('Password (leave blank for no password)'))
    webhook = TextField(lazy_gettext('Webhook'), [pb_validator.Webhook()])
示例#30
0
class HostingForm(Form):
    password = PasswordField(
        lazy_gettext("Passwort"),
        validators=[
            DataRequired(lazy_gettext("Kein Passwort eingegeben!")),
            PasswordComplexity(),
        ])
    confirm = PasswordField(
        lazy_gettext("Bestätigung"),
        validators=[
            DataRequired(
                lazy_gettext("Bestätigung des neuen Passworts fehlt!")),
            EqualTo(
                'password',
                message=lazy_gettext("Neue Passwörter stimmen nicht überein!"))
        ])
    action = HiddenField()
示例#31
0
def signup():
    form = SignupForm()
    if request.method == 'POST':
        if form.validate_on_submit() == False:
            flash(lazy_gettext(u'All fields are required'))
            return render_template('signup.html', form=form)
        else:
            startup = Company(**form.data)
            db.session.add(startup)
            try:
                db.session.commit()
            except IntegrityError:
                flash(lazy_gettext(u'This company email is already signed up'))
                return render_template('signup.html', form=form)
            return render_template('signup.html', form=form)
    elif request.method == 'GET':
        return render_template('signup.html', form=form)
示例#32
0
 def validate(self):
     validated = super(SignupForm, self).validate()
     if self.nickname.data != User.make_valid_nickname(self.nickname.data):
         self.nickname.errors.append(lazy_gettext(
                 'This nickname has invalid characters. '
                 'Please use letters, numbers, dots and underscores only.'))
         validated = False
     return validated
示例#33
0
文件: forms.py 项目: makai281/pysymo
class RegistrationForm(Form):
    # FIXME (IL) - 'username' - same field as in LoginForm. If registration fails username restored in both forms
    username = StringField(
        lazy_gettext('Username'),
        [validators.DataRequired(),
         validators.Length(min=3)])
    password = PasswordField(lazy_gettext('Password'), [
        validators.DataRequired(),
        validators.equal_to('confirm',
                            message=lazy_gettext('Passwords must match.')),
        validators.Length(min=6, max=20)
    ])
    confirm = PasswordField(lazy_gettext('Confirm password'),
                            [validators.DataRequired()])
    email = StringField(lazy_gettext('Email'),
                        [validators.DataRequired(),
                         validators.Length(min=4)])
示例#34
0
class PasswordModForm(Form):
    password = PasswordField(lazy_gettext("Password"), [
        validators.Required(lazy_gettext("Please enter a password.")),
        validators.Length(min=6, max=100)
    ])
    password_conf = PasswordField(
        lazy_gettext("Password confirmation"),
        [validators.Required(lazy_gettext("Confirm the password."))])

    submit = SubmitField(lazy_gettext("Save"))

    def validate(self):
        validated = super().validate()
        if self.password.data != self.password_conf.data:
            self.password_conf.errors.append("Passwords don't match")
            validated = False
        return validated
示例#35
0
 def __call__(self, form, field):
     try:
         if field.data:
             r = requests.get(field.data)
             if r.status_code != 200:
                 raise ValidationError(self.message)
     except requests.exceptions.ConnectionError:
         raise ValidationError(lazy_gettext(u"Connection error"))
示例#36
0
def unique_email_check(form, field):
    """
    Custom validator that checks if an given email is already used by someone
    """
    existing_email = User.query.filter_by(email=field.data).all()

    if existing_email:
        raise ValidationError(lazy_gettext('Someone already uses this email address.'))
示例#37
0
class ResetPasswordForm(Form):
    """Class for resetting user's password."""

    err_msg = lazy_gettext("Password cannot be empty")
    err_msg_2 = lazy_gettext("Passwords must match")
    if enable_strong_password:
        new_password = PasswordField(lazy_gettext('New Password'), [
            validators.Required(err_msg),
            pb_validator.CheckPasswordStrength(),
            validators.EqualTo('confirm', err_msg_2)
        ])
    else:
        new_password = PasswordField(lazy_gettext('New Password'), [
            validators.Required(err_msg),
            validators.EqualTo('confirm', err_msg_2)
        ])
    confirm = PasswordField(lazy_gettext('Repeat Password'))
示例#38
0
 def __call__(self, form, field):
     try:
         if field.data:
             r = requests.get(field.data)
             if r.status_code != 200:
                 raise ValidationError(self.message)
     except requests.exceptions.ConnectionError:
         raise ValidationError(lazy_gettext(u"Connection error"))
class PresentationProposalForm(wtf.Form):
    fasusername = wtf.TextField(lazy_gettext('FAS username'))
    title = wtf.TextField(lazy_gettext('Presentation title'),
                          [wtf.validators.Required()])
    # I think that this choices shouldn't be translated.
    category = wtf.SelectField(lazy_gettext('Category'),
                               choices=choicer([
                                   'Ambassadors',
                                   'ARM',
                                   'Cloud',
                                   'Community',
                                   'Design',
                                   'Desktop',
                                   'Fonts',
                                   'Games',
                                   'Hardware',
                                   'Infrastructure',
                                   'Kernel',
                                   'Marketing',
                                   'QA',
                                   'Security',
                                   'SIG',
                                   'Other',
                               ]))
    type_ = wtf.SelectField(lazy_gettext('Type'),
                            choices=choicer([
                                lazy_gettext('Talk (45 min)'),
                                lazy_gettext('Workshop (2 hours)'),
                            ]))
    abstract = wtf.TextAreaField(lazy_gettext('Presentation abstract'),
                                 [wtf.validators.Required()])
示例#40
0
class ProjectForm(Form):
    name = TextField(lazy_gettext('Name'), [
        validators.Required(),
        pb_validator.Unique(project_repo.get_by,
                            'name',
                            message=lazy_gettext("Name is already taken."))
    ])
    short_name = TextField(lazy_gettext('Short Name'), [
        validators.Required(),
        pb_validator.NotAllowedChars(),
        pb_validator.Unique(
            project_repo.get_by,
            'short_name',
            message=lazy_gettext("Short Name is already taken.")),
        pb_validator.ReservedName('project', current_app)
    ])
    long_description = TextAreaField(lazy_gettext('Long Description'),
                                     [validators.Required()])
    description = TextAreaField(lazy_gettext('Description'),
                                [validators.Length(max=255)])
    password = TextField(lazy_gettext('Password'), [
        validators.Required(),
        pb_validator.CheckPasswordStrength(min_len=PROJECT_PWD_MIN_LEN,
                                           special=False)
    ])
示例#41
0
class UserPrefMetadataForm(Form):
    """Form for admins to add metadata for users."""
    languages = SelectMultipleField(
                        lazy_gettext('Language(s)'),
                        choices=[], default='')
    locations = SelectMultipleField(
                        lazy_gettext('Location(s)'),
                        choices=[], default='')
    work_hours_from = TimeField(
                        lazy_gettext('Work Hours From'),
                        [TimeFieldsValidator(["work_hours_to", "timezone"],
                        message="Work Hours From, Work Hours To, and Timezone must be filled out for submission")],
                        default='')
    work_hours_to = TimeField(
                        lazy_gettext('Work Hours To'),
                        [TimeFieldsValidator(["work_hours_to", "timezone"],
                        message="Work Hours From, Work Hours To, and Timezone must be filled out for submission")],
                        default='')
    timezone = SelectField(
                        lazy_gettext('Timezone'),
                        [TimeFieldsValidator(["work_hours_from", "work_hours_to"],
                        message="Work Hours From, Work Hours To, and Timezone must be filled out for submission")],
                        choices=[], default=None)
    user_type = SelectField(
                        lazy_gettext('Type of user'),
                        choices=[], default='')
    review = TextAreaField(
                        lazy_gettext('Additional comments'), default='')

    def set_upref_mdata_choices(self):
        from pybossa.core import upref_mdata_choices
        self.languages.choices = upref_mdata_choices['languages']
        self.locations.choices = upref_mdata_choices['locations']
        self.timezone.choices = upref_mdata_choices['timezones']
        self.user_type.choices = upref_mdata_choices['user_types']
示例#42
0
文件: kant.py 项目: Bytespeicher/KANT
def login():
    error = None
    if request.method == 'POST':
        db = get_db()
        cur = db.execute('SELECT password FROM admins WHERE name = ?',
                         [request.form['username']])

        res = cur.fetchone()

        if res == None:
            error = lazy_gettext('Invalid username')
        elif pwd_context.verify(request.form['password'], res['password']) != True:
            error = lazy_gettext('Invalid password')
        else:
            session['logged_in'] = True
            flash(lazy_gettext('You were logged in'))
            return redirect(url_for('show_keys'))
    return render_template('login.html', error=error)
示例#43
0
文件: views.py 项目: j0ack/microbe
def login() :
    """
        Login User
    """
    # create form
    form = LoginForm()
    # form submit
    if form.validate_on_submit() :
        # check username and password
        user = Users.get(form.username.data)
        if not user :
            form.username.errors.append(lazy_gettext(u'Invalid user'))
        elif not user.check_password(form.password.data) :
            form.password.errors.append(lazy_gettext(u'Invalid password'))
        else :
            login_user(user, remember = form.remember.data)
            return redirect(request.args.get('next') or url_for('admin.index'))
    return render_template('admin/model.html', form = form, url = '')
示例#44
0
class ProjectForm(Form):
    name = TextField(lazy_gettext('Name'), [
        validators.Required(),
        pb_validator.Unique(project_repo.get_by,
                            'name',
                            message=lazy_gettext("Name is already taken."))
    ])
    short_name = TextField(lazy_gettext('Short Name'), [
        validators.Required(),
        pb_validator.NotAllowedChars(),
        pb_validator.Unique(
            project_repo.get_by,
            'short_name',
            message=lazy_gettext("Short Name is already taken.")),
        pb_validator.ReservedName('project', current_app)
    ])
    long_description = TextAreaField(lazy_gettext('Long Description'),
                                     [validators.Required()])
示例#45
0
class BulkTaskIIIFImportForm(Form):
    form_name = TextField(label=None, widget=HiddenInput(), default='iiif')
    msg_required = lazy_gettext("You must provide a URL")
    msg_url = lazy_gettext("Oops! That's not a valid URL. "
                           "You must provide a valid URL")
    manifest_uri = TextField(lazy_gettext('URL'),
                             [validators.Required(message=msg_required),
                             validators.URL(message=msg_url)])
    version = SelectField(lazy_gettext('Presentation API version'), choices=[
        (ctx, ctx) for ctx in ManifestReader.contexts
    ], default='2.1')

    def get_import_data(self):
        return {
            'type': 'iiif',
            'manifest_uri': self.manifest_uri.data,
            'version': self.version.data
        }
示例#46
0
 def decorated_function (*args, **kwargs):
     if session.get('AuthUser'):
         return fn(*args, **kwargs)
     else:
         flash(lazy_gettext('Error: User not logged in') )
         if url=='/' :
             return redirect(url_for('login'))
         else:
             return redirect(url_for('login', next=request.url))
示例#47
0
class BulkTaskCSVImportForm(BulkTaskImportForm):
    msg_required = lazy_gettext("You must provide a URL")
    msg_url = lazy_gettext("Oops! That's not a valid URL. "
                           "You must provide a valid URL")
    csv_url = TextField(lazy_gettext('URL'),
                        [validators.Required(message=msg_required),
                         validators.URL(message=msg_url)])
    template_id = "csv"
    form_id = "csvform"
    form_detector = "csv_url"

    def get_data_url(self, form):
        return form.csv_url.data

    def tasks(self, form):
        dataurl = self.get_data_url(form)
        r = requests.get(dataurl)
        return self.get_csv_data_from_request(r)
示例#48
0
 def validate_username(form, field):
     """Disallow usernames which are already present in the contest but associated with a different email"""
     if (db.session.query(User).join(Participation).filter(
             Participation.contest_id == app.config['CONTEST_ID']).filter(
                 or_(User.email == None,
                     User.email != form.email.data)).filter(
                         User.username == field.data)).count():
         raise ValidationError(
             lazy_gettext("Antud kasutajatunnus on juba kasutusel"))
示例#49
0
class UpdateProfileForm(Form):

    """Form Class for updating PyBossa's user Profile."""

    id = IntegerField(label=None, widget=HiddenInput())

    err_msg = lazy_gettext("Full name must be between 3 and 35 "
                           "characters long")
    fullname = TextField(lazy_gettext('Full name'),
                         [validators.Length(min=3, max=35, message=err_msg)])

    err_msg = lazy_gettext("User name must be between 3 and 35 "
                           "characters long")
    err_msg_2 = lazy_gettext("The user name is already taken")
    name = TextField(lazy_gettext('User name'),
                     [validators.Length(min=3, max=35, message=err_msg),
                      pb_validator.NotAllowedChars(),
                      pb_validator.Unique(
                          db.session, model.User, model.User.name, err_msg_2)])

    err_msg = lazy_gettext("Email must be between 3 and 35 characters long")
    err_msg_2 = lazy_gettext("Email is already taken")
    email_addr = TextField(lazy_gettext('Email Address'),
                           [validators.Length(min=3, max=35, message=err_msg),
                            validators.Email(),
                            pb_validator.Unique(
                                db.session, model.User,
                                model.User.email_addr, err_msg_2)])

    locale = SelectField(lazy_gettext('Default Language'))
    ckan_api = TextField(lazy_gettext('CKAN API Key'))

    def set_locales(self, locales):
        """Fill the locale.choices."""
        choices = []
        for locale in locales:
            if locale == 'en':
                lang = gettext("English")
            if locale == 'es':
                lang = gettext("Spanish")
            if locale == 'fr':
                lang = gettext("French")
            choices.append((locale, lang))
        self.locale.choices = choices
示例#50
0
文件: views.py 项目: adesst/hendpos
def user_edit(id=None):
    session['AuthUser'] = {'id' : 1}
    error_message = []
    if request.form :
        form_data = dict(request.form.items())
        for key, value in form_data.iteritems() :
            if value == '':
                error_message.append( lazy_gettext(' %s is NULL' %( key )) )
        if len( error_message ) == 0:
            try:
                id = copy.copy(u'%s' % form_data['id'])
                del form_data['id']
                form_data['date_create'] = parser.parse(form_data['date_create'])
                user_query = db_session.query(User).filter(User.id==id)
                user_query.update(form_data)
                user = user_query.one()
                userlog = UserLog()
                poslog = PosLog()
                userlog.set_fields(form_data)
                userlog.user_id = id
                userlog.date_log = datetime.datetime.now()
                db_session.add(userlog)
                message = lazy_gettext("User %s has been updated " %pop_up_link(('/user/view/%s') %user.id, user.username))
                params = {'auth_user_id' : session['AuthUser']['id'], \
                    'user_id' : user.id, \
                    'message' : message, \
                }
                if not pos_log(params):
                    raise ValueError
                else:
                    flash(message)
                    db_session.flush()
                    db_session.commit()
            except Exception, e:
                db_session.rollback()
                message = "Error: %s %s" %(e, type(e))
                flash(message)
                logging.error('%s %s' %(traceback.print_exc(), message))
                error_message.append( message )
                return redirect(url_for('user_edit', id=id))
            return redirect(url_for('user_list'))
        else:
            pass
示例#51
0
文件: views.py 项目: adesst/hendpos
def user_renew_card(id=None):
    if id == None :
        flash(lazy_gettext('Error: No user ID specified, redirecting to list'))
        return redirect(url_for('user_list'))
    elif request.form :
        pass
    else:
        pass
    user = User.query.filter_by(id=id).first()
    return render_template('default/user_renew_card.html', user=user)
示例#52
0
文件: web.py 项目: rkyymmt/pybossa
def global_template_context():
    if current_user.is_authenticated():
        if current_user.email_addr == current_user.name or current_user.email_addr == "None":
            flash(
                lazy_gettext("Please update your e-mail address in your profile page," " right now it is empty!"),
                "error",
            )

    # Cookies warning
    cookie_name = app.config["BRAND"] + "_accept_cookies"
    show_cookies_warning = False
    print request.cookies.get(cookie_name)
    if not request.cookies.get(cookie_name):
        show_cookies_warning = True

    # Announcement sections
    if app.config.get("ANNOUNCEMENT"):
        announcement = app.config["ANNOUNCEMENT"]
        if current_user.is_authenticated():
            for key in announcement.keys():
                if key == "admin" and current_user.admin:
                    flash(announcement[key], "info")
                if key == "owner" and len(current_user.apps) != 0:
                    flash(announcement[key], "info")
                if key == "user":
                    flash(announcement[key], "info")

    if app.config.get("CONTACT_EMAIL"):
        contact_email = app.config.get("CONTACT_EMAIL")
    else:
        contact_email = "*****@*****.**"

    if app.config.get("CONTACT_TWITTER"):
        contact_twitter = app.config.get("CONTACT_TWITTER")
    else:
        contact_twitter = "PyBossa"

    return dict(
        brand=app.config["BRAND"],
        title=app.config["TITLE"],
        logo=app.config["LOGO"],
        copyright=app.config["COPYRIGHT"],
        description=app.config["DESCRIPTION"],
        terms_of_use=app.config["TERMSOFUSE"],
        data_use=app.config["DATAUSE"],
        enforce_privacy=app.config["ENFORCE_PRIVACY"],
        version=pybossa.__version__,
        current_user=current_user,
        show_cookies_warning=show_cookies_warning,
        contact_email=contact_email,
        contact_twitter=contact_twitter,
    )
示例#53
0
文件: views.py 项目: adesst/hendpos
def transaction_rekap():
    criteration = []
    if not request.form:
        return render_template('default/transaction_rekap.html', form=None)
    if request.form :
        form_data = dict(request.form.items())
        if form_data['from_date'] != '' and form_data['to_date'] != '':
            criteration.append(Balance.tr_date>=parser.parse(form_data['from_date']))
            criteration.append(Balance.tr_date<=parser.parse(form_data['to_date']))
        else:
            criteration.append(Balance.tr_date>=parser.parse(datetime.datetime.now().strftime('%Y-%m-%d')))
            criteration.append(Balance.tr_date>=parser.parse(datetime.datetime.now().strftime('%Y-%m-%d')))
    if id == None:
        flash(lazy_gettext('Error: No user ID specified, redirecting to Transaction List'))
        return redirect(url_for('transaction_list'))
    else:
        mutations = db_session.query(Balance,User).filter(*criteration)
        if mutations:
            return render_template('default/transaction_rekap.html', form=form_data, mutations=mutations)
        else:
            flash(lazy_gettext('Error: Transaction %s is not exists' % id))
            return redirect(url_for('transaction_rekap'))
示例#54
0
文件: views.py 项目: adesst/hendpos
def transaction_delete(id=None):
    if id == None:
        flash(lazy_gettext('Error: No user ID specified, redirecting to Transaction List'))
    else:
        try:
            balance_query = Balance.query.filter_by(id=id)
            balance = balance.one()
        except Exception as e:
            db_session.rollback()
            message = "Error: %s %s" %(e, type(e))
            flash(message)
            logging.error('%s %s' %(traceback.print_exc(), message))
    return redirect(url_for('transaction_list'))
示例#55
0
文件: views.py 项目: adesst/hendpos
def login():
    if request.form:
        form_data = dict(request.form)
        next_url = 'index'
        url_query = dict(request.args)
        user = form_data['username']
        flash(lazy_gettext('Hello %s' %str(user[0])))
        session['AuthUser'] = {'id' : 1}
        if url_query.has_key('next'):
            next_url = url_query['next']
        return redirect(u'%s' %next_url)
    else:
        session['AuthUser'] = {'id' : 1}
        return render_template('default/login.html')
示例#56
0
def apikey_list(user):
    form = new_apikey_form(request.form)
    if request.method == 'POST' and form.validate():
        apikey = ApiKey(application=form.application.data,
                        description=form.description.data,
                        user=current_user)
        apikey.gen_key()
        rfk.database.session.add(apikey)
        rfk.database.session.commit()
        form.application.data = ''
        form.description.data = ''
        flash(lazy_gettext('Added Apikey'))
    apikeys = ApiKey.query.filter(ApiKey.user == current_user).all()
    return render_template('user/apikeys.html', apikeys=apikeys, form=form)
示例#57
0
文件: core.py 项目: bingoko/pybossa
    def global_template_context():
        if current_user.is_authenticated():
            if (current_user.email_addr == current_user.name or
                    current_user.email_addr == "None"):
                flash(lazy_gettext("Please update your e-mail address in your profile page,"
                      " right now it is empty!"), 'error')

        # Cookies warning
        cookie_name = app.config['BRAND'] + "_accept_cookies"
        show_cookies_warning = False
        if not request.cookies.get(cookie_name):
            show_cookies_warning = True

        # Announcement sections
        if app.config.get('ANNOUNCEMENT'):
            announcement = app.config['ANNOUNCEMENT']
            if current_user.is_authenticated():
                for key in announcement.keys():
                    if key == 'admin' and current_user.admin:
                        flash(announcement[key], 'info')
                    if key == 'owner' and len(current_user.apps) != 0:
                        flash(announcement[key], 'info')
                    if key == 'user':
                        flash(announcement[key], 'info')

        if app.config.get('CONTACT_EMAIL'):  # pragma: no cover
            contact_email = app.config.get('CONTACT_EMAIL')
        else:
            contact_email = '*****@*****.**'

        if app.config.get('CONTACT_TWITTER'):  # pragma: no cover
            contact_twitter = app.config.get('CONTACT_TWITTER')
        else:
            contact_twitter = 'PyBossa'

        return dict(
            brand=app.config['BRAND'],
            title=app.config['TITLE'],
            logo=app.config['LOGO'],
            copyright=app.config['COPYRIGHT'],
            description=app.config['DESCRIPTION'],
            terms_of_use=app.config['TERMSOFUSE'],
            data_use=app.config['DATAUSE'],
            enforce_privacy=app.config['ENFORCE_PRIVACY'],
            #version=pybossa.__version__,
            current_user=current_user,
            show_cookies_warning=show_cookies_warning,
            contact_email=contact_email,
            contact_twitter=contact_twitter,
            upload_method=app.config['UPLOAD_METHOD'])
示例#58
0
文件: views.py 项目: j0ack/microbe
def link() :
    """
        Create a new link
    """
    form = LinkForm()
    title = lazy_gettext(u'New link')
    if form.validate_on_submit() :
        # add new link
        label = form.label.data
        url = form.url.data
        cat = form.category.data
        Links.add(label, url, cat)
        return redirect(url_for('admin.links'))
    return render_template('admin/model.html', title = title, 
            form = form, url = url_for('admin.link'))