示例#1
0
def test_upload_field():
    app = Flask(__name__)

    path = _create_temp()

    def _remove_testfiles():
        safe_delete(path, 'test1.txt')
        safe_delete(path, 'test2.txt')

    class TestForm(form.BaseForm):
        upload = form.FileUploadField('Upload', base_path=path)

    class Dummy(object):
        pass

    my_form = TestForm()
    eq_(my_form.upload.base_path, path)

    _remove_testfiles()

    dummy = Dummy()

    # Check upload
    with app.test_request_context(
            method='POST',
            data={'upload': (BytesIO(b'Hello World 1'), 'test1.txt')}):
        my_form = TestForm(helpers.get_form_data())

        ok_(my_form.validate())

        my_form.populate_obj(dummy)

        eq_(dummy.upload, 'test1.txt')
        ok_(op.exists(op.join(path, 'test1.txt')))

    # Check replace
    with app.test_request_context(
            method='POST',
            data={'upload': (BytesIO(b'Hello World 2'), 'test2.txt')}):
        my_form = TestForm(helpers.get_form_data())

        ok_(my_form.validate())
        my_form.populate_obj(dummy)

        eq_(dummy.upload, 'test2.txt')
        ok_(not op.exists(op.join(path, 'test1.txt')))
        ok_(op.exists(op.join(path, 'test2.txt')))

    # Check delete
    with app.test_request_context(method='POST',
                                  data={'_upload-delete': 'checked'}):
        my_form = TestForm(helpers.get_form_data())

        ok_(my_form.validate())

        my_form.populate_obj(dummy)
        eq_(dummy.upload, None)

        ok_(not op.exists(op.join(path, 'test2.txt')))
示例#2
0
def test_upload_field():
    app = Flask(__name__)

    path = _create_temp()

    def _remove_testfiles():
        safe_delete(path, 'test1.txt')
        safe_delete(path, 'test2.txt')

    class TestForm(form.BaseForm):
        upload = form.FileUploadField('Upload', base_path=path)

    class Dummy(object):
        pass

    my_form = TestForm()
    eq_(my_form.upload.base_path, path)

    _remove_testfiles()

    dummy = Dummy()

    # Check upload
    with app.test_request_context(method='POST', data={'upload': (BytesIO(b'Hello World 1'), 'test1.txt')}):
        my_form = TestForm(helpers.get_form_data())

        ok_(my_form.validate())

        my_form.populate_obj(dummy)

        eq_(dummy.upload, 'test1.txt')
        ok_(op.exists(op.join(path, 'test1.txt')))

    # Check replace
    with app.test_request_context(method='POST', data={'upload': (BytesIO(b'Hello World 2'), 'test2.txt')}):
        my_form = TestForm(helpers.get_form_data())

        ok_(my_form.validate())
        my_form.populate_obj(dummy)

        eq_(dummy.upload, 'test2.txt')
        ok_(not op.exists(op.join(path, 'test1.txt')))
        ok_(op.exists(op.join(path, 'test2.txt')))

    # Check delete
    with app.test_request_context(method='POST', data={'_upload-delete': 'checked'}):
        my_form = TestForm(helpers.get_form_data())

        ok_(my_form.validate())

        my_form.populate_obj(dummy)
        eq_(dummy.upload, None)

        ok_(not op.exists(op.join(path, 'test2.txt')))
示例#3
0
    def index(self):
        # 加载该界面的一些常用数据
        form = EarlyWarningForm()

        warn = EarlyWarning(current_app.redis_cache)
        warn.get_form(form)
        warn.get_value()
        warn.out_put()
        if is_form_submitted():
            form = EarlyWarningForm(formdata=get_form_data())
            if form.validate():
                warn.get_form(form)
                warnings = warn.set_warning()
                warn.out_put()
                current_app.predicts_cfg = warnings
                flash('配置设置成功。', 'success')
            else:
                flash('配置设置失败。', 'error')

        # 获取后台支持的文档类别
        resp = proxy.get('/v1/doc-type/')
        support_doctypes = []
        if resp.status_code == 200 and resp.json()['items'] is not None:
            support_doctypes = [item['id'] for item in resp.json()['items']]
        return self.render(self._template,
                           form=form,
                           support_doctypes=support_doctypes)
示例#4
0
 def create_form(self, obj=None):
     ret = None
     model_name = request.args.get('model', '')
     if request.method == 'GET':
         ao_id = request.args.get('id', '')
         ret = self.creat_detail_view(ao_id=ao_id,
                                      create=True,
                                      storage_model=model_name)
     else:
         request_str = request.headers['Referer']
         modelName = re.findall(r"model=(.+?)&", request_str)[0]
         action_id = None
         for val in request_str.split('&'):
             if 'id=' in val:
                 action_id = val.split('=')[1]
                 break
         # action_id = ac_id if ''request_str.split('&id=')[1]
         ret = self.creat_detail_view(ao_id=action_id,
                                      create=True,
                                      storage_model=modelName)
     if ret:
         self._template_args.update({
             'table_columns':
             self.init_table_columns(ret[1]),
             'table_datas':
             ret[0],
         })
     self.get_accessory_from_before(self.get_create_form(), model_name,
                                    self.types_dict)
     return self._create_form_class(get_form_data(), obj=obj)
示例#5
0
文件: admin.py 项目: ipenn/myflask
    def edit_form(self, obj=None):
        Form = self.scaffold_form()

        class MyForm(Form):
            password = MyPasswordField('密码')

        return MyForm(get_form_data(), obj=obj)
示例#6
0
    def create_form(self, obj=None):

        self._create_form_class.troubleShooting.kwargs[
            'query_factory'] = trouble_shooting_choices

        ts_id = request.args.get('id', '')
        view_url = request.args.get('view', '')
        if ts_id:
            if view_url and 'troubleshooting' in view_url:
                ts = TroubleShooting.query.filter(
                    TroubleShooting.id == ts_id).first()
                inst = FaultReports.query.join(
                    TroubleShooting,
                    TroubleShooting.faultReports_id == FaultReports.id).filter(
                        TroubleShooting.id == ts_id)
                tmp_form_class = self.get_create_form()
                datas = []
                for key, value in inst[0].__dict__.iteritems():
                    if key not in self.review_details_columns or\
                            key == 'recordNum':
                        continue
                    datas.append(key)
                    tmp = getattr(tmp_form_class, key)
                    tmp.kwargs['default'] = value

                tmp_form_class.troubleShooting.kwargs['default'] = ts
                tmp_form_class.faultType.kwargs['default'] = '严重故障'
                return tmp_form_class(get_form_data(), obj)

            if view_url and 'reservedfault' in view_url:
                rf = ReservedFault.query.filter(
                    ReservedFault.id == ts_id).first()
                return self.create_form_with_default(rf)

        return super(_ExamineRepairRecordView, self).create_form(obj)
示例#7
0
文件: app.py 项目: mbcha/pictionary
    def guessed_view(self):
        return_url = self.get_url('.index_view')

        form = get_form_data()
        word_id = form['word_id']

        word = self.get_one(word_id)
        word.guessed = True
        team = word.team
        team.score = team.score + word.score

        try:
            self.session.commit()
            flash(gettext(
                'Word ID {word_id} guessed!'.format(word_id=word_id)))
        except Exception as ex:
            if not self.handle_view_exception(ex):
                raise

            flash(
                gettext('Failed to set word ID {word_id} to guessed.'.format(
                    word_id=word_id),
                        error=str(ex)), 'error')

        return redirect(return_url)
示例#8
0
def test_relative_path():
    app = Flask(__name__)

    path = _create_temp()

    def _remove_testfiles():
        safe_delete(path, 'test1.txt')

    class TestForm(form.BaseForm):
        upload = form.FileUploadField('Upload', base_path=path, relative_path='inner/')

    class Dummy(object):
        pass

    my_form = TestForm()
    eq_(my_form.upload.base_path, path)
    eq_(my_form.upload.relative_path, 'inner/')

    _remove_testfiles()

    dummy = Dummy()

    # Check upload
    with app.test_request_context(method='POST', data={'upload': (BytesIO(b'Hello World 1'), 'test1.txt')}):
        my_form = TestForm(helpers.get_form_data())

        ok_(my_form.validate())

        my_form.populate_obj(dummy)

        eq_(dummy.upload, 'inner/test1.txt')
        ok_(op.exists(op.join(path, 'inner/test1.txt')))

        eq_(url_for('static', filename=dummy.upload), '/static/inner/test1.txt')
示例#9
0
 def authorize_view(self):
     return_url = self.get_url('.index_view')
     # check permission
     if not (current_user.has_role(Role.ROLE_ADMIN) or current_user.has_role(Role.ROLE_AUTHORIZER)):
         # permission denied
         flash('Not authorized.', 'error')
         return redirect(return_url)
     # get the model from the database
     form = get_form_data()
     if not form:
         flash('Could not get form data.', 'error')
         return redirect(return_url)
     proposal_id = form['proposal_id']
     proposal = self.get_one(proposal_id)
     if proposal is None:
         flash('Proposal not not found.', 'error')
         return redirect(return_url)
     # process the proposal
     proposal.authorize(current_user)
     # commit to db
     try:
         self.session.commit()
         flash('Proposal {proposal_id} set as authorized'.format(proposal_id=proposal_id))
     except (SQLAlchemyError, DBAPIError) as ex:
         if not self.handle_view_exception(ex):
             raise
         flash('Failed to set proposal {proposal_id} as authorized'.format(proposal_id=proposal_id), 'error')
     return redirect(return_url)
示例#10
0
文件: admin.py 项目: wushuyi/myflask
    def edit_form(self, obj=None):
        Form = self.scaffold_form()

        class MyForm(Form):
            password = MyPasswordField('密码')

        return MyForm(get_form_data(), obj=obj)
示例#11
0
def test_relative_path():
    app = Flask(__name__)

    path = _create_temp()

    def _remove_testfiles():
        safe_delete(path, 'test1.txt')

    class TestForm(form.BaseForm):
        upload = form.FileUploadField('Upload', base_path=path, relative_path='inner/')

    class Dummy(object):
        pass

    my_form = TestForm()
    eq_(my_form.upload.base_path, path)
    eq_(my_form.upload.relative_path, 'inner/')

    _remove_testfiles()

    dummy = Dummy()

    # Check upload
    with app.test_request_context(method='POST', data={'upload': (BytesIO(b'Hello World 1'), 'test1.txt')}):
        my_form = TestForm(helpers.get_form_data())

        ok_(my_form.validate())

        my_form.populate_obj(dummy)

        eq_(dummy.upload, 'inner/test1.txt')
        ok_(op.exists(op.join(path, 'inner/test1.txt')))

        eq_(url_for('static', filename=dummy.upload), '/static/inner/test1.txt')
    def edit_form(self, obj=None) -> Form:
        class _NewStatusForm(Form):
            beneficiary = StringField(
                "Bénéficiaire",
                default=obj.beneficiary.email if obj.beneficiary else "N/A",
                render_kw={"readonly": True},
            )
            applicationId = StringField("Dossier DMS",
                                        default=obj.applicationId,
                                        render_kw={"readonly": True})
            statuses = TextAreaField("Statuts précédents",
                                     default=obj.history,
                                     render_kw={
                                         "readonly": True,
                                         "rows": len(obj.statuses)
                                     })
            detail = StringField("Raison du changement de statut")
            status = SelectField(
                "Nouveau statut",
                choices=[(status.name, status.value)
                         for status in ImportStatus],
                default=obj.currentStatus.value,
            )

        return _NewStatusForm(get_form_data())
示例#13
0
 def reset_view(self):
     return_url = self.get_url('.index_view')
     # check permission
     if not (current_user.has_role('admin')
             or current_user.has_role('finance')):
         # permission denied
         flash('Not authorized.', 'error')
         return redirect(return_url)
     # get the model from the database
     form = get_form_data()
     if not form:
         flash('Could not get form data.', 'error')
         return redirect(return_url)
     settlement_id = form['settlement_id']
     settlement = self.get_one(settlement_id)
     if settlement is None:
         flash('Settlement not not found.', 'error')
         return redirect(return_url)
     # process the settlement
     if settlement.status in (settlement.STATE_ERROR,
                              settlement.STATE_SUSPENDED):
         settlement.status = settlement.STATE_SENT_ZAP
     # commit to db
     try:
         self.session.commit()
         flash('Settlement {settlement_id} set as sent_zap'.format(
             settlement_id=settlement_id))
     except Exception as ex:
         if not self.handle_view_exception(ex):
             raise
         flash(
             'Failed to set Settlement {settlement_id} as sent_zap'.format(
                 settlement_id=settlement_id), 'error')
     return redirect(return_url)
示例#14
0
 def decline_view(self):
     return_url = self.get_url('.index_view')
     # check permission
     if not (current_user.has_role('admin')
             or current_user.has_role('authorizer')):
         # permission denied
         flash('Not authorized.', 'error')
         return redirect(return_url)
     # get the model from the database
     form = get_form_data()
     if not form:
         flash('Could not get form data.', 'error')
         return redirect(return_url)
     proposal_id = form['proposal_id']
     proposal = self.get_one(proposal_id)
     if proposal is None:
         flash('Proposal not not found.', 'error')
         return redirect(return_url)
     # process the proposal
     if proposal.status == proposal.STATE_CREATED:
         proposal.status = proposal.STATE_DECLINED
         proposal.authorizer = current_user
     # commit to db
     try:
         self.session.commit()
         flash('Proposal {proposal_id} set as declined'.format(
             proposal_id=proposal_id))
     except Exception as ex:
         if not self.handle_view_exception(ex):
             raise
         flash(
             'Failed to set proposal {proposal_id} as declined'.format(
                 proposal_id=proposal_id), 'error')
     return redirect(return_url)
    def bulk_create_view(self):
        return_url = self.get_url(".index_view")
        if not self.can_create:
            return redirect(return_url)

        form = self.get_thc_result_create_1_form()
        form_data = get_form_data()

        if request.method == "POST" and form_data:
            if form_data.get("form_step") == "1":
                # store
                form = self.get_thc_result_create_1_form()
                if self.validate_form(form):
                    session["thc_form_1_data"] = form_data
                    q_list = THCQuestion.query.filter_by(
                        deck=form_data["deck"]).all()
                    return self.render("cadmin/thc_result_create_2.html",
                                       q_list=q_list)

            elif form_data.get("form_step") == "2":
                # create objects
                try:
                    prev_form_data = session.pop("thc_form_1_data")
                except KeyError:
                    # display step 1
                    pass
                else:
                    q_list = THCQuestion.query.filter_by(
                        deck=prev_form_data["deck"]).all()
                    for i in range(1, len(q_list) + 1):
                        measurement_data = dict(
                            question_id=form_data[f"q_{i}"],
                            result_red=form_data[f"red_{i}"],
                            result_yellow=form_data[f"yellow_{i}"],
                            result_green=form_data[f"green_{i}"],
                        )
                        obj = THCMeasurement(
                            measurement_date=prev_form_data["date"],
                            session_name=prev_form_data["session_name"],
                            team_id=prev_form_data["team"],
                            **measurement_data,
                        )
                        db.session.add(obj)
                    try:
                        db.session.commit()
                        flash(
                            f"Successfully recorded {prev_form_data['session_name']}",
                            "success",
                        )
                    except:
                        err_msg = f"Failed to record {prev_form_data['session_name']}"
                        current_app.logger.error(traceback.format_exc())
                        current_app.logger.error(err_msg)
                        flash(err_msg, "error")
                    return redirect(return_url)

        form = self.get_thc_result_create_1_form()
        template = "cadmin/thc_result_create_1.html"
        return self.render(template, form=form, return_url=return_url)
 def get_thc_result_create_1_form(self):
     form = THCResultForm1(get_form_data())
     form.team.query = current_user.readable_teams
     form.deck.choices = [
         (d[0], d[0])
         for d in db.session.query(THCQuestion.deck).distinct()
     ]
     return form
示例#17
0
 def edit_form(self, obj=None):
     ''''Pour mettre des champs en Read Only'''
     from flask_admin.helpers import get_form_data
     self._edit_form_class = self.get_edit_form()
     form_class = deepcopy(self._edit_form_class)
     for field in self._edit_form_readonly_fields:
         setattr(form_class, field, ReadOnlyStringField())
     return form_class(get_form_data(), obj=obj)
示例#18
0
    def import_view(self):
        return_url = get_redirect_target() or self.get_url('.index_view')
        form = ImportForm(get_form_data())

        if self.validate_form(form):
            pair_tuple = form.data['cert'].encode(
                'ascii'), form.data['key'].encode('ascii')
            info = x509.load_certificate_info(pair_tuple)

            if not x509.does_keys_match(pair_tuple):
                flash('Failed to import identity: keys does not match.',
                      'error')
                return redirect(return_url)

            identity = models.Identity()
            identity.name = info.subj_cn

            if not info.self_signed:

                def find_issuer():
                    for issuer in models.Identity.query.filter_by(
                            name=info.issuer_cn):
                        cert_chain = issuer.get_cert_chain()
                        try:
                            x509.verify_certificate_chain(
                                pair_tuple[0], cert_chain)
                        except x509.InvalidCertificate:
                            pass
                        else:
                            return issuer

                identity.issuer = find_issuer()
                if not identity.issuer:
                    flash(
                        'Failed to import identity: issuer identity not found.',
                        'error')
                    return redirect(return_url)

            self.session.add(identity)
            pair = models.Pair(*pair_tuple)
            pair.identity = identity
            self.session.add(pair)

            try:
                self.session.commit()
            except IntegrityError:
                flash(
                    'Failed to import identity: identity with same name already exists.',
                    'error')
                return redirect(return_url)

            flash('Identity was successfully imported.', 'success')
            return redirect(self.get_save_return_url(identity,
                                                     is_created=True))

        return self.render('admin/identity_import.html',
                           form=form,
                           return_url=return_url)
示例#19
0
文件: admin.py 项目: ipenn/myflask
    def edit_form(self, obj=None):
        Form = self.scaffold_form()

        class MyForm(Form):
            # markdown = TextAreaField('Markdown')
            pre_content = HiddenField('预览内容')
            content = HiddenField('内容')

        return MyForm(get_form_data(), obj=obj)
示例#20
0
 def process_flow_form(self, form_class, model, verb):
     if verb in ['upload_contract_file', 'upload_meeting_file']:
         form = form_class(formdata=get_form_data())
         if form.validate():
             form.populate_obj(model)
         self.session.commit()
     else:
         super(ApproveFlowUploadFileView, self).\
             process_flow_form(form_class, model, verb)
示例#21
0
    def edit_form(self, obj=None):
        """
            Instantiate model editing form and return it.

            Override to implement custom behavior.
        """
        form_obj = self._edit_form_class(get_form_data(), obj=obj)
        form_obj.tests.choices = get_all_test_choices()
        return form_obj
示例#22
0
文件: admin.py 项目: wushuyi/myflask
    def edit_form(self, obj=None):
        Form = self.scaffold_form()

        class MyForm(Form):
            # markdown = TextAreaField('Markdown')
            pre_content = HiddenField('预览内容')
            content = HiddenField('内容')

        return MyForm(get_form_data(), obj=obj)
示例#23
0
    def create_form(self, obj=None):
        """Overriding the default create form to add some hidden field values"""
        form_data = get_form_data()

        i = InviteForm()

        if form_data:
            i.invitee_email.data = form_data['invitee_email']
            i.invitor_id.data = current_user.id
            i.token.data = generate_invitation_token(current_user)

        return i
示例#24
0
    def create_form(self, obj=None):
        if not is_form_submitted():
            current_config = offers_repository.get_current_offer_validation_config(
            )
            if current_config:
                form = OfferValidationConfigForm()
                form.specs.data = yaml.dump(current_config.specs,
                                            indent=4,
                                            allow_unicode=True)
                return form

        return OfferValidationConfigForm(get_form_data())
示例#25
0
    def edit_form(self, obj=None):
        class _NewStatusForm(Form):
            beneficiary = StringField('Bénéficiaire', default=obj.beneficiary.email if obj.beneficiary else 'N/A',
                                      render_kw={'readonly': True})
            demarche_simplifiee_application_id = StringField(
                'Dossier DMS', default=obj.demarcheSimplifieeApplicationId, render_kw={'readonly': True}
            )
            statuses = TextAreaField('Status précédents', default=obj.history,
                                     render_kw={'readonly': True, 'rows': len(obj.statuses)})
            detail = StringField('Raison du changement de statut')
            status = SelectField('Nouveau statut', choices=[(s.name, s.value) for s in ImportStatus])

        return _NewStatusForm(get_form_data())
示例#26
0
 def create_form_with_default(self, inst, related=None, obj=None):
     tmp_form_class = self.get_create_form()
     for key, value in inst.__dict__.iteritems():
         if key not in self.review_details_columns:
             continue
         if key in ['statusName', 'number', 'remark', 'date']:
             continue
         tmp = getattr(tmp_form_class, key)
         tmp.kwargs['default'] = value
     if related:
         tmp = getattr(tmp_form_class, related)
         tmp.kwargs['default'] = inst
     return tmp_form_class(get_form_data(), obj=obj)
示例#27
0
    def edit_form(self, obj=None):
        """
            Instantiate model editing form and return it.

            Override to implement custom behavior.
        """
        if not obj:
            raise ValueError

        view_subclass = self.subclass.get(obj.__class__)
        if view_subclass and view_subclass != self.__class__:
            view = view_subclass(obj.__class__, self.session)
            return view.edit_form(obj)

        return self._edit_form_class(get_form_data(), obj=obj)
示例#28
0
    def create_form(self, obj=None, klass=None):
        data = get_form_data()
        if not data:
            params = {}
            active_filters = self._get_list_filter_args()
            if active_filters:
                for i, flt in enumerate(active_filters):
                    key = self.column_filters[flt[0]]
                    params[key] = flt[2]

            if self.inject_current_project and current_project and 'project' in self.model._fields:
                params.setdefault('project', current_project.id)

            data = ImmutableMultiDict(params)

        if klass is None:
            klass = self._create_form_class

        form = klass(data, obj=obj)
        return form
示例#29
0
 def index(self):
     # 加载该界面的一些常用数据
     form = CheckWarningForm()
     warn = CheckWarning(current_app.redis_cache)
     warn.get_form(form)
     warn.get_value()
     warn.out_put()
     if is_form_submitted():
         form = CheckWarningForm(formdata=get_form_data())
         try:
             if form.validate():
                 warn.get_form(form)
                 warnings = warn.set_warning()
                 warn.out_put()
                 current_app.predicts_cfg = warnings
                 flash('配置设置成功。', 'success')
             else:
                 flash('配置设置失败!请检查您的输入数据类型是否为整数。', 'error')
         except ValueError as ex:
             flash('Failed. %s' % ex.message, 'error')
     return self.render(self._template, form=form, support_doctypes=None)
示例#30
0
文件: page.py 项目: icaicai/yunduo
    def check(self):
        data = get_form_data()
        form = self._create_form_class(data)
        # print dir(form)
        d = {}
        for f in form._fields:
            d[f] = getattr(form, f).data

        # rules = []
        if 'link_rules' in d:
            for rule in d['link_rules']:
                # print(rule)
                page = rule.pop('page')
                rule['page'] = page.alias
                if 'allows' in rule and rule['allows']:
                    rule['allows'] = rule['allows'].strip().split('\n')
                if 'denies' in rule and rule['denies']:
                    rule['denies'] = rule['denies'].strip().split('\n')
            # rules.append('rule')
        return json.dumps(self.test_conf(d)), 200, {
            'Content-Type': 'application/json'
        }
示例#31
0
 def edit_form(self, obj=None):
     ao_id = request.args.get('id', '')
     outStorageModel = PutOutStoreModel.query.filter_by(id=ao_id).first()
     des = self.get_edit_details_view_colums(
         outStorageModel.outStoreCategory)
     converter = self.model_form_converter(self.session, self)
     self._template_args.update({
         'table_columns':
         self.init_table_columns(des[0]),
         'table_datas':
         self.get_table_data_from_db(outStorageModel),
     })
     self._edit_form_class = form.get_form(
         self.model,
         converter,
         base_class=self.form_base_class,
         only=self.form_columns,
         exclude=des[1],
         field_args=self.form_args,
         ignore_hidden=self.ignore_hidden,
         extra_fields=self.form_extra_fields)
     return self._edit_form_class(get_form_data(), obj=obj)
    def edit_form(self, obj=None) -> Form:
        form_class = self.get_edit_form()
        is_allocine = isinstance(obj, AllocineVenueProvider)

        form_class.allocine_is_duo = (BooleanField(
            default=obj.isDuo if is_allocine else None,
            label="En duo (allociné)",
            validators=[Optional()],
        ) if is_allocine else None)
        form_class.allocine_quantity = (IntegerField(
            default=obj.quantity if is_allocine else None,
            label="Quantité (allociné)",
            validators=[Optional()],
        ) if is_allocine else None)
        form_class.allocine_price = (IntegerField(
            default=obj.priceRules[0].price
            if is_allocine and obj.priceRules else None,
            label="Prix (allociné)",
            validators=[Optional()],
        ) if is_allocine else None)

        return form_class(get_form_data(), obj=obj)
def test_relative_path():
    app = Flask(__name__)

    path = _create_temp()

    def _remove_testfiles():
        safe_delete(path, "test1.txt")

    class TestForm(form.BaseForm):
        upload = form.FileUploadField("Upload",
                                      base_path=path,
                                      relative_path="inner/")

    class Dummy(object):
        pass

    my_form = TestForm()
    eq_(my_form.upload.base_path, path)
    eq_(my_form.upload.relative_path, "inner/")

    _remove_testfiles()

    dummy = Dummy()

    # Check upload
    with app.test_request_context(
            method="POST",
            data={"upload": (BytesIO(b"Hello World 1"), "test1.txt")}):
        my_form = TestForm(helpers.get_form_data())

        ok_(my_form.validate())

        my_form.populate_obj(dummy)

        eq_(dummy.upload, "inner/test1.txt")
        ok_(op.exists(op.join(path, "inner/test1.txt")))

        eq_(url_for("static", filename=dummy.upload),
            "/static/inner/test1.txt")
示例#34
0
    def checkout_view(self):

        return_url = self.get_url('.index_view')

        form = get_form_data()

        if not form:
            flash(gettext('Could not get form from request.'), 'error')
            return redirect(return_url)

        # Form is an ImmutableMultiDict
        student_id = form['student_id']

        # Get the model from the database
        model = self.get_one(student_id)

        if model is None:
            flash(gettext('Student not not found.'), 'error')
            return redirect(return_url)

        # process the model
        model.is_paid = True

        try:
            self.session.commit()
            flash(
                gettext('Student, ID: {student_id}, set as paid'.format(
                    student_id=student_id)))
        except Exception as ex:
            if not self.handle_view_exception(ex):
                raise

            flash(
                gettext(
                    'Failed to set student, ID: {student_id}, as paid'.format(
                        student_id=student_id),
                    error=str(ex)), 'error')

        return redirect(return_url)
示例#35
0
    def send_mail_view(self):
        """发送验证邮件"""
        from app.services.auth.confirm import generate_confirm_token
        from app.backtasks.send_mail import send_mail

        return_url = self.get_url(".index_view")
        form = get_form_data()

        if not form:
            flash("无法获取表单", "error")
            return redirect(return_url)

        uid = form["user_id"]

        user = self.model.get_by_id(uid)
        token = generate_confirm_token(user, "confirm")
        url = url_for("Auth.UserConfirmView", token=token, _external=True)
        send_mail.delay(
            user.email, "验证邮箱", {"url": url, "message": "这是一封验证邮件"}, "confirm"
        )
        flash("验证邮件已发送")

        return redirect(return_url)
示例#36
0
文件: view.py 项目: cluo/flask-admin
 def edit_form(self, obj):
     """
         Create edit form from the MongoDB document
     """
     return self._edit_form_class(get_form_data(), **obj)
示例#37
0
 def edit_form(self, obj):
     """
         Create edit form from the MongoDB document
     """
     return self._edit_form_class(get_form_data(), **obj)
示例#38
0
def test_image_upload_field():
    app = Flask(__name__)

    path = _create_temp()

    def _remove_testimages():
        safe_delete(path, 'test1.png')
        safe_delete(path, 'test1_thumb.jpg')
        safe_delete(path, 'test2.png')
        safe_delete(path, 'test2_thumb.jpg')
        safe_delete(path, 'test1.jpg')
        safe_delete(path, 'test1.jpeg')
        safe_delete(path, 'test1.gif')
        safe_delete(path, 'test1.png')
        safe_delete(path, 'test1.tiff')

    class TestForm(form.BaseForm):
        upload = form.ImageUploadField('Upload',
                                       base_path=path,
                                       thumbnail_size=(100, 100, True))

    class TestNoResizeForm(form.BaseForm):
        upload = form.ImageUploadField('Upload', base_path=path, endpoint='test')

    class TestAutoResizeForm(form.BaseForm):
        upload = form.ImageUploadField('Upload',
                                       base_path=path,
                                       max_size=(64, 64, True))

    class Dummy(object):
        pass

    my_form = TestForm()
    eq_(my_form.upload.base_path, path)
    eq_(my_form.upload.endpoint, 'static')

    _remove_testimages()

    dummy = Dummy()

    # Check upload
    filename = op.join(op.dirname(__file__), 'data', 'copyleft.png')

    with open(filename, 'rb') as fp:
        with app.test_request_context(method='POST', data={'upload': (fp, 'test1.png')}):
            my_form = TestForm(helpers.get_form_data())

            ok_(my_form.validate())

            my_form.populate_obj(dummy)

            eq_(dummy.upload, 'test1.png')
            ok_(op.exists(op.join(path, 'test1.png')))
            ok_(op.exists(op.join(path, 'test1_thumb.png')))

    # Check replace
    with open(filename, 'rb') as fp:
        with app.test_request_context(method='POST', data={'upload': (fp, 'test2.png')}):
            my_form = TestForm(helpers.get_form_data())

            ok_(my_form.validate())

            my_form.populate_obj(dummy)

            eq_(dummy.upload, 'test2.png')
            ok_(op.exists(op.join(path, 'test2.png')))
            ok_(op.exists(op.join(path, 'test2_thumb.png')))

            ok_(not op.exists(op.join(path, 'test1.png')))
            ok_(not op.exists(op.join(path, 'test1_thumb.jpg')))

    # Check delete
    with app.test_request_context(method='POST', data={'_upload-delete': 'checked'}):
        my_form = TestForm(helpers.get_form_data())

        ok_(my_form.validate())

        my_form.populate_obj(dummy)
        eq_(dummy.upload, None)

        ok_(not op.exists(op.join(path, 'test2.png')))
        ok_(not op.exists(op.join(path, 'test2_thumb.png')))

    # Check upload no-resize
    with open(filename, 'rb') as fp:
        with app.test_request_context(method='POST', data={'upload': (fp, 'test1.png')}):
            my_form = TestNoResizeForm(helpers.get_form_data())

            ok_(my_form.validate())

            my_form.populate_obj(dummy)

            eq_(dummy.upload, 'test1.png')
            ok_(op.exists(op.join(path, 'test1.png')))
            ok_(not op.exists(op.join(path, 'test1_thumb.png')))

    # Check upload, auto-resize
    filename = op.join(op.dirname(__file__), 'data', 'copyleft.png')

    with open(filename, 'rb') as fp:
        with app.test_request_context(method='POST', data={'upload': (fp, 'test1.png')}):
            my_form = TestAutoResizeForm(helpers.get_form_data())

            ok_(my_form.validate())

            my_form.populate_obj(dummy)

            eq_(dummy.upload, 'test1.png')
            ok_(op.exists(op.join(path, 'test1.png')))

    filename = op.join(op.dirname(__file__), 'data', 'copyleft.tiff')

    with open(filename, 'rb') as fp:
        with app.test_request_context(method='POST', data={'upload': (fp, 'test1.tiff')}):
            my_form = TestAutoResizeForm(helpers.get_form_data())

            ok_(my_form.validate())

            my_form.populate_obj(dummy)

            eq_(dummy.upload, 'test1.jpg')
            ok_(op.exists(op.join(path, 'test1.jpg')))


    # check allowed extensions
    for extension in ('gif', 'jpg', 'jpeg', 'png', 'tiff'):
        filename = 'copyleft.' + extension
        filepath = op.join(op.dirname(__file__), 'data', filename)
        with open(filepath, 'rb') as fp:
            with app.test_request_context(method='POST', data={'upload': (fp, filename)}):
                my_form = TestNoResizeForm(helpers.get_form_data())
                ok_(my_form.validate())
                my_form.populate_obj(dummy)
                eq_(dummy.upload, my_form.upload.data.filename)

    # check case-sensitivity for extensions
    filename = op.join(op.dirname(__file__), 'data', 'copyleft.jpg')
    with open(filename, 'rb') as fp:
        with app.test_request_context(method='POST', data={'upload': (fp, 'copyleft.JPG')}):
            my_form = TestNoResizeForm(helpers.get_form_data())
            ok_(my_form.validate())
示例#39
0
 def get_edit_form(self, obj):
     return self.edit_form(get_form_data(), **obj)
示例#40
0
 def edit_form(self, obj):
     cols = {}
     for col in set(self.column_list + self.column_details_list):
         cols[col] = obj.get(col)
     return self._edit_form_class(get_form_data(), **cols)