示例#1
0
    def upload(self, path=None):
        """
            Upload view method

            :param path:
                Optional directory path. If not provided, will use the base directory
        """
        # Get path and verify if it is valid
        base_path, directory, path = self._normalize_path(path)

        if not self.can_upload:
            flash(gettext("File uploading is disabled."), "error")
            return redirect(self._get_dir_url(".index", path))

        if not self.is_accessible_path(path):
            flash(gettext("Permission denied."), "error")
            return redirect(self._get_dir_url(".index"))

        form = self.upload_form()
        if self.validate_form(form):
            try:
                self._save_form_files(directory, path, form)
                flash(gettext("Successfully saved file: %(name)s", name=form.upload.data.filename))
                return redirect(self._get_dir_url(".index", path))
            except Exception as ex:
                flash(gettext("Failed to save file: %(error)s", error=ex), "error")

        return self.render(
            self.upload_template, form=form, header_text=gettext("Upload File"), modal=request.args.get("modal")
        )
示例#2
0
    def rename(self):
        """
            Rename view method
        """
        path = request.args.get('path')

        if not path:
            return redirect(url_for('.index'))

        base_path, full_path, path = self._normalize_path(path)

        return_url = self._get_dir_url('.index', op.dirname(path))

        if not self.can_rename:
            flash(gettext('Renaming is disabled.'))
            return redirect(return_url)

        if not op.exists(full_path):
            flash(gettext('Path does not exist.'))
            return redirect(return_url)

        form = NameForm(request.form, name=op.basename(path))
        if form.validate_on_submit():
            try:
                dir_base = op.dirname(full_path)
                filename = secure_filename(form.name.data)

                os.rename(full_path, op.join(dir_base, filename))
                flash(gettext('Successfully renamed "%(src)s" to "%(dst)s"',
                      src=op.basename(path),
                      dst=filename))
            except Exception, ex:
                flash(gettext('Failed to rename: %(error)s', error=ex), 'error')

            return redirect(return_url)
示例#3
0
    def upload(self, path=None):
        """
            Upload view method

            :param path:
                Optional directory path. If not provided, will use the base directory
        """
        # Get path and verify if it is valid
        base_path, directory, path = self._normalize_path(path)

        if not self.can_upload:
            flash(gettext('File uploading is disabled.'), 'error')
            return redirect(self._get_dir_url('.index', path))

        if not self.is_accessible_path(path):
            flash(gettext('Permission denied.'), 'error')
            return redirect(self._get_dir_url('.index'))

        form = self.upload_form()
        if self.validate_form(form):
            try:
                self._save_form_files(directory, path, form)
                return redirect(self._get_dir_url('.index', path))
            except Exception as ex:
                flash(gettext('Failed to save file: %(error)s', error=ex), 'error')

        return self.render(self.upload_template, form=form)
示例#4
0
    def mkdir(self, path=None):
        """
            Directory creation view method

            :param path:
                Optional directory path. If not provided, will use the base directory
        """
        # Get path and verify if it is valid
        base_path, directory, path = self._normalize_path(path)

        dir_url = self._get_dir_url('.index', path)

        if not self.can_mkdir:
            flash(gettext('Directory creation is disabled.'), 'error')
            return redirect(dir_url)

        if not self.is_accessible_path(path):
            flash(gettext('Permission denied.'), 'error')
            return redirect(self._get_dir_url('.index'))

        form = self.name_form()

        if self.validate_form(form):
            try:
                os.mkdir(op.join(directory, form.name.data))
                self.on_mkdir(directory, form.name.data)
                return redirect(dir_url)
            except Exception as ex:
                flash(gettext('Failed to create directory: %(error)s', error=ex), 'error')
        else:
            helpers.flash_errors(form, message='Failed to create directory: %(error)s')

        return self.render(self.mkdir_template,
                           form=form,
                           dir_url=dir_url)
示例#5
0
    def upload(self, path=None):
        """
            Upload view method

            :param path:
                Optional directory path. If not provided, will use the base directory
        """
        # Get path and verify if it is valid
        base_path, directory, path = self._normalize_path(path)

        if not self.can_upload:
            flash(gettext('File uploading is disabled.'), 'error')
            return redirect(self._get_dir_url('.index', path))

        form = UploadForm(self)
        if form.validate_on_submit():
            filename = op.join(directory,
                               secure_filename(form.upload.data.filename))

            if op.exists(filename):
                flash(gettext('File "%(name)s" already exists.', name=form.upload.data.filename),
                      'error')
            else:
                try:
                    self.save_file(filename, form.upload.data)
                    return redirect(self._get_dir_url('.index', path))
                except Exception, ex:
                    flash(gettext('Failed to save file: %(error)s', error=ex))
示例#6
0
    def delete(self):
        """
            Delete view method
        """
        path = request.form.get('path')

        if not path:
            return redirect(url_for('.index'))

        # Get path and verify if it is valid
        base_path, full_path, path = self._normalize_path(path)

        return_url = self._get_dir_url('.index', op.dirname(path))

        if not self.can_delete:
            flash(gettext('Deletion is disabled.'))
            return redirect(return_url)

        if op.isdir(full_path):
            if not self.can_delete_dirs:
                flash(gettext('Directory deletion is disabled.'))
                return redirect(return_url)

            try:
                shutil.rmtree(full_path)
                flash(gettext('Directory "%s" was successfully deleted.' % path))
            except Exception, ex:
                flash(gettext('Failed to delete directory: %(error)s', error=ex), 'error')
示例#7
0
 def pre_validate(self, form):
     if self._is_uploaded_file(self.data) and not self.is_file_allowed(self.data.filename):
         raise ValidationError(gettext('Invalid file extension'))
     # Handle overwriting existing content
     if not self._is_uploaded_file(self.data):
         return
     if self._allow_overwrite == False and os.path.exists(self._get_path(self.data.filename)):
         raise ValidationError(gettext('File "%s" already exists.' % self.data.filename))
示例#8
0
            def validate_upload(self, field):
                if not self.upload.data:
                    raise validators.ValidationError(gettext('File required.'))

                filename = self.upload.data.filename

                if not self.admin.is_file_allowed(filename):
                    raise validators.ValidationError(gettext('Invalid file type.'))
示例#9
0
    def action_delete(self, items):
        for path in items:
            base_path, full_path, path = self._normalize_path(path)

            try:
                os.remove(full_path)
                flash(gettext('File "%(name)s" was successfully deleted.', name=path))
            except Exception, ex:
                flash(gettext('Failed to delete file: %(name)s', name=ex), 'error')
示例#10
0
    def upload(self, path=None):
        """
            Upload view method

            :param path:
                Optional directory path. If not provided, will use the base directory
        """
        # Get path and verify if it is valid
        base_path, directory, path = self._normalize_path(path)

        if not self.can_upload:
            flash(gettext('File uploading is disabled.'), 'error')
            return redirect(self._get_dir_url('.index', path))

        if not self.is_accessible_path(path):
            flash(gettext('Permission denied.'))
            return redirect(self._get_dir_url('.index'))

        form = self.upload_form()

        if helpers.validate_form_on_submit(form):
            filename = op.join(directory,
                               secure_filename(form.upload.data.filename))

            if op.exists(filename):
                flash(gettext('File "%(name)s" already exists.', name=filename),
                      'error')
            else:
                try:
                    self.save_file(filename, form.upload.data)
                    self.on_file_upload(directory, path, filename)
                    flash('%s was correctly uploaded' % form.upload.data.filename)
                    return redirect(self._get_dir_url('.index', path))
                except Exception as ex:
                    flash(gettext('Failed to save file: %(error)s', error=ex))
        elif request.form and 'async' in request.form:
            total_uploaded = 0
            for tmp_filename in json.loads(request.form['async']):
                filename = op.join(directory,
                               secure_filename(form.upload.data.filename))
                if op.exists(filename):
                    total_uploaded = total_uploaded + 1

            if total_uploaded == 0:
                flash('Nothing was uploaded', 'error')
            elif total_uploaded == 1:
                flash('%s was correctly uploaded' % tmp_filename)
                return redirect(self._get_dir_url('.index', path))
            else:
                flash('%d files were correctly uploaded' % total_uploaded)
                return redirect(self._get_dir_url('.index', path))

        return self.render(self.upload_template, form=form, dir_path=path)
示例#11
0
文件: app.py 项目: jf-parent/webbase
    def on_model_change(self, form, model, is_created):
        logger.info("on_model_change")
        with DbSessionContext(config.get('mongo_database_name')) as session:
            try:
                m = importlib.import_module(
                    'server.model.{model}'
                    .format(model=self.name.lower())
                )
                model_class = getattr(m, self.name)

                if not is_created:
                    model_obj = session.query(model_class)\
                        .filter(model_class.mongo_id == model['_id'])\
                        .one()
                else:
                    model_obj = model_class()

                context = {}
                context['db_session'] = session
                context['author'] = login.current_user
                context['data'] = form.data
                context['save'] = True

                loop.run_until_complete(model_obj.validate_and_save(context))

                pk = model_obj.get_uid()
                self.coll.update({'_id': pk}, model)

            except Exception as e:
                if isinstance(e, exceptions.ServerBaseException):
                    flash(
                      gettext(
                        'Failed to update record. %(exception)s(%(error)s)',
                        exception=e.get_name(),
                        error=e
                      ),
                      'error'
                    )
                else:
                    flash(
                        gettext(
                            'Failed to update record. %(error)s',
                            error=e
                        ),
                        'error'
                    )
                return False
            else:
                self.after_model_change(form, model, True)

            return True
示例#12
0
    def action_delete(self, items):
        if not self.can_delete:
            flash(gettext('File deletion is disabled.'), 'error')
            return

        for path in items:
            base_path, full_path, path = self._normalize_path(path)

            if self.is_accessible_path(path):
                try:
                    os.remove(full_path)
                    flash(gettext('File "%(name)s" was successfully deleted.', name=path))
                except Exception as ex:
                    flash(gettext('Failed to delete file: %(name)s', name=ex), 'error')
示例#13
0
    def rename(self):
        """
            Rename view method
        """
        form = self.name_form()

        path = form.path.data
        if path:
            base_path, full_path, path = self._normalize_path(path)

            return_url = self._get_dir_url(".index", op.dirname(path))
        else:
            return redirect(self.get_url(".index"))

        if not self.can_rename:
            flash(gettext("Renaming is disabled."), "error")
            return redirect(return_url)

        if not self.is_accessible_path(path):
            flash(gettext("Permission denied."), "error")
            return redirect(self._get_dir_url(".index"))

        if not op.exists(full_path):
            flash(gettext("Path does not exist."), "error")
            return redirect(return_url)

        if self.validate_form(form):
            try:
                dir_base = op.dirname(full_path)
                filename = secure_filename(form.name.data)

                os.rename(full_path, op.join(dir_base, filename))
                self.on_rename(full_path, dir_base, filename)
                flash(gettext('Successfully renamed "%(src)s" to "%(dst)s"', src=op.basename(path), dst=filename))
            except Exception as ex:
                flash(gettext("Failed to rename: %(error)s", error=ex), "error")

            return redirect(return_url)
        else:
            helpers.flash_errors(form, message="Failed to rename: %(error)s")

        return self.render(
            self.rename_template,
            form=form,
            path=op.dirname(path),
            name=op.basename(path),
            dir_url=return_url,
            modal=request.args.get("modal"),
        )
示例#14
0
    def update_model(self, form, model):
        """
            Update model from form.

            :param form:
                Form instance
            :param model:
                Model instance
        """
        try:
            form.populate_obj(model)
            self._on_model_change(form, model, False)
            self.session.commit()
        except Exception as ex:
            if not self.handle_view_exception(ex):
                flash(gettext("Failed to update record. %(error)s", error=str(ex)), "error")
                log.exception("Failed to update record.")

            self.session.rollback()

            return False
        else:
            self.after_model_change(form, model, False)

        return True
示例#15
0
    def action_delete(self, ids):
        try:
            query = tools.get_query_for_ids(self.get_query(), self.model, ids)

            if self.fast_mass_delete:
                count = query.delete(synchronize_session=False)
            else:
                count = 0

                for m in query.all():
                    if self.delete_model(m):
                        count += 1

            self.session.commit()

            flash(
                ngettext(
                    "Record was successfully deleted.",
                    "%(count)s records were successfully deleted.",
                    count,
                    count=count,
                ),
                "success",
            )
        except Exception as ex:
            if not self.handle_view_exception(ex):
                raise

            flash(gettext("Failed to delete records. %(error)s", error=str(ex)), "error")
示例#16
0
    def create_model(self, form):
        """
            Create model from form.

            :param form:
                Form instance
        """
        try:
            model = self._manager.new_instance()
            # TODO: We need a better way to create model instances and stay compatible with
            # SQLAlchemy __init__() behavior
            state = instance_state(model)
            self._manager.dispatch.init(state, [], {})

            form.populate_obj(model)
            self.session.add(model)
            self._on_model_change(form, model, True)
            self.session.commit()
        except Exception as ex:
            if not self.handle_view_exception(ex):
                flash(gettext('Failed to create record. %(error)s', error=str(ex)), 'error')
                log.exception('Failed to create record.')

            self.session.rollback()

            return False
        else:
            self.after_model_change(form, model, True)

        return model
示例#17
0
    def update_model(self, form, model):
        """
            Update model helper

            :param form:
                Form instance
            :param model:
                Model instance to update
        """
        try:
            form.populate_obj(model)
            self._on_model_change(form, model, False)
            model.save()
        except Exception as ex:
            if not self.handle_view_exception(ex):
                flash(gettext('Failed to update record. %(error)s',
                              error=format_error(ex)),
                      'error')
                log.exception('Failed to update record.')

            return False
        else:
            self.after_model_change(form, model, False)

        return True
示例#18
0
    def modal_crop(self, path):
        """
            Index view method

            :param path:
                Optional directory path. If not provided, will use the base directory
        """
        prev_view_type = request.args.get('pvt', None)
        if prev_view_type != 'list':
            prev_view_type = 'icons'

        # Get path and verify if it is valid
        media_path, full_path, path = self._normalize_path(path)
        parent_path = os.path.dirname(path)

        if not self.is_accessible_path(full_path):
            flash(gettext('Permission denied.'))
            return redirect(self._get_dir_url('.index'))

        width, height = get_image_dimensions(full_path)

        actions, actions_confirmation = self.get_actions_list()

        return self.render(self.crop_modal_template,
                           path=path, dir_path=parent_path,
                           width=width, height=height,
                           prev_view_type=prev_view_type,
                           actions=actions,
                           actions_confirmation=actions_confirmation)
示例#19
0
    def create_model(self, form):
        """
            Create model helper

            :param form:
                Form instance
        """
        try:
            model = self.model()
            form.populate_obj(model)
            self._on_model_change(form, model, True)
            model.save()
        except Exception as ex:
            if self._debug:
                raise

            if not self.handle_view_exception(ex):
                flash(gettext('Failed to create record. %(error)s',
                              error=format_error(ex)),
                      'error')
                log.exception('Failed to create record.')

            return False
        else:
            self.after_model_change(form, model, True)

        return model
示例#20
0
    def delete_model(self, model):
        """
            Delete model.

            :param model:
                Model to delete
        """
        try:
            self.on_model_delete(model)
            self.session.flush()
            self.session.delete(model)
            self.session.commit()
        except Exception as ex:
            if not self.handle_view_exception(ex):
                flash(
                    gettext(
                        'Failed to delete record. %(error)s', error=str(ex)),
                    'error')
                log.exception('Failed to delete record.')

            self.session.rollback()

            return False
        else:
            self.after_model_delete(model)

        return True
示例#21
0
    def action_delete(self, ids):
        try:
            model_pk = getattr(self.model, self._primary_key)

            if self.fast_mass_delete:
                count = self.model.delete().where(model_pk << ids).execute()
            else:
                count = 0

                query = self.model.select().filter(model_pk << ids)

                for m in query:
                    self.on_model_delete(m)
                    m.delete_instance(recursive=True)
                    count += 1

            flash(
                ngettext(
                    "Record was successfully deleted.",
                    "%(count)s records were successfully deleted.",
                    count,
                    count=count,
                )
            )
        except Exception as ex:
            if not self.handle_view_exception(ex):
                flash(gettext("Failed to delete records. %(error)s", error=str(ex)), "error")
示例#22
0
    def create_model(self, form):
        """
            Create model from form.

            :param form:
                Form instance
        """
        try:
            model = self.model()
            form.populate_obj(model)
            self.session.add(model)
            self._on_model_change(form, model, True)
            self.session.commit()
        except Exception as ex:
            if not self.handle_view_exception(ex):
                flash(gettext('Failed to create record. %(error)s', error=str(ex)), 'error')
                log.exception('Failed to create record.')

            self.session.rollback()

            return False
        else:
            self.after_model_change(form, model, True)

        return model
示例#23
0
文件: tracks.py 项目: WorldViews/WVS
 def parse(self, filename):
     if filename.endswith('.gpx'):
         self.parseGPX(filename)
     elif filename.endswith('.json'):
         self.parseJSON(filename)
     else:
         os.remove(filename)
         raise validators.ValidationError(gettext('Unsupported file type.'))
示例#24
0
    def _save_form_files(self, directory, path, form):
        filename = op.join(directory, secure_filename(form.upload.data.filename))

        if op.exists(filename):
            flash(gettext('File "%(name)s" already exists.', name=filename), "error")
        else:
            self.save_file(filename, form.upload.data)
            self.on_file_upload(directory, path, filename)
示例#25
0
    def index(self, path=None):
        """
            Index view method

            :param path:
                Optional directory path. If not provided, will use the base directory
        """
        if self.can_delete:
            delete_form = self.delete_form()
        else:
            delete_form = None

        # Get path and verify if it is valid
        base_path, directory, path = self._normalize_path(path)
        if not self.is_accessible_path(path):
            flash(gettext('Permission denied.'), 'error')
            return redirect(self._get_dir_url('.index'))

        # Get directory listing
        items = []

        # Parent directory
        if directory != base_path:
            parent_path = op.normpath(self._separator.join([path, '..']))
            if parent_path == '.':
                parent_path = None

            items.append(('..', parent_path, True, 0, 0))

        for item in self.storage.get_files(path, directory):
            file_name, rel_path, is_dir, size, last_modified = item
            if self.is_accessible_path(rel_path):
                items.append(item)

        # Sort by name
        items.sort(key=itemgetter(0))

        # Sort by type
        items.sort(key=itemgetter(2), reverse=True)

        # Sort by modified date
        items.sort(key=lambda values: (values[0], values[1], values[2], values[3], datetime.fromtimestamp(values[4])), reverse=True)

        # Generate breadcrumbs
        breadcrumbs = self._get_breadcrumbs(path)

        # Actions
        actions, actions_confirmation = self.get_actions_list()

        return self.render(self.list_template,
                           dir_path=path,
                           breadcrumbs=breadcrumbs,
                           get_dir_url=self._get_dir_url,
                           get_file_url=self._get_file_url,
                           items=items,
                           actions=actions,
                           actions_confirmation=actions_confirmation,
                           delete_form=delete_form)
示例#26
0
    def icon_index(self, path=None):
        # Get path and verify if it is valid
        base_path, directory, path = self._normalize_path(path)

        if not self.is_accessible_path(path):
            flash(gettext('Permission denied.'))
            return redirect(self._get_dir_url('.index'))

        # Get directory listing
        items = []
        mimes = {}

        # Parent directory
        parent_path = None
        if directory != base_path:
            parent_path = op.normpath(op.join(path, '..'))
            if parent_path == '.':
                parent_path = None

        for f in os.listdir(directory):
            fp = op.join(directory, f)
            rel_path = op.join(path, f)

            if self.is_accessible_path(rel_path) and not f.startswith('.'):
                file_size = op.getsize(fp)
                file_size = humanize.naturalsize(file_size, format = '%0.f')
                items.append((f, rel_path, op.isdir(fp), file_size))
                mimes[rel_path] = 'other'
                for mime in self.mime_by_ext:
                    if op.splitext(rel_path)[1].lower() in self.mime_by_ext[mime]:
                        mimes[rel_path] = mime


        # Sort by name
        items.sort(key=itemgetter(0))

        # Sort by type
        items.sort(key=itemgetter(2), reverse=True)

        # Generate breadcrumbs
        accumulator = []
        breadcrumbs = []
        for n in path.split(os.sep):
            accumulator.append(n)
            breadcrumbs.append((n, op.join(*accumulator)))

        # Actions
        actions, actions_confirmation = self.get_actions_list()

        return self.render(self.icon_list_template,
                           dir_path=path, parent_path=parent_path,
                           breadcrumbs=breadcrumbs,
                           get_dir_url=self._get_dir_url,
                           get_file_url=self._get_file_url,
                           items=items,
                           mimes=mimes,
                           actions=actions,
                           actions_confirmation=actions_confirmation)
示例#27
0
    def handle_view_exception(self, exc):
        if isinstance(exc, IntegrityError):
            if current_app.config.get('ADMIN_RAISE_ON_VIEW_EXCEPTION'):
                raise
            else:
                flash(gettext('Integrity error. %(message)s', message=text_type(exc)), 'error')
            return True

        return super(ModelView, self).handle_view_exception(exc)
示例#28
0
    def handle_view_exception(self, exc):
        if isinstance(exc, IntegrityError):
            flash(
                gettext(
                    'Integrity error. %(message)s', message=text_type(exc)),
                'error')
            return True

        return super(ModelView, self).handle_view_exception(exc)
示例#29
0
    def _save_form_files(self, directory, path, form):
        filename = self._separator.join([directory, secure_filename(form.upload.data.filename)])

        if self.storage.path_exists(filename):
            secure_name = self._separator.join([path, secure_filename(form.upload.data.filename)])
            raise Exception(gettext('File "%(name)s" already exists.', name=secure_name))
        else:
            self.save_file(filename, form.upload.data)
            self.on_file_upload(directory, path, filename)
示例#30
0
文件: view.py 项目: hellwen/pyservice
 def delete_model(self, model):
     try:
         self.on_model_delete(model)
         model.delete_instance(recursive=True)
         return True
     except Exception, ex:
         flash(gettext('Failed to delete model. %(error)s', error=str(ex)), 'error')
         logging.exception('Failed to delete model')
         return False
    def _save_form_files(self, directory, path, form):
        filename = op.join(directory,
                           secure_filename(form.upload.data.filename))

        if op.exists(filename):
            flash(gettext('File "%(name)s" already exists.', name=filename),
                  'error')
        else:
            self.save_file(filename, form.upload.data)
            self.on_file_upload(directory, path, filename)
示例#32
0
    def create_model(self, form):
        try:
            model = self.build_new_instance()

            form.populate_obj(model)
            idKH = form.data.get('khach_hang').id
            tongTienThu = float(form.data.get('tong_tien_thu'))
            ngayLapPhieu = form.data.get('ngay_thu_tien')
            suDungQD = QuyDinh.query.value(QuyDinh.tien_thu_khong_vuot_tien_no)

            if suDungQD:
                tongNo = utils.chi_tiet_tien_no_KH(idKH=idKH,
                                                   thang=ngayLapPhieu)

                if tongTienThu <= tongNo:
                    self.session.add(model)
                    self._on_model_change(form, model, True)
                    self.session.commit()
                else:
                    flash(
                        gettext(
                            'THÊM PHIẾU THU TIỀN THẤT BẠI! (SỐ TIỀN THU KHÔNG ĐƯỢC HƠN TỔNG NỢ) '
                        ), 'danger')
                    self.session.rollback()
                    return False
            else:
                self.session.add(model)
                self._on_model_change(form, model, True)
                self.session.commit()
        except Exception as ex:
            if not self.handle_view_exception(ex):
                flash(
                    gettext('GHI THẤT BAI! MỜI KIỂM TRA LẠI. %(error)s',
                            error=str(ex)), 'error')
                log.exception('GHI THẤT BAI! MỜI KIỂM TRA LẠI.')

            self.session.rollback()

            return False
        else:
            self.after_model_change(form, model, True)

        return model
    def mkdir(self, path=None):
        """
            Directory creation view method

            :param path:
                Optional directory path. If not provided, will use the base directory
        """
        # Get path and verify if it is valid
        base_path, directory, path = self._normalize_path(path)

        dir_url = self._get_dir_url('.index', path)

        if not self.can_mkdir:
            flash(gettext('Directory creation is disabled.'), 'error')
            return redirect(dir_url)

        if not self.is_accessible_path(path):
            flash(gettext('Permission denied.'), 'error')
            return redirect(self._get_dir_url('.index'))

        form = self.name_form()

        if self.validate_form(form):
            try:
                os.mkdir(op.join(directory, form.name.data))
                self.on_mkdir(directory, form.name.data)
                flash(
                    gettext('Successfully created directory: %(directory)s',
                            directory=form.name.data))
                return redirect(dir_url)
            except Exception as ex:
                flash(
                    gettext('Failed to create directory: %(error)s', error=ex),
                    'error')
        else:
            helpers.flash_errors(
                form, message='Failed to create directory: %(error)s')

        return self.render(self.mkdir_template,
                           form=form,
                           dir_url=dir_url,
                           header_text=gettext('Create Directory'),
                           modal=request.args.get('modal'))
示例#34
0
文件: view.py 项目: laolu94678/qingmi
    def ajax_update(self):
        """
            Edits a single column of a record in list view.
        """
        if not self.column_editable_list:
            abort(404)

        form = self.list_form()

        # prevent validation issues due to submitting a single field
        # delete all fields except the submitted fields and csrf token
        for field in list(form):
            if (field.name in request.form) or (field.name == 'csrf_token'):
                pass
            else:
                form.__delitem__(field.name)

        if self.validate_form(form):
            pk = form.list_form_pk.data
            record = self.get_one(pk)

            if record is None:
                return gettext('Record does not exist.'), 500

            if self.update_model(form, record):
                # Success
                return gettext('Record was successfully saved.')
            else:
                # Error: No records changed, or problem saving to database.
                msgs = ", ".join([msg for msg in get_flashed_messages()])
                return gettext('Failed to update record. %(error)s',
                               error=msgs), 500
        else:
            for field in form:
                for error in field.errors:
                    # return validation error to x-editable
                    if isinstance(error, list):
                        return gettext('Failed to update record. %(error)s',
                                       error=", ".join(error)), 500
                    else:
                        return gettext('Failed to update record. %(error)s',
                                       error=error), 500
示例#35
0
    def delete(self):
        """
            Delete view method
        """
        form = self.delete_form()

        path = form.path.data
        if path:
            return_url = self._get_dir_url('.index', op.dirname(path))
        else:
            return_url = self.get_url('.index')

        if self.validate_form(form):
            # Get path and verify if it is valid
            base_path, full_path, path = self._normalize_path(path)

            if not self.can_delete:
                flash(gettext('Deletion is disabled.'), 'error')
                return redirect(return_url)

            if not self.is_accessible_path(path):
                flash(gettext('Permission denied.'), 'error')
                return redirect(self._get_dir_url('.index'))

            if op.isdir(full_path):
                if not self.can_delete_dirs:
                    flash(gettext('Directory deletion is disabled.'), 'error')
                    return redirect(return_url)

                try:
                    self.before_directory_delete(full_path, path)
                    shutil.rmtree(full_path)
                    self.on_directory_delete(full_path, path)
                    flash(
                        gettext(
                            'Directory "%(path)s" was successfully deleted.',
                            path=path))
                except Exception as ex:
                    flash(
                        gettext('Failed to delete directory: %(error)s',
                                error=ex), 'error')
            else:
                try:
                    self.before_file_delete(full_path, path)
                    os.remove(full_path)
                    self.on_file_delete(full_path, path)
                    flash(
                        gettext('File "%(name)s" was successfully deleted.',
                                name=path))
                except Exception as ex:
                    flash(gettext('Failed to delete file: %(name)s', name=ex),
                          'error')
        else:
            helpers.flash_errors(form,
                                 message='Failed to delete file. %(error)s')

        return redirect(return_url)
示例#36
0
 def index(self):
     '''
     main route
     '''
     temp_form = BufferForm(request.form)
     if request.method == 'POST':
         if temp_form.buffer.data != "":
             uuid = str(uuid4())
             result = {}
             for item in request.form.getlist("choices"):
                 result.update({item: True})
             filename = ''.join(choice(ascii_uppercase) for _ in range(8))
             savetotemp = path.join(MALWARE_FOLDER, filename) + "._buffer"
             with open(savetotemp, "w") as tempfile:
                 tempfile.write(temp_form.buffer.data)
             with open(savetotemp, "rb") as tempfile:
                 result["file"] = savetotemp
                 result["uuid"] = uuid
                 result["analyzer_timeout"] = temp_form.analyzertimeout.data
                 result["function_timeout"] = temp_form.functiontimeout.data
                 files = Files()
                 files.uuid = uuid
                 files.line = result
                 files.file.put(tempfile,
                                content_type="application/octet-stream",
                                filename=filename)
                 files.save()
                 QUEUE.put(uuid, result)
                 if request.form.get('submitandwait') == 'Submit And Wait':
                     flash(gettext(uuid), 'successandwaituuid')
                 else:
                     flash(
                         gettext(
                             'Done submitting buffer Task {}'.format(uuid)),
                         'success')
         else:
             flash(gettext("Something wrong"), 'error')
     return self.render("upload.html",
                        header="Scan Buffer",
                        table_header="Last 10 Buffers",
                        form=temp_form,
                        recent_files=get_last_files("buffer"))
    def export(self, export_type):
        return_url = get_redirect_target() or self.get_url('.index_view')

        if not self.can_export or (export_type not in self.export_types):
            flash(gettext('Permission denied.'), 'error')
            return redirect(return_url)

        if export_type == 'csv':
            return self._export_csv(return_url)
        else:
            return self._export_tablib(export_type, return_url)
示例#38
0
 def get_list(self,
              page,
              sort_field,
              sort_desc,
              search,
              filters,
              page_size=None):
     bukudb = self.bukudb
     contain_buku_search = any(x[1] == 'buku' for x in filters)
     if contain_buku_search:
         mode_id = [x[0] for x in filters]
         if len(list(set(mode_id))) > 1:
             flash(gettext('Invalid search mode combination'), 'error')
             return 0, []
         keywords = [x[2] for x in filters]
         for idx, flt_name, value in filters:
             if flt_name == 'buku':
                 flt = self._filters[idx]
         bookmarks = bukudb.searchdb(keywords,
                                     all_keywords=flt.all_keywords,
                                     deep=flt.deep,
                                     regex=flt.regex)
     else:
         bookmarks = bukudb.get_rec_all()
     bookmarks = self._apply_filters(bookmarks, filters)
     if sort_field:
         key_idx = [
             x.value for x in BookmarkField if x.name.lower() == sort_field
         ][0]
         bookmarks = sorted(bookmarks,
                            key=lambda x: x[key_idx],
                            reverse=sort_desc)
     count = len(bookmarks)
     if page_size and bookmarks:
         bookmarks = list(chunks(bookmarks, page_size))[page]
     data = []
     for bookmark in bookmarks:
         bm_sns = SimpleNamespace(id=None,
                                  url=None,
                                  title=None,
                                  tags=None,
                                  description=None)
         for field in list(BookmarkField):
             if field == BookmarkField.TAGS:
                 value = bookmark[field.value]
                 if value.startswith(','):
                     value = value[1:]
                 if value.endswith(','):
                     value = value[:-1]
                 setattr(bm_sns, field.name.lower(), value)
             else:
                 setattr(bm_sns, field.name.lower(), bookmark[field.value])
         data.append(bm_sns)
     return count, data
示例#39
0
    def _save_file(self, data, filename):
        path = self._get_path(filename)
        if not op.exists(op.dirname(path)):
            os.makedirs(os.path.dirname(path), self.permission | 0o111)

        if (self._allow_overwrite is False) and os.path.exists(path):
            raise ValueError(gettext('File "%s" already exists.' % path))

        data.save(path)

        return filename
示例#40
0
    def handle_view_exception(self, exc):
        if isinstance(exc, IntegrityError):
            if current_app.config.get('ADMIN_RAISE_ON_VIEW_EXCEPTION'):
                raise
            else:
                flash(
                    gettext('Integrity error. %(message)s',
                            message=text_type(exc)), 'error')
            return True

        return super(ModelView, self).handle_view_exception(exc)
示例#41
0
def _export(obj, export_type):
    return_url = get_redirect_target() or obj.get_url('.index_view')

    if not obj.can_export or (export_type not in obj.export_types):
        flash(gettext('Permission denied.'), 'error')
        return redirect(return_url)

    if export_type == 'csv':
        return obj._export_csv(return_url)
    else:
        return _export_fields(obj, export_type, return_url)
示例#42
0
    def convert(self):
        result = super(AjaxModalAction, self).convert()
        btn = self.btn
        if self.btn is True:
            if self.form:
                btn = [gettext('Save'), gettext('Cancel')]
            else:
                btn = [gettext('Done')]

        result.update({
            'ajax': False,
            'data': {
                'modal': True,
                'url': self.url,
                'title': self.modal_title,
                'form': bool(self.form),
                'btn': btn
            }
        })
        return result
示例#43
0
 def index(self):
     # handle user login
     form = UploadForm(request.form)
     if request.method == 'POST':
         uploaded_files = request.files.getlist("file")
         for file in uploaded_files:
             filename = ""
             uuid = str(uuid4())
             if file:
                 result = {}
                 filename = secure_filename(file.filename)
                 savetotemp = path.join(gettempdir(),filename)
                 for x in request.form.getlist("choices"):
                     result.update({x:True})
                 result["file"] = savetotemp
                 result["uuid"] = uuid
                 result["analyzer_timeout"]= form.analyzertimeout.data
                 result["function_timeout"]= form.functiontimeout.data
                 files = Files()
                 files.uuid = uuid
                 files.line = result
                 #form.populate_obj(files)
                 #save to db
                 files.file.put(file, content_type=file.content_type, filename=filename)
                 files.save()
                 #save to hdd
                 file.seek(0)
                 file.save(savetotemp)
                 #q_return = queue.insert(uuid,result)
                 jobs = Jobs()
                 jobs.jobID = uuid
                 jobs.status = 'wait'
                 jobs.created = datetime.now()
                 jobs.started = datetime.now()
                 jobs.finished = datetime.now()
                 jobs.data = result
                 jobs.save()
                 flash(gettext("Done uploading {} Task ({})".format(filename,uuid)), 'success')
             else:
                 flash(gettext("Something wrong while uploading {} Task ({})".format(filename,uuid)), 'error')
     return self.render("fileupload.html",form=form)
示例#44
0
文件: views.py 项目: ye-man/Buku
 def delete_model(self, model):
     try:
         self.on_model_delete(model)
         res = self.bukudb.delete_rec(model.id)
     except Exception as ex:
         if not self.handle_view_exception(ex):
             flash(gettext('Failed to delete record. %(error)s', error=str(ex)), 'error')
             LOG.exception('Failed to delete record.')
         return False
     else:
         self.after_model_delete(model)
     return res
示例#45
0
 def user_redirect_view(self):
     id = get_mdict_item_or_list(request.args, 'id')
     if id:
         server = self.get_one(id)
         if server:
             return redirect(
                 url_for('admin/users.edit_view',
                         id=server.admin_c.id,
                         url=self.get_url('.index_view')))
         else:
             flash(gettext('Does not exist.'), 'error')
             return redirect(return_url)
示例#46
0
 def on_model_change(self, form, model, is_created):
     invalid = []
     for service in model.quick_list:
         if service not in model.services:
             invalid.append(str(service))
             model.quick_list.remove(service)
     if len(invalid) != 0:
         message = ", ".join(invalid)
         flash(
             gettext(
                 "Services saved minus services not offered at this office: "
                 + message), 'warning')
示例#47
0
    def create_model(self, form):
        data = form.data
        data['node_pubkey_string'] = data['node_pubkey_string'].pub_key
        try:
            response = self.ln.open_channel(**data)
        except Exception as exc:
            if hasattr(exc, '_state'):
                flash(gettext(exc._state.details), 'error')
            else:
                flash(gettext(str(exc)))
            return False

        if response.code() == StatusCode.UNKNOWN:
            flash(gettext(response._state.details), 'error')
            return False
        else:
            new_channel = [
                c for c in self.ln.get_channels()
                if c.remote_pubkey == data['node_pubkey_string']
            ][0]
            return new_channel
示例#48
0
    def _save_form_files(self, directory, path, form):
        filename = op.join(directory,
                           secure_filename(form.upload.data.filename))

        if op.exists(filename):
            secure_name = op.join(path,
                                  secure_filename(form.upload.data.filename))
            raise Exception(
                gettext('File "%(name)s" already exists.', name=secure_name))
        else:
            self.save_file(filename, form.upload.data)
            self.on_file_upload(directory, path, filename)
 def create_model(self, form):
     if form.data.get('pubkey_at_host'):
         pubkey = form.data.get('pubkey_at_host').split('@')[0]
         host = form.data.get('pubkey_at_host').split('@')[1]
     else:
         pubkey = form.data.get('pubkey')
         host = form.data.get('host')
     try:
         self.ln.connect(pubkey=pubkey, host=host)
     except Exception as exc:
         flash(gettext(exc._state.details), 'error')
     return
示例#50
0
    def _save_form_files(self, directory, path, form):
        filename = self._separator.join(
            [directory, secure_filename(form.upload.data.filename)])

        if self.storage.path_exists(filename):
            secure_name = self._separator.join(
                [path, secure_filename(form.upload.data.filename)])
            raise Exception(
                gettext('File "%(name)s" already exists.', name=secure_name))
        else:
            self.save_file(filename, form.upload.data)
            self.on_file_upload(directory, path, filename)
示例#51
0
 def _tag_view_base(self, mode):
     return_url = get_redirect_target() or self.get_url('.index_view')
     id = get_mdict_item_or_list(request.args, 'id')
     if id is None:
         return redirect(return_url)
     model = self.get_one(id)
     if model is None:
         flash(gettext('Record does not exist.'), 'error')
         return redirect(return_url)
     if mode not in [models.MODE_PLAUSIBLE_TAG, models.MODE_TOP_TAG]:
         flash(gettext('Unknown mode.'), 'error')
         return redirect(return_url)
     estimated_tags = model.checksum.get_estimated_tags(mode=mode)
     if not any(estimated_tags.values()):
         img = Image.open(model.full_path)
         start_time = time.time()
         global ILLUST2VEC
         if not ILLUST2VEC:
             ILLUST2VEC = make_i2v_with_chainer(
                 "illust2vec_tag_ver200.caffemodel", "tag_list.json")
         illust2vec = ILLUST2VEC
         end = time.time()
         logger.debug('i2v initiated', time=(time.time() - start_time))
         if mode == models.MODE_PLAUSIBLE_TAG:
             res = illust2vec.estimate_plausible_tags([img])
         else:
             res = illust2vec.estimate_top_tags([img])
         res = res[0]
         session = models.db.session
         tags = list(
             model.checksum.update_tag_estimation(res,
                                                  mode=mode,
                                                  session=session))
         list(map(session.add, tags))
         session.commit()
     estimated_tags = model.checksum.get_estimated_tags(mode=mode)
     return self.render('i2v/image_tag.html',
                        estimated_tags=estimated_tags,
                        model=model,
                        mode=mode)
示例#52
0
    def create_model(self, form):
        try:
            getDate = lambda x: f'{x.year}{x.month}{x.day}{x.hour}{x.minute}{x.second}'
            if request.files["image"]:
                s3.upload_to_aws(
                    request.files["image"],
                    current_app.config.get('S3_BUCKET_NAME'),
                    'products/' + getDate(datetime.utcnow()) + '.png')

                # # Create Stripe product
                # product = stripe.Product.create(
                #   name=form.name.data,
                #   type='good',
                #   attributes=['name'],
                #   description=form.description.data,
                #   images=[file_upload],
                # )

                # # Create SKU for Stripe product
                # sku = stripe.SKU.create(
                #   product=product.id,
                #   attributes={'name': product.name},
                #   price=int(form.price.data * 100),
                #   currency='usd',
                #   image=product.images[0],
                #   inventory={'type': 'infinite'}
                # )

                # # Create database product
                # p = Product(
                #   id_=product.id,
                #   sku=sku.id,
                #   name=product.name,
                #   image=product.images[0],
                #   price=form.price.data,
                #   active=product.active,
                #   created=datetime.fromtimestamp(product.created),
                #   description=product.description,
                #   object_=product.type,
                #   url=product.url
                # )
                # db.session.add(p)
                # db.session.commit()
        except Exception as ex:
            if not self.handle_view_exception(ex):
                flash(
                    gettext('Failed to create record. %(error)s',
                            error=str(ex)), 'error')
                log.exception('Failed to create record.')
            self.session.rollback()
            return False
        return True
示例#53
0
    def __call__(self, field, **kwargs):
        kwargs.setdefault('data-role', 'select2-ajax')

        # field의 options로 정의된 param들을 data-url에 붙여준다.
        # 추후필요에 따라 data-url자체를 재정의할 수 있는 방법도 제공해주면 좋겠다.
        url = get_url('portal.ajax_model_lookup',
                      name=field.loader.name,
                      querym=json.dumps(field.options))
        kwargs.setdefault('data-url', url)
        # kwargs.setdefault('data-url', field.loader.data_url)

        allow_blank = getattr(field, 'allow_blank', False)
        if allow_blank and not self.multiple:
            kwargs['data-allow-blank'] = u'1'

        kwargs.setdefault('id', field.id)
        kwargs.setdefault('type', 'hidden')

        options_string = []
        if self.multiple:
            result = []
            ids = []

            for value in field.data:
                data = field.loader.format(value)
                options_string.append(
                    HTMLString('<option %s>%s</option>' %
                               (html_params(value=data[0]), data[1])))
                result.append(data)
                ids.append(as_unicode(data[0]))

            separator = getattr(field, 'separator', ',')

            kwargs['value'] = separator.join(ids)
            kwargs['data-json'] = json.dumps(result)
            kwargs['data-multiple'] = u'1'
        else:
            data = field.loader.format(field.data)

            if data:
                options_string.append(
                    HTMLString('<option %s>%s</option>' %
                               (html_params(value=data[0]), data[1])))
                kwargs['value'] = data[0]
                kwargs['data-json'] = json.dumps(data)

        placeholder = gettext(
            field.loader.options.get('placeholder', 'Please select model'))
        kwargs.setdefault('data-placeholder', placeholder)

        return HTMLString('<select %s>%s</select>' % (html_params(
            name=field.name, **kwargs), '\n'.join(options_string)))
示例#54
0
    def edit_view(self):
        """
            Edit model view
        """
        return_url = self.get_return_url()
        model = self.validate_model()

        if not model:
            return redirect(return_url)

        csr_id = get_mdict_item_or_list(request.args, 'id')

        form = self.edit_form(obj=model)
        if not hasattr(form,
                       '_validated_ruleset') or not form._validated_ruleset:
            self._validate_form_instance(ruleset=self._form_edit_rules,
                                         form=form)

        if self.validate_form(form) and self.update_model(form, model):

            #  Trim the user name, if necessary.
            updated_csr = CSR.query.filter_by(csr_id=csr_id).first()

            check_uservalues(updated_csr)

            socketio.emit('clear_csr_cache', {"id": csr_id})
            socketio.emit('csr_update', {
                "csr_id": csr_id,
                "receptionist_ind": updated_csr.receptionist_ind
            },
                          room=current_user.office_id)

            flash(gettext('''Record was successfully saved.'''), 'success')

            request_redirect(self, return_url, model, request)

        if request.method == 'GET' or form.errors:
            self.on_form_prefill(form, id)

        form_opts = FormOpts(widget_args=self.form_widget_args,
                             form_rules=self._form_edit_rules)

        if self.edit_modal and request.args.get('modal'):
            template = self.edit_modal_template
        else:
            template = self.edit_template

        return self.render(template,
                           model=model,
                           form=form,
                           form_opts=form_opts,
                           return_url=return_url)
示例#55
0
文件: views.py 项目: ye-man/Buku
 def delete_model(self, model):
     res = None
     try:
         self.on_model_delete(model)
         res = self.bukudb.delete_tag_at_index(0, model.name, chatty=False)
     except Exception as ex:
         if not self.handle_view_exception(ex):
             flash(gettext('Failed to delete record. %(error)s', error=str(ex)), 'error')
             LOG.exception('Failed to delete record.')
         return False
     else:
         self.after_model_delete(model)
     return res
示例#56
0
    def delete_model(self, model):
        try:
            self.on_model_delete(model)
            model.delete_instance(recursive=True)
            return True
        except Exception as ex:
            if not self.handle_view_exception(ex):
                flash(
                    gettext('Failed to delete record. %(error)s',
                            error=str(ex)), 'error')
                log.exception('Failed to delete record.')

            return False
示例#57
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)
    def _export_tablib(self, export_type, return_url):
        """
            Exports a variety of formats using the tablib library.
        """
        if tablib is None:
            flash(gettext('Tablib dependency not installed.'), 'error')
            return redirect(return_url)

        filename = self.get_export_name(export_type)

        disposition = 'attachment;filename=%s' % (secure_filename(filename),)

        mimetype, encoding = mimetypes.guess_type(filename)
        if not mimetype:
            mimetype = 'application/octet-stream'
        if encoding:
            mimetype = '%s; charset=%s' % (mimetype, encoding)

        ds = tablib.Dataset(headers=[c[0] for c in self._export_columns])
        count, data = self._export_data()

        for row in data:
            vals = [self.get_export_value(row, c[0]) for c in self._export_columns]
            ds.append(vals)
        try:
            try:
                response_data = ds.export(format=export_type)
            except AttributeError:
                response_data = getattr(ds, export_type)
        except (AttributeError, tablib.UnsupportedFormat):
            flash(gettext('Export type "%(type)s not supported.',
                          type=export_type), 'error')
            return redirect(return_url)

        return Response(
            response_data,
            headers={'Content-Disposition': disposition},
            mimetype=mimetype,
        )
示例#59
0
    def upload(self, path=None):
        """
            Upload view method

            :param path:
                Optional directory path. If not provided, will use the base directory
        """
        # Get path and verify if it is valid
        base_path, directory, path = self._normalize_path(path)

        if not self.can_upload:
            flash(gettext('File uploading is disabled.'), 'error')
            return redirect(self._get_dir_url('.index_view', path))

        if not self.is_accessible_path(path):
            flash(gettext('Permission denied.'), 'error')
            return redirect(self._get_dir_url('.index_view'))

        form = self.upload_form(directory)
        if self.validate_form(form):
            try:
                self._save_form_files(directory, path, form)
                flash(
                    gettext('Successfully saved file: %(name)s',
                            name=form.upload.data.filename), 'success')
                return redirect(self._get_dir_url('.index_view', path))
            except Exception as ex:
                flash(gettext('Failed to save file: %(error)s', error=ex),
                      'error')

        if self.upload_modal and request.args.get('modal'):
            template = self.upload_modal_template
        else:
            template = self.upload_template

        return self.render(template,
                           form=form,
                           header_text=gettext('Upload File'),
                           modal=request.args.get('modal'))
示例#60
0
文件: app.py 项目: dpdi-unifor/seed
def marshmallow_errors():
    """
    Static list of validation errors keys used in marshmallow, required in order
    to extract messages by pybabel
    """
    gettext('Missing data for required field.')
    gettext('Not a valid integer.')
    gettext('Not a valid datetime.')