Example #1
0
File: views.py Project: endsh/chiki
class BaseView(with_metaclass(CoolAdminMeta, _BaseView)):
    """ 基础视图 """

    def is_accessible(self):
        if current_user.root is True:
            return current_user.root
        if current_user.group:
            return self.__class__.__name__ in current_user.group.power_list
        return False

    def inaccessible_callback(self, name, **kwargs):
        flash('暂无操作权限!')
        return self.render('admin/power.html')
Example #2
0
File: views.py Project: endsh/chiki
class AdminIndexView(with_metaclass(CoolAdminMeta, _AdminIndexView)):
    """ 仪表盘 """

    MENU_ICON = 'diamond'

    def is_accessible(self):
        if current_user.root is True:
            return current_user.root
        if current_user.group:
            return self.__class__.__name__ in current_user.group.power_list
        return False

    def inaccessible_callback(self, name, **kwargs):
        return redirect('/admin/user')
Example #3
0
class BaseView(with_metaclass(AdminViewMeta, BaseViewClass)):
    """
        Base administrative view.

        Derive from this class to implement your administrative interface piece. For example::

            class MyView(BaseView):
                @expose('/')
                def index(self):
                    return 'Hello World!'
    """
    @property
    def _template_args(self):
        """
            Extra template arguments.

            If you need to pass some extra parameters to the template,
            you can override particular view function, contribute
            arguments you want to pass to the template and call parent view.

            These arguments are local for this request and will be discarded
            in the next request.

            Any value passed through ``_template_args`` will override whatever
            parent view function passed to the template.

            For example::

                class MyAdmin(ModelView):
                    @expose('/')
                    def index(self):
                        self._template_args['name'] = 'foobar'
                        self._template_args['code'] = '12345'
                        super(MyAdmin, self).index()
        """
        args = getattr(g, '_admin_template_args', None)

        if args is None:
            args = g._admin_template_args = dict()

        return args

    def __init__(self, name=None, category=None, endpoint=None, url=None,
                 static_folder=None, static_url_path=None):
        """
            Constructor.

            :param name:
                Name of this view. If not provided, will default to the class name.
            :param category:
                View category. If not provided, this view will be shown as a top-level menu item. Otherwise, it will
                be in a submenu.
            :param endpoint:
                Base endpoint name for the view. For example, if there's a view method called "index" and
                endpoint is set to "myadmin", you can use `url_for('myadmin.index')` to get the URL to the
                view method. Defaults to the class name in lower case.
            :param url:
                Base URL. If provided, affects how URLs are generated. For example, if the url parameter
                is "test", the resulting URL will look like "/admin/test/". If not provided, will
                use endpoint as a base url. However, if URL starts with '/', absolute path is assumed
                and '/admin/' prefix won't be applied.
            :param static_url_path:
                Static URL Path. If provided, this specifies the path to the static url directory.
            :param debug:
                Optional debug flag. If set to `True`, will rethrow exceptions in some cases, so Werkzeug
                debugger can catch them.
        """
        self.name = name
        self.category = category
        self.endpoint = endpoint
        self.url = url
        self.static_folder = static_folder
        self.static_url_path = static_url_path

        # Initialized from create_blueprint
        self.admin = None
        self.blueprint = None

        # Default view
        if self._default_view is None:
            raise Exception(u'Attempted to instantiate admin view %s without default view' % self.__class__.__name__)

    def create_blueprint(self, admin):
        """
            Create Flask blueprint.
        """
        # Store admin instance
        self.admin = admin

        # If endpoint name is not provided, get it from the class name
        if self.endpoint is None:
            self.endpoint = self.__class__.__name__.lower()

        # If the static_url_path is not provided, use the admin's
        if not self.static_url_path:
            self.static_url_path = admin.static_url_path

        # If url is not provided, generate it from endpoint name
        if self.url is None:
            if self.admin.url != '/':
                self.url = '%s/%s' % (self.admin.url, self.endpoint)
            else:
                if self == admin.index_view:
                    self.url = '/'
                else:
                    self.url = '/%s' % self.endpoint
        else:
            if not self.url.startswith('/'):
                self.url = '%s/%s' % (self.admin.url, self.url)

        # If we're working from the root of the site, set prefix to None
        if self.url == '/':
            self.url = None

        # If name is not povided, use capitalized endpoint name
        if self.name is None:
            self.name = self._prettify_name(self.__class__.__name__)

        # Create blueprint and register rules
        self.blueprint = Blueprint(self.endpoint, __name__,
                                   url_prefix=self.url,
                                   subdomain=self.admin.subdomain,
                                   template_folder='templates',
                                   static_folder=self.static_folder,
                                   static_url_path=self.static_url_path)

        for url, name, methods in self._urls:
            self.blueprint.add_url_rule(url,
                                        name,
                                        getattr(self, name),
                                        methods=methods)

        return self.blueprint

    def render(self, template, **kwargs):
        """
            Render template

            :param template:
                Template path to render
            :param kwargs:
                Template arguments
        """
        # Store self as admin_view
        kwargs['admin_view'] = self
        kwargs['admin_base_template'] = self.admin.base_template

        # Provide i18n support even if flask-babel is not installed
        # or enabled.
        kwargs['_gettext'] = babel.gettext
        kwargs['_ngettext'] = babel.ngettext
        kwargs['h'] = h

        # Contribute extra arguments
        kwargs.update(self._template_args)

        return render_template(template, **kwargs)

    def _prettify_name(self, name):
        """
            Prettify a class name by splitting the name on capitalized characters. So, 'MySuperClass' becomes 'My Super Class'

            :param name:
                String to prettify
        """
        return sub(r'(?<=.)([A-Z])', r' \1', name)

    def is_visible(self):
        """
            Override this method if you want dynamically hide or show administrative views
            from Flask-Admin menu structure

            By default, item is visible in menu.

            Please note that item should be both visible and accessible to be displayed in menu.
        """
        return True

    def is_accessible(self):
        """
            Override this method to add permission checks.

            Flask-Admin does not make any assumptions about the authentication system used in your application, so it is
            up to you to implement it.

            By default, it will allow access for everyone.
        """
        return True

    def _handle_view(self, name, **kwargs):
        """
            This method will be executed before calling any view method.

            By default, it will check if the admin class is accessible and if it is not it will
            throw HTTP 404 error.

            :param name:
                View function name
            :param kwargs:
                View function arguments
        """
        if not self.is_accessible():
            return abort(403)

    @property
    def _debug(self):
        if not self.admin or not self.admin.app:
            return False

        return self.admin.app.debug
Example #4
0
class ModelView(with_metaclass(CoolAdminMeta, _ModelView)):

    page_size = 50
    can_view_details = True
    details_modal = True
    edit_modal = True
    model_form_converter = KModelConverter
    filter_converter = KFilterConverter()

    column_type_formatters = _ModelView.column_type_formatters or dict()
    column_type_formatters[datetime] = type_best
    column_type_formatters[FileProxy] = type_file

    show_popover = False
    robot_filters = False

    def __init__(self,
                 model,
                 name=None,
                 category=None,
                 endpoint=None,
                 url=None,
                 static_folder=None,
                 menu_class_name=None,
                 menu_icon_type=None,
                 menu_icon_value=None):

        self.column_formatters = dict(self.column_formatters or dict())

        # 初始化标识
        self.column_labels = self.column_labels or dict()
        self.column_labels.setdefault('id', 'ID')
        for field in model._fields:
            if field not in self.column_labels:
                attr = getattr(model, field)
                if hasattr(attr, 'verbose_name'):
                    verbose_name = attr.verbose_name
                    if verbose_name:
                        self.column_labels[field] = verbose_name

        #初始化筛选器
        types = (IntField, ReferenceField, StringField, BooleanField,
                 DateTimeField) if self.robot_filters else (ReferenceField, )
        self.column_filters = list(self.column_filters or [])

        primary = False
        for field in model._fields:
            attr = getattr(model, field)
            if hasattr(attr, 'primary_key'):
                if attr.primary_key is True:
                    self.column_filters = [field] + self.column_filters
                    primary = True
            elif type(attr) in types and attr.name not in self.column_filters:
                self.column_filters.append(attr.name)
        if not primary:
            self.column_filters = ['id'] + self.column_filters

        if self.robot_filters:
            self.column_filters = filter_sort(self.column_filters,
                                              self.column_list)

        #初始化类型格式化
        for field in model._fields:
            attr = getattr(model, field)
            if type(attr) == StringField:
                self.column_formatters.setdefault(attr.name, formatter_len(40))

        self.form_ajax_refs = self.form_ajax_refs or dict()
        for field in model._fields:
            attr = getattr(model, field)
            if type(attr) == ReferenceField:
                if field not in self.form_ajax_refs and hasattr(
                        attr.document_type, 'ajax_ref'):
                    self.form_ajax_refs[field] = dict(
                        fields=attr.document_type.ajax_ref, page_size=20)

        if not self.column_default_sort and 'created' in model._fields:
            self.column_default_sort = ('-created', )

        self._init_referenced = False

        super(ModelView, self).__init__(model,
                                        name,
                                        category,
                                        endpoint,
                                        url,
                                        static_folder,
                                        menu_class_name=menu_class_name,
                                        menu_icon_type=menu_icon_type,
                                        menu_icon_value=menu_icon_value)

    def _refresh_cache(self):
        self.column_choices = self.column_choices or dict()
        for field in self.model._fields:
            choices = getattr(self.model, field).choices
            if choices:
                self.column_choices[field] = choices
        super(ModelView, self)._refresh_cache()

    def _process_ajax_references(self):
        references = BaseModelView._process_ajax_references(self)
        return process_ajax_references(references, self)

    def create_model(self, form):
        try:
            model = self.model()
            self.pre_model_change(form, model, True)
            form.populate_obj(model)
            self._on_model_change(form, model, True)
            model.save()
        except Exception as ex:
            current_app.logger.error(ex)
            if not self.handle_view_exception(ex):
                flash(
                    'Failed to create record. %(error)s' %
                    dict(error=format_error(ex)), 'error')
            return False
        else:
            self.after_model_change(form, model, True)

        return True

    def update_model(self, form, model):
        try:
            self.pre_model_change(form, model, False)
            form.populate_obj(model)
            self._on_model_change(form, model, False)
            model.save()
        except Exception as ex:
            current_app.logger.error(ex)
            if not self.handle_view_exception(ex):
                flash(
                    'Failed to update record. %(error)s' %
                    dict(error=format_error(ex)), 'error')
            return False
        else:
            self.after_model_change(form, model, False)

        return True

    def pre_model_change(self, form, model, created=False):
        pass

    def on_model_change(self, form, model, created=False):
        if created is True and hasattr(model, 'create'):
            if callable(model.create):
                model.create()
        elif hasattr(model, 'modified'):
            model.modified = datetime.now()

    # @expose('/')
    # def index_view(self):
    #     res = super(ModelView, self).index_view()
    #     gc.collect()
    #     return res

    def get_ref_type(self, attr):
        document, ref_type = attr.document_type, None
        if hasattr(document, 'id'):
            xattr = document._fields.get('id')
            if isinstance(xattr, IntField) or isinstance(xattr, LongField):
                ref_type = int
            elif isinstance(xattr, DecimalField) or isinstance(
                    xattr, FloatField):
                ref_type = float
            elif isinstance(xattr, ObjectIdField):
                ref_type = ObjectId
        return ref_type

    def scaffold_filters(self, name):
        if isinstance(name, string_types):
            attr = self.model._fields.get(name)
        else:
            attr = name

        if attr is None:
            raise Exception('Failed to find field for filter: %s' % name)

        # Find name
        visible_name = None

        if not isinstance(name, string_types):
            visible_name = self.get_column_name(attr.name)

        if not visible_name:
            visible_name = self.get_column_name(name)

        # Convert filter
        type_name = type(attr).__name__
        if isinstance(attr, ReferenceField):
            ref_type = self.get_ref_type(attr)
            flt = self.filter_converter.convert(type_name, attr, visible_name,
                                                ref_type)
        elif isinstance(attr, ListField) and isinstance(
                attr.field, ReferenceField):
            ref_type = self.get_ref_type(attr.field)
            flt = self.filter_converter.convert(type_name, attr, visible_name,
                                                ref_type)
        elif isinstance(attr, ObjectIdField):
            flt = self.filter_converter.convert(type_name, attr, visible_name,
                                                ObjectId)
        else:
            flt = self.filter_converter.convert(type_name, attr, visible_name)

        return flt

    def get_list(self,
                 page,
                 sort_column,
                 sort_desc,
                 search,
                 filters,
                 execute=True,
                 page_size=None):
        query = self.get_query()
        if self._filters:
            for flt, flt_name, value in filters:
                f = self._filters[flt]
                query = f.apply(query, f.clean(value))

        if self._search_supported and search:
            query = self._search(query, search)

        count = query.count() if not self.simple_list_pager else None

        if sort_column:
            query = query.order_by('%s%s' %
                                   ('-' if sort_desc else '', sort_column))
        else:
            order = self._get_default_order()
            if order:
                if len(order) <= 1 or order[1] is not True and order[
                        1] is not False:
                    query = query.order_by(*order)
                else:
                    query = query.order_by('%s%s' %
                                           ('-' if order[1] else '', order[0]))

        if page_size is None:
            page_size = self.page_size

        if page_size:
            query = query.limit(page_size)

        if page and page_size:
            query = query.skip(page * page_size)

        if execute:
            query = query.all()

        return count, query

    def get_filter_tpl(self, attr):
        for view in self.admin._views:
            if hasattr(
                    view, 'model'
            ) and attr.document_type == view.model and view._filter_args:
                for idx, flt in view._filter_args.itervalues():
                    if type(flt) == ObjectIdEqualFilter:
                        return ('/admin/%s/?flt0_' %
                                view.model.__name__.lower()) + str(idx) + '=%s'
                    if flt.column.primary_key:
                        cls = type(flt).__name__
                        if 'EqualFilter' in cls and 'Not' not in cls:
                            return (
                                '/admin/%s/?flt0_' %
                                view.model.__name__.lower()) + str(idx) + '=%s'

    def set_filter_formatter(self, attr):
        def formatter(tpl, name):
            return lambda m: (getattr(m, name), tpl % str(
                getattr(m, name).id if getattr(m, name) else ''))

        tpl = self.get_filter_tpl(attr)
        if tpl:
            f = formatter_link(formatter(tpl, attr.name))
            self.column_formatters.setdefault(attr.name, f)

    def init_referenced(self):
        #初始化类型格式化
        for field in self.model._fields:
            attr = getattr(self.model, field)
            if type(attr) == ReferenceField:
                self.set_filter_formatter(attr)

    @contextfunction
    def get_list_value(self, context, model, name):
        if not self._init_referenced:
            self._init_referenced = True
            self.init_referenced()

        column_fmt = self.column_formatters.get(name)
        if column_fmt is not None:
            try:
                value = column_fmt(self, context, model, name)
            except:
                current_app.logger.error(traceback.format_exc())
                value = '该对象被删了'
        else:
            value = self._get_field_value(model, name)

        #获取choice
        choices_map = self._column_choices_map.get(name, {})
        if choices_map:
            return type_select(self, value, model, name, choices_map) or value

        if isinstance(value, bool):
            return type_bool(self, value, model, name)

        if value and isinstance(value, list) and isinstance(
                value[0], ImageProxy):
            self.show_popover = True
            return type_images(self, value)

        type_fmt = None
        for typeobj, formatter in self.column_type_formatters.items():
            if isinstance(value, typeobj):
                type_fmt = formatter
                break
        if type_fmt is not None:
            try:
                value = type_fmt(self, value)
            except:
                current_app.logger.error(traceback.format_exc())
                value = '该对象被删了'

        return value

    @action('delete', lazy_gettext('Delete'),
            lazy_gettext('Are you sure you want to delete selected records?'))
    def action_delete(self, ids):
        try:
            count = 0

            id = self.model._meta['id_field']
            if id in self.model._fields:
                if isinstance(self.model._fields[id], IntField):
                    all_ids = [int(pk) for pk in ids]
                elif isinstance(self.model._fields[id], StringField):
                    all_ids = ids
                else:
                    all_ids = [self.object_id_converter(pk) for pk in ids]
            else:
                all_ids = [self.object_id_converter(pk) for pk in ids]

            for obj in self.get_query().in_bulk(all_ids).values():
                count += self.delete_model(obj)

            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')

    def on_field_change(self, model, name, value):
        model[name] = value
        if hasattr(model, 'modified'):
            model['modified'] = datetime.now()

    @expose('/dropdown')
    def dropdown(self):
        id = request.args.get('id', 0, unicode)
        val = request.args.get('key', '')
        name = request.args.get('name', '', unicode)
        value = request.args.get('value', '', unicode)
        model = self.model

        if not val:
            val = False if value == 'False' else True
        if type(val) == int:
            val = int(val)

        obj = model.objects(id=id).first()
        if obj:
            self.on_field_change(obj, name, val)
            obj.save()
            return json_success()

        return json_error(msg='该记录不存在')

    def get_field_type(self, field):
        if hasattr(self.model, field):
            return type(getattr(self.model, field)).__name__
        return 'LabelField'

    def _create_ajax_loader(self, name, opts):
        return create_ajax_loader(self.model, name, name, opts)
Example #5
0
class BaseView(with_metaclass(CoolAdminMeta, _BaseView)):
    """ 基础视图 """
Example #6
0
class AdminIndexView(with_metaclass(CoolAdminMeta, _AdminIndexView)):
    """ 仪表盘 """

    MENU_ICON = 'diamond'
Example #7
0
class BaseView(with_metaclass(AdminViewMeta, BaseViewClass)):
    """
        Base administrative view.

        Derive from this class to implement your administrative interface piece. For example::

            from flask.ext.admin import BaseView, expose
            class MyView(BaseView):
                @expose('/')
                def index(self):
                    return 'Hello World!'

        Icons can be added to the menu by using `menu_icon_type` and `menu_icon_value`. For example::

            admin.add_view(MyView(name='My View', menu_icon_type='glyph', menu_icon_value='glyphicon-home'))
    """
    @property
    def _template_args(self):
        """
            Extra template arguments.

            If you need to pass some extra parameters to the template,
            you can override particular view function, contribute
            arguments you want to pass to the template and call parent view.

            These arguments are local for this request and will be discarded
            in the next request.

            Any value passed through ``_template_args`` will override whatever
            parent view function passed to the template.

            For example::

                class MyAdmin(ModelView):
                    @expose('/')
                    def index(self):
                        self._template_args['name'] = 'foobar'
                        self._template_args['code'] = '12345'
                        super(MyAdmin, self).index()
        """
        args = getattr(g, '_admin_template_args', None)

        if args is None:
            args = g._admin_template_args = dict()

        return args

    def __init__(self, name=None, category=None, endpoint=None, url=None,
                 static_folder=None, static_url_path=None,
                 menu_class_name=None, menu_icon_type=None, menu_icon_value=None):
        """
            Constructor.

            :param name:
                Name of this view. If not provided, will default to the class name.
            :param category:
                View category. If not provided, this view will be shown as a top-level menu item. Otherwise, it will
                be in a submenu.
            :param endpoint:
                Base endpoint name for the view. For example, if there's a view method called "index" and
                endpoint is set to "myadmin", you can use `url_for('myadmin.index')` to get the URL to the
                view method. Defaults to the class name in lower case.
            :param url:
                Base URL. If provided, affects how URLs are generated. For example, if the url parameter
                is "test", the resulting URL will look like "/admin/test/". If not provided, will
                use endpoint as a base url. However, if URL starts with '/', absolute path is assumed
                and '/admin/' prefix won't be applied.
            :param static_url_path:
                Static URL Path. If provided, this specifies the path to the static url directory.
            :param menu_class_name:
                Optional class name for the menu item.
            :param menu_icon_type:
                Optional icon. Possible icon types:

                 - `flask.ext.admin.consts.ICON_TYPE_GLYPH` - Bootstrap glyph icon
                 - `flask.ext.admin.consts.ICON_TYPE_IMAGE` - Image relative to Flask static directory
                 - `flask.ext.admin.consts.ICON_TYPE_IMAGE_URL` - Image with full URL
            :param menu_icon_value:
                Icon glyph name or URL, depending on `menu_icon_type` setting
        """
        self.name = name
        self.category = category
        self.endpoint = endpoint
        self.url = url
        self.static_folder = static_folder
        self.static_url_path = static_url_path
        self.menu = None

        self.menu_class_name = menu_class_name
        self.menu_icon_type = menu_icon_type
        self.menu_icon_value = menu_icon_value

        # Initialized from create_blueprint
        self.admin = None
        self.blueprint = None

        # Default view
        if self._default_view is None:
            raise Exception(u'Attempted to instantiate admin view %s without default view' % self.__class__.__name__)

    def create_blueprint(self, admin):
        """
            Create Flask blueprint.
        """
        # Store admin instance
        self.admin = admin

        # If endpoint name is not provided, get it from the class name
        if self.endpoint is None:
            self.endpoint = self.__class__.__name__.lower()

        # If the static_url_path is not provided, use the admin's
        if not self.static_url_path:
            self.static_url_path = admin.static_url_path

        # If url is not provided, generate it from endpoint name
        if self.url is None:
            if self.admin.url != '/':
                self.url = '%s/%s' % (self.admin.url, self.endpoint)
            else:
                if self == admin.index_view:
                    self.url = '/'
                else:
                    self.url = '/%s' % self.endpoint
        else:
            if not self.url.startswith('/'):
                self.url = '%s/%s' % (self.admin.url, self.url)

        
        # If we're working from the root of the site, set prefix to None
        if self.url == '/':
            self.url = None
            # prevent admin static files from conflicting with flask static files
            if not self.static_url_path:
                self.static_folder='static'
                self.static_url_path='/static/admin'
            
            
        # If name is not povided, use capitalized endpoint name
        if self.name is None:
            self.name = self._prettify_class_name(self.__class__.__name__)

        # Create blueprint and register rules
        self.blueprint = Blueprint(self.endpoint, __name__,
                                   url_prefix=self.url,
                                   subdomain=self.admin.subdomain,
                                   template_folder=op.join('templates', self.admin.template_mode),
                                   static_folder=self.static_folder,
                                   static_url_path=self.static_url_path)

        for url, name, methods in self._urls:
            self.blueprint.add_url_rule(url,
                                        name,
                                        getattr(self, name),
                                        methods=methods)

        return self.blueprint

    def render(self, template, **kwargs):
        """
            Render template

            :param template:
                Template path to render
            :param kwargs:
                Template arguments
        """
        # Store self as admin_view
        kwargs['admin_view'] = self
        kwargs['admin_base_template'] = self.admin.base_template

        # Provide i18n support even if flask-babel is not installed
        # or enabled.
        kwargs['_gettext'] = babel.gettext
        kwargs['_ngettext'] = babel.ngettext
        kwargs['h'] = h

        # Expose get_url helper
        kwargs['get_url'] = self.get_url

        # Expose config info
        kwargs['config'] = current_app.config

        # Contribute extra arguments
        kwargs.update(self._template_args)

        return render_template(template, **kwargs)

    def _prettify_class_name(self, name):
        """
            Split words in PascalCase string into separate words.

            :param name:
                String to prettify
        """
        return h.prettify_class_name(name)

    def is_visible(self):
        """
            Override this method if you want dynamically hide or show administrative views
            from Flask-Admin menu structure

            By default, item is visible in menu.

            Please note that item should be both visible and accessible to be displayed in menu.
        """
        return True

    def is_accessible(self):
        """
            Override this method to add permission checks.

            Flask-Admin does not make any assumptions about the authentication system used in your application, so it is
            up to you to implement it.

            By default, it will allow access for everyone.
        """
        return True

    def _handle_view(self, name, **kwargs):
        """
            This method will be executed before calling any view method.

            It will execute the ``inaccessible_callback`` if the view is not
            accessible.

            :param name:
                View function name
            :param kwargs:
                View function arguments
        """
        if not self.is_accessible():
            return self.inaccessible_callback(name, **kwargs)

    def _run_view(self, fn, *args, **kwargs):
        """
            This method will run actual view function.

            While it is similar to _handle_view, can be used to change
            arguments that are passed to the view.

            :param fn:
                View function
            :param kwargs:
                Arguments
        """
        return fn(self, *args, **kwargs)

    def inaccessible_callback(self, name, **kwargs):
        """
            Handle the response to inaccessible views.

            By default, it throw HTTP 403 error. Override this method to
            customize the behaviour.
        """
        return abort(403)

    def get_url(self, endpoint, **kwargs):
        """
            Generate URL for the endpoint. If you want to customize URL generation
            logic (persist some query string argument, for example), this is
            right place to do it.

            :param endpoint:
                Flask endpoint name
            :param kwargs:
                Arguments for `url_for`
        """
        return url_for(endpoint, **kwargs)

    @property
    def _debug(self):
        if not self.admin or not self.admin.app:
            return False

        return self.admin.app.debug
Example #8
0
    class StaticFileAdmin(with_metaclass(CoolAdminMeta, FileAdmin)):
        MENU_ICON = 'folder-o'
        list_template = 'admin/file/list2.html'

        def fileType(self, file_name):
            l = file_name.lower().split('.')
            if len(l) < 2:
                return None
            else:
                return l[-1]

        @expose('/unzip')
        def unzip(self):
            pass

        @expose('/')
        @expose('/b/<path:path>')
        def index(self, path=None):
            if self.can_delete:
                delete_form = self.delete_form()
            else:
                delete_form = None

            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'))

            items = []
            if directory != base_path:
                parent_path = op.normpath(op.join(path, '..'))
                if parent_path == '.':
                    parent_path = None

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

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

                if self.is_accessible_path(rel_path):
                    items.append((f, rel_path, op.isdir(fp), op.getsize(fp), op.getmtime(fp)))

            items.sort(key=itemgetter(0))
            items.sort(key=itemgetter(2), reverse=True)
            items.sort(key=lambda values: (values[0], values[1], values[2], values[3], datetime.fromtimestamp(values[4])), reverse=True)

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

            actions, actions_confirmation = self.get_actions_list()

            base_static_url = self.base_url
            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,
                               base_static_url=base_static_url,
                               fileType=self.fileType)