首页 后端开发 Python教程 Flask的图形化管理界面搭建框架Flask-Admin的使用教程

Flask的图形化管理界面搭建框架Flask-Admin的使用教程

Jun 16, 2016 am 08:47 AM
flask python

Flask-Admin是Flask框架的一个扩展,用它能够快速创建Web管理界面,它实现了比如用户、文件的增删改查等常用的管理功能;如果对它的默认界面不喜欢,可以通过修改模板文件来定制;
Flask-Admin把每一个菜单(超链接)看作一个view,注册后才能显示出来,view本身也有属性来控制其是否可见;因此,利用这个机制可以定制自己的模块化界面,比如让不同权限的用户登录后看到不一样的菜单;

项目地址:https://flask-admin.readthedocs.io/en/latest/

example/simple
这是最简单的一个样例,可以帮助我们快速、直观的了解基本概念,学会定制Flask-Admin的界面
simple.py:

from flask import Flask

from flask.ext import admin


# Create custom admin view
class MyAdminView(admin.BaseView):
  @admin.expose('/')
  def index(self):
    return self.render('myadmin.html')


class AnotherAdminView(admin.BaseView):
  @admin.expose('/')
  def index(self):
    return self.render('anotheradmin.html')

  @admin.expose('/test/')
  def test(self):
    return self.render('test.html')


# Create flask app
app = Flask(__name__, template_folder='templates')
app.debug = True

# Flask views
@app.route('/')
def index():
  return '<a href="/admin/">Click me to get to Admin!</a>'

# Create admin interface
admin = admin.Admin()
admin.add_view(MyAdminView(category='Test'))
admin.add_view(AnotherAdminView(category='Test'))
admin.init_app(app)

if __name__ == '__main__':

  # Start app
  app.run()

登录后复制

在这里可以看到运行效果

BaseView

所有的view都必须继承自BaseView:

复制代码 代码如下:


class BaseView(name=None, category=None, endpoint=None, url=None, static_folder=None, static_url_path=None)


name: view在页面上表现为一个menu(超链接),menu name == 'name',缺省就用小写的class name
category: 如果多个view有相同的category就全部放到一个dropdown里面(dropdown name=='category')
endpoint: 假设endpoint='xxx',则可以用url_for(xxx.index),也能改变页面URL(/admin/xxx)
url: 页面URL,优先级url > endpoint > class name
static_folder: static目录的路径
static_url_path: static目录的URL
anotheradmin.html:

{% extends 'admin/master.html' %}
{% block body %}
  Hello World from AnotherMyAdmin!<br/>
  <a href="{{ url_for('.test') }}">Click me to go to test view</a>
{% endblock %}
登录后复制

如果AnotherAdminView增加参数endpoint='xxx',那这里就可以写成url_for('xxx.text'),然后页面URL会由/admin/anotheradminview/变成/admin/xxx
如果同时指定参数url='aaa',那页面URL会变成/admin/aaa,url优先级比endpoint高
Admin

复制代码 代码如下:


class Admin(app=None, name=None, url=None, subdomain=None, index_view=None, translations_path=None, endpoint=None, static_url_path=None, base_template=None)


app: Flask Application Object;本例中可以不写admin.init_app(app),直接用admin = admin.Admin(app=app)是一样的
name: Application name,缺省'Admin';会显示为main menu name('Home'左边的'Admin')和page title
subdomain: ???
index_view: 'Home'那个menu对应的就叫index view,缺省AdminIndexView
base_template: 基础模板,缺省admin/base.html,该模板在Flask-Admin的源码目录里面
部分Admin代码如下:

class MenuItem(object):
  """
    Simple menu tree hierarchy.
  """
  def __init__(self, name, view=None):
    self.name = name
    self._view = view
    self._children = []
    self._children_urls = set()
    self._cached_url = None
    self.url = None
    if view is not None:
      self.url = view.url

  def add_child(self, view):
    self._children.append(view)
    self._children_urls.add(view.url)

class Admin(object):

  def __init__(self, app=None, name=None,
         url=None, subdomain=None,
         index_view=None,
         translations_path=None,
         endpoint=None,
         static_url_path=None,
         base_template=None):

    self.app = app

    self.translations_path = translations_path

    self._views = []
    self._menu = []
    self._menu_categories = dict()
    self._menu_links = []

    if name is None:
      name = 'Admin'
    self.name = name

    self.index_view = index_view or AdminIndexView(endpoint=endpoint, url=url)
    self.endpoint = endpoint or self.index_view.endpoint
    self.url = url or self.index_view.url
    self.static_url_path = static_url_path
    self.subdomain = subdomain
    self.base_template = base_template or 'admin/base.html'

    # Add predefined index view
    self.add_view(self.index_view)

    # Register with application
    if app is not None:
      self._init_extension()

  def add_view(self, view):

    # Add to views
    self._views.append(view)

    # If app was provided in constructor, register view with Flask app
    if self.app is not None:
      self.app.register_blueprint(view.create_blueprint(self))
      self._add_view_to_menu(view)

  def _add_view_to_menu(self, view):

    if view.category:
      category = self._menu_categories.get(view.category)

      if category is None:
        category = MenuItem(view.category)
        self._menu_categories[view.category] = category
        self._menu.append(category)

      category.add_child(MenuItem(view.name, view))
    else:
      self._menu.append(MenuItem(view.name, view))

  def init_app(self, app):

    self.app = app

    self._init_extension()

    # Register views
    for view in self._views:
      app.register_blueprint(view.create_blueprint(self))
      self._add_view_to_menu(view)

登录后复制

从上面的代码可以看出init_app(app)和Admin(app=app)是一样的:
将每个view注册为blueprint(Flask里的概念,可以简单理解为模块)
记录所有view,以及所属的category和url
AdminIndexView

复制代码 代码如下:


class AdminIndexView(name=None, category=None, endpoint=None, url=None, template='admin/index.html')


name: 缺省'Home'
endpoint: 缺省'admin'
url: 缺省'/admin'
如果要封装出自己的view,可以参照AdminIndexView的写法:

class AdminIndexView(BaseView):

  def __init__(self, name=None, category=None,
         endpoint=None, url=None,
         template='admin/index.html'):
    super(AdminIndexView, self).__init__(name or babel.lazy_gettext('Home'),
                       category,
                       endpoint or 'admin',
                       url or '/admin',
                       'static')
    self._template = template

  @expose()
  def index(self):
    return self.render(self._template)
base_template

登录后复制

base_template缺省是/admin/base.html,是页面的主要代码(基于bootstrap),它里面又import admin/layout.html;
layout是一些宏,主要用于展开、显示menu;
在模板中使用一些变量来取出之前注册view时保存的信息(如menu name和url等):
# admin/layout.html (部分)

{% macro menu() %}
 {% for item in admin_view.admin.menu() %}
  {% if item.is_category() %}
   {% set children = item.get_children() %}
   {% if children %}
    {% if item.is_active(admin_view) %}<li class="active dropdown">{% else %}<li class="dropdown">{% endif %}
     <a class="dropdown-toggle" data-toggle="dropdown" href="javascript:void(0)">{{ item.name }}<b class="caret"></b></a>
     <ul class="dropdown-menu">
      {% for child in children %}
       {% if child.is_active(admin_view) %}<li class="active">{% else %}<li>{% endif %}
        <a href="{{ child.get_url() }}">{{ child.name }}</a>
       </li>
      {% endfor %}
     </ul>
    </li>
   {% endif %}
  {% else %}
   {% if item.is_accessible() and item.is_visible() %}
    {% if item.is_active(admin_view) %}<li class="active">{% else %}<li>{% endif %}
     <a href="{{ item.get_url() }}">{{ item.name }}</a>
    </li>
   {% endif %}
  {% endif %}
 {% endfor %}
{% endmacro %}
登录后复制

example/file
这个样例能帮助我们快速搭建起文件管理界面,但我们的重点是学习使用ActionsMixin模块
file.py:

import os
import os.path as op

from flask import Flask

from flask.ext import admin
from flask.ext.admin.contrib import fileadmin

# Create flask app
app = Flask(__name__, template_folder='templates', static_folder='files')

# Create dummy secrey key so we can use flash
app.config['SECRET_KEY'] = '123456790'


# Flask views
@app.route('/')
def index():
  return '<a href="/admin/">Click me to get to Admin!</a>'


if __name__ == '__main__':
  # Create directory
  path = op.join(op.dirname(__file__), 'files')
  try:
    os.mkdir(path)
  except OSError:
    pass

  # Create admin interface
  admin = admin.Admin(app)
  admin.add_view(fileadmin.FileAdmin(path, '/files/', name='Files'))

  # Start app
  app.run(debug=True)

登录后复制

FileAdmin是已经写好的的一个view,直接用即可:

复制代码 代码如下:


class FileAdmin(base_path, base_url, name=None, category=None, endpoint=None, url=None, verify_path=True)


base_path: 文件存放的相对路径
base_url: 文件目录的URL
FileAdmin中和ActionsMixin相关代码如下:
class FileAdmin(BaseView, ActionsMixin):

  def __init__(self, base_path, base_url,
         name=None, category=None, endpoint=None, url=None,
         verify_path=True):

    self.init_actions()

@expose('/action/', methods=('POST',))
def action_view(self):
  return self.handle_action()

# Actions
@action('delete',
    lazy_gettext('Delete'),
    lazy_gettext('Are you sure you want to delete these files&#63;'))
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')

@action('edit', lazy_gettext('Edit'))
def action_edit(self, items):
  return redirect(url_for('.edit', path=items))
@action()用于wrap跟在后面的函数,这里的作用就是把参数保存起来:
def action(name, text, confirmation=None)
  def wrap(f):
    f._action = (name, text, confirmation)
    return f

  return wrap

登录后复制

name: action name
text: 可用于按钮名称
confirmation: 弹框确认信息
init_actions()把所有action的信息保存到ActionsMixin里面:

# 调试信息
_actions = [('delete', lu'Delete'), ('edit', lu'Edit')]
_actions_data = {'edit': (<bound method FileAdmin.action_edit of <flask_admin.contrib.fileadmin.FileAdmin object at 0x1aafc50>>, lu'Edit', None), 'delete': (<bound method FileAdmin.action_delete of <flask_admin.contrib.fileadmin.FileAdmin object at 0x1aafc50>>, lu'Delete', lu'Are you sure you want to delete these files&#63;')}
登录后复制

action_view()用于处理POST给/action/的请求,然后调用handle_action(),它再调用不同的action处理,最后返回当前页面:

# 省略无关代码
def handle_action(self, return_view=None):

  action = request.form.get('action')
  ids = request.form.getlist('rowid')

  handler = self._actions_data.get(action)

  if handler and self.is_action_allowed(action):
    response = handler[0](ids)

    if response is not None:
      return response

  if not return_view:
    url = url_for('.' + self._default_view)
  else:
    url = url_for('.' + return_view)

  return redirect(url)

登录后复制

ids是一个文件清单,作为参数传给action处理函数(参数items):

# 调试信息
ids: [u'1.png', u'2.png']
登录后复制

再分析页面代码,Files页面对应文件为admin/file/list.html,重点看With selected下拉菜单相关代码:
{% import 'admin/actions.html' as actionslib with context %}

{% if actions %}
  <div class="btn-group">
    {{ actionslib.dropdown(actions, 'dropdown-toggle btn btn-large') }}
  </div>
{% endif %}

{% block actions %}
  {{ actionslib.form(actions, url_for('.action_view')) }}
{% endblock %}

{% block tail %}
  {{ actionslib.script(_gettext('Please select at least one file.'),
           actions,
           actions_confirmation) }}
{% endblock %}

登录后复制

上面用到的三个宏在actions.html:

{% macro dropdown(actions, btn_class='dropdown-toggle') -%}
  <a class="{{ btn_class }}" data-toggle="dropdown" href="javascript:void(0)">{{ _gettext('With selected') }}<b class="caret"></b></a>
  <ul class="dropdown-menu">
    {% for p in actions %}
    <li>
      <a href="javascript:void(0)" onclick="return modelActions.execute('{{ p[0] }}');">{{ _gettext(p[1]) }}</a>
    </li>
    {% endfor %}
  </ul>
{% endmacro %}

{% macro form(actions, url) %}
  {% if actions %}
  <form id="action_form" action="{{ url }}" method="POST" style="display: none">
    {% if csrf_token %}
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
    {% endif %}
    <input type="hidden" id="action" name="action" />
  </form>
  {% endif %}
{% endmacro %}

{% macro script(message, actions, actions_confirmation) %}
  {% if actions %}
  <script src="{{ admin_static.url(filename='admin/js/actions.js') }}"></script>
  <script language="javascript">
    var modelActions = new AdminModelActions({{ message|tojson|safe }}, {{ actions_confirmation|tojson|safe }});
  </script>
  {% endif %}
{% endmacro %}

登录后复制

最终生成的页面(部分):

<div class="btn-group">
  <a class="dropdown-toggle btn btn-large" href="javascript:void(0)" data-toggle="dropdown">
    With selected
    <b class="caret"></b>
  </a>

  <ul class="dropdown-menu">
    <li>
      <a onclick="return modelActions.execute('delete');" href="javascript:void(0)">Delete</a>
    </li>
    <li>
      <a onclick="return modelActions.execute('edit');" href="javascript:void(0)">Edit</a>
    </li>
  </ul>
</div>

<form id="action_form" action="/admin/fileadmin/action/" method="POST" style="display: none">
  <input type="hidden" id="action" name="action" />
</form>

<script src="/admin/static/admin/js/actions.js"></script>
<script language="javascript">
  var modelActions = new AdminModelActions("Please select at least one file.", {"delete": "Are you sure you want to delete these files&#63;"});
</script>

登录后复制

选择菜单后的处理方法在actions.js:

var AdminModelActions = function(actionErrorMessage, actionConfirmations) {
  // Actions helpers. TODO: Move to separate file
  this.execute = function(name) {
    var selected = $('input.action-checkbox:checked').size();

    if (selected === 0) {
      alert(actionErrorMessage);
      return false;
    }

    var msg = actionConfirmations[name];

    if (!!msg)
      if (!confirm(msg))
        return false;

    // Update hidden form and submit it
    var form = $('#action_form');
    $('#action', form).val(name);

    $('input.action-checkbox', form).remove();
    $('input.action-checkbox:checked').each(function() {
      form.append($(this).clone());
    });

    form.submit();

    return false;
  };

  $(function() {
    $('.action-rowtoggle').change(function() {
      $('input.action-checkbox').attr('checked', this.checked);
    });
  });
};

登录后复制

对比一下修改前后的表单:

# 初始化
<form id="action_form" style="display: none" method="POST" action="/admin/fileadmin/action/">
  <input id="action" type="hidden" name="action">
</form>

# 'Delete'选中的三个文件
<form id="action_form" style="display: none" method="POST" action="/admin/fileadmin/action/">
  <input id="action" type="hidden" name="action" value="delete">
  <input class="action-checkbox" type="checkbox" value="1.png" name="rowid">
  <input class="action-checkbox" type="checkbox" value="2.png" name="rowid">
  <input class="action-checkbox" type="checkbox" value="3.png" name="rowid">
</form>

# 'Edit'选中的一个文件
<form id="action_form" style="display: none" method="POST" action="/admin/fileadmin/action/">
  <input id="action" type="hidden" name="action" value="edit">
  <input class="action-checkbox" type="checkbox" value="1.png" name="rowid">
</form>

登录后复制

总结一下,当我们点击下拉菜单中的菜单项(Delete,Edit),本地JavaScript代码会弹出确认框(假设有确认信息),然后提交一个表单给/admin/fileadmin/action/,请求处理函数action_view()根据表单类型再调用不同的action处理函数,最后返回一个页面。

Flask-Admin字段(列)格式化
在某些情况下,我们需要对模型的某个属性进行格式化。比如,默认情况下,日期时间显示出来会比较长,这时可能需要只显示月和日,这时候,列格式化就派上用场了。

比如,如果你要显示双倍的价格,你可以这样做:

class MyModelView(BaseModelView):
  column_formatters = dict(price=lambda v, c, m, p: m.price*2)
登录后复制

或者在Jinja2模板中使用宏:

from flask.ext.admin.model.template import macro

class MyModelView(BaseModelView):
  column_formatters = dict(price=macro('render_price'))

# in template
{% macro render_price(model, column) %}
  {{ model.price * 2 }}
{% endmacro %}

登录后复制

回调函数模型:

def formatter(view, context, model, name):
  # `view` is current administrative view
  # `context` is instance of jinja2.runtime.Context
  # `model` is model instance
  # `name` is property name
  pass
登录后复制

正好和上面的v, c, m, p相对应。

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
4 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

mysql 是否要付费 mysql 是否要付费 Apr 08, 2025 pm 05:36 PM

MySQL 有免费的社区版和收费的企业版。社区版可免费使用和修改,但支持有限,适合稳定性要求不高、技术能力强的应用。企业版提供全面商业支持,适合需要稳定可靠、高性能数据库且愿意为支持买单的应用。选择版本时考虑的因素包括应用关键性、预算和技术技能。没有完美的选项,只有最合适的方案,需根据具体情况谨慎选择。

mysql安装后怎么使用 mysql安装后怎么使用 Apr 08, 2025 am 11:48 AM

文章介绍了MySQL数据库的上手操作。首先,需安装MySQL客户端,如MySQLWorkbench或命令行客户端。1.使用mysql-uroot-p命令连接服务器,并使用root账户密码登录;2.使用CREATEDATABASE创建数据库,USE选择数据库;3.使用CREATETABLE创建表,定义字段及数据类型;4.使用INSERTINTO插入数据,SELECT查询数据,UPDATE更新数据,DELETE删除数据。熟练掌握这些步骤,并学习处理常见问题和优化数据库性能,才能高效使用MySQL。

Navicat查看MongoDB数据库密码的方法 Navicat查看MongoDB数据库密码的方法 Apr 08, 2025 pm 09:39 PM

直接通过 Navicat 查看 MongoDB 密码是不可能的,因为它以哈希值形式存储。取回丢失密码的方法:1. 重置密码;2. 检查配置文件(可能包含哈希值);3. 检查代码(可能硬编码密码)。

mysql 需要互联网吗 mysql 需要互联网吗 Apr 08, 2025 pm 02:18 PM

MySQL 可在无需网络连接的情况下运行,进行基本的数据存储和管理。但是,对于与其他系统交互、远程访问或使用高级功能(如复制和集群)的情况,则需要网络连接。此外,安全措施(如防火墙)、性能优化(选择合适的网络连接)和数据备份对于连接到互联网的 MySQL 数据库至关重要。

如何针对高负载应用程序优化 MySQL 性能? 如何针对高负载应用程序优化 MySQL 性能? Apr 08, 2025 pm 06:03 PM

MySQL数据库性能优化指南在资源密集型应用中,MySQL数据库扮演着至关重要的角色,负责管理海量事务。然而,随着应用规模的扩大,数据库性能瓶颈往往成为制约因素。本文将探讨一系列行之有效的MySQL性能优化策略,确保您的应用在高负载下依然保持高效响应。我们将结合实际案例,深入讲解索引、查询优化、数据库设计以及缓存等关键技术。1.数据库架构设计优化合理的数据库架构是MySQL性能优化的基石。以下是一些核心原则:选择合适的数据类型选择最小的、符合需求的数据类型,既能节省存储空间,又能提升数据处理速度

HadiDB:Python 中的轻量级、可水平扩展的数据库 HadiDB:Python 中的轻量级、可水平扩展的数据库 Apr 08, 2025 pm 06:12 PM

HadiDB:轻量级、高水平可扩展的Python数据库HadiDB(hadidb)是一个用Python编写的轻量级数据库,具备高度水平的可扩展性。安装HadiDB使用pip安装:pipinstallhadidb用户管理创建用户:createuser()方法创建一个新用户。authentication()方法验证用户身份。fromhadidb.operationimportuseruser_obj=user("admin","admin")user_obj.

mysql workbench 可以连接到 mariadb 吗 mysql workbench 可以连接到 mariadb 吗 Apr 08, 2025 pm 02:33 PM

MySQL Workbench 可以连接 MariaDB,前提是配置正确。首先选择 "MariaDB" 作为连接器类型。在连接配置中,正确设置 HOST、PORT、USER、PASSWORD 和 DATABASE。测试连接时,检查 MariaDB 服务是否启动,用户名和密码是否正确,端口号是否正确,防火墙是否允许连接,以及数据库是否存在。高级用法中,使用连接池技术优化性能。常见错误包括权限不足、网络连接问题等,调试错误时仔细分析错误信息和使用调试工具。优化网络配置可以提升性能

mysql 需要服务器吗 mysql 需要服务器吗 Apr 08, 2025 pm 02:12 PM

对于生产环境,通常需要一台服务器来运行 MySQL,原因包括性能、可靠性、安全性和可扩展性。服务器通常拥有更强大的硬件、冗余配置和更严格的安全措施。对于小型、低负载应用,可在本地机器运行 MySQL,但需谨慎考虑资源消耗、安全风险和维护成本。如需更高的可靠性和安全性,应将 MySQL 部署到云服务器或其他服务器上。选择合适的服务器配置需要根据应用负载和数据量进行评估。

See all articles