Home Backend Development Python Tutorial Python的Flask框架中Flask-Admin库的简单入门指引

Python的Flask框架中Flask-Admin库的简单入门指引

Jun 06, 2016 am 11:24 AM
flask python

 Flask-Admin是一个功能齐全、简单易用的Flask扩展,让你可以为Flask应用程序增加管理界面。它受django-admin包的影响,但用这样一种方式实现,开发者拥有最终应用程序的外观、感觉和功能的全部控制权。

本文是关于Flask-Admin库的快速入门。本文假设读者预先具有一些Flask框架的知识。

  1.     介绍
  2.     初始化
  3.     增加视图
  4.     身份验证
  5.     生成URL
  6.     模型视图
  7.     文件管理

介绍

这个库打算做到尽可能的灵活。并且开发者不需要任何猴子补丁就可以获得期望的功能。

这个库使用一个简单而强大的概念——管理部件(administrative pieces,不太好翻译),是用视图方法构建的类。

例如,这是一个绝对有效的管理部件:
 

class MyView(BaseView):
  @expose('/')
  def index(self):
    return self.render('admin/myindex.html')
 
  @expose('/test/')
  def test(self):
    return self.render('admin/test.html')
Copy after login

如果用户访问index视图,模板文件admin/myindex.html会被渲染。同样的,访问test视图的结果是admin/test.html被渲染。

那么,这个方法怎样帮助管理界面的结构化?使用这些已建立的部件,你可以实施高度定制化的可重复使用的功能。

例如,Flask-Admin提供一个现成的SQLAlchemy模型接口。它以类执行并接受2个参数:模型类和数据库会话。当它显示一些改变接口的行为的类级变量(有点像django.contrib.admin),没有任何东西阻止你继承它并覆盖表单创建逻辑、数据库存储方法或者通过增加更多的视图扩展现有的功能。
初始化

要开始使用Flask-Admin,你需要创建一个Admin类实例并和Flask应用程序实例关联。

from flask import Flask
from flask.ext.admin import Admin
 
app = Flask(__name__)
 
admin = Admin(app)
# Add administrative views here
 
app.run()
Copy after login

如果你运行这个程序并访问http://localhost:5000/admin/,你会看到一个顶部有导航栏的空的“Home”页面:

201547151627357.png (630×212)

你可以更换应用程序名称通过传值给Admin类构造函数的name参数:

admin = Admin(app, name='My App')
Copy after login

作为一个选择方案,在Admin实例初始化之后,你可以调用init_app()函数把Flask应用程序对象传给Admin构造函数:

admin = Admin(name='My App')
# Add views here
admin.init_app(app)
Copy after login

增加视图

现在,让我们增加一个管理视图。下面的例子会致使两个项目出现在导航菜单:Home和Hello。为此,你需要衍生于BaseView类:

from flask import Flask
from flask.ext.admin import Admin, BaseView, expose
 
class MyView(BaseView):
  @expose('/')
  def index(self):
    return self.render('index.html')
 
app = Flask(__name__)
 
admin = Admin(app)
admin.add_view(MyView(name='Hello'))
 
app.run()
Copy after login

一个关于管理视图的重要约束是每个视图类应该拥有一个默认的以根URL/开头的页面视图方法。下面的例子是正确的:

class MyView(BaseView):
  @expose('/')
  def index(self):
    return self.render('index.html')
Copy after login

可是,这个不工作:

class MyView(BaseView):
  @expose('/index/')
  def index(self):
    return self.render('index.html')
Copy after login

现在,创建一个新的index.html文件并写入如下内容:

{% extends 'admin/master.html' %}
{% block body %}
  Hello World from MyView!
{% endblock %}
Copy after login

然后把它放到templates目录。为维持一致的外观和感觉,所有管理页面应该延伸于admin/master.html模板。

你现在应该看到Hello页面的新的管理页面起作用了。
要增加另一个级别的菜单项目,你可以指定category参数的值当传送管理视图给Admin实例时。category指定顶级菜单项目的名字,并且所有与之关联的视图,都会通过下拉菜单进入。例如:

from flask import Flask
from flask.ext.admin import Admin, BaseView, expose
 
class MyView(BaseView):
  @expose('/')
  def index(self):
    return self.render('index.html')
 
app = Flask(__name__)
 
admin = Admin(app)
admin.add_view(MyView(name='Hello 1', endpoint='test1', category='Test'))
admin.add_view(MyView(name='Hello 2', endpoint='test2', category='Test'))
admin.add_view(MyView(name='Hello 3', endpoint='test3', category='Test'))
app.run()
Copy after login
Copy after login

看起来是这样的:

201547151816428.png (630×212)

要增加另一个级别的菜单项目,你可以指定category参数的值当传送管理视图给Admin实例时。category指定顶级菜单项目的名字,并且所有与之关联的视图,都会通过下拉菜单进入。例如:

from flask import Flask
from flask.ext.admin import Admin, BaseView, expose
 
class MyView(BaseView):
  @expose('/')
  def index(self):
    return self.render('index.html')
 
app = Flask(__name__)
 
admin = Admin(app)
admin.add_view(MyView(name='Hello 1', endpoint='test1', category='Test'))
admin.add_view(MyView(name='Hello 2', endpoint='test2', category='Test'))
admin.add_view(MyView(name='Hello 3', endpoint='test3', category='Test'))
app.run()
Copy after login
Copy after login

看起来是这样的:

201547151851634.png (630×212)

身份验证

Flask-Admin没有设想任何你可以使用的身份验证系统。因此,默认的,管理界面是完全开放的。

要控制使用管理界面,你可以指定is_accessible方法当扩展BaseView类时。那么,举例,如果你使用Flask-Login做身份验证,下面的代码确保只有已登入的用户能访问视图:

class MyView(BaseView):
  def is_accessible(self):
    return login.current_user.is_authenticated()
Copy after login

你也可以实施基于策略的保密,有条件的允许或不允许使用管理界面的某些部分。如果一个用户无权使用某个特定视图,则菜单项目不可见。
生成URL

在内部,视图类工作于Flask蓝图的顶部,因此你可以使用url_for附带一个.前缀来获得局部视图的URL:

from flask import url_for
 
class MyView(BaseView):
  @expose('/')
  def index(self)
    # Get URL for the test view method
    url = url_for('.test')
    return self.render('index.html', url=url)
 
  @expose('/test/')
  def test(self):
    return self.render('test.html')
Copy after login

如果你要在外部生成一个特定视图的URL,应用下面的规则:

你可以覆盖endpoint名称通过传送endpoint参数给视图类构造函数:

  admin = Admin(app)
  admin.add_view(MyView(endpoint='testadmin'))
   
  # In this case, you can generate links by concatenating the view method name with an endpoint:
   
  url_for('testadmin.index')
Copy after login

如果你不覆盖endpoint名称,类名的小写形式会用于生成URL,像这样:

url_for('myview.index')

对基于模型的视图规则不一样——模型类名称会被使用如果没有提供endpoint名称。基于模型的视图下一节解释。

模型视图

模型视图允许你为数据库中的每个模型增加专用的管理页面。通过创建ModelView类实例做这个,ModelView类可从Flask-Admin内置的ORM后端引入。一个SQLAlchemy后端的例子,你可以这样使用:

from flask.ext.admin.contrib.sqla import ModelView
 
# Flask and Flask-SQLAlchemy initialization here
 
admin = Admin(app)
admin.add_view(ModelView(User, db.session))
Copy after login

这创建一个User模型的管理界面。默认的,列表视图看起来是这样的:

201547151933319.png (630×374)

要定制这些模型视图,你有两个选择:一是覆盖ModelView类的公有属性,二是覆盖它的方法。

例如,假如你要禁用模型创建功能并且只在列表视力显示某些列,你可以这样做:

from flask.ext.admin.contrib.sqla import ModelView
 
# Flask and Flask-SQLAlchemy initialization here
 
class MyView(ModelView):
  # Disable model creation
  can_create = False
 
  # Override displayed fields
  column_list = ('login', 'email')
 
  def __init__(self, session, **kwargs):
    # You can pass name and other parameters if you want to
    super(MyView, self).__init__(User, session, **kwargs)
 
admin = Admin(app)
admin.add_view(MyView(db.session))

Copy after login

覆盖表单元素有些棘手,但还是可能的。这个例子是关于如何建立一个包含有只允许使用预定义值的名为status的列的表单,并使用SelectField:

from wtforms.fields import SelectField
 
class MyView(ModelView):
  form_overrides = dict(status=SelectField)
  form_args = dict(
    # Pass the choices to the `SelectField`
    status=dict(
      choices=[(0, 'waiting'), (1, 'in_progress'), (2, 'finished')]
    ))
Copy after login

通过继承BaseModelView类和实现数据库相关的方法为不同的数据库后端(比如Mongo等)增加支持是相对容易的。

关于如何定制基于模型的管理视图的行为请参考flask.ext.admin.contrib.sqla文档。
文件管理

Flask-Admin拥有另一个便利的特性——文件管理。它给予你管理服务器文件的能力(上传、删除、重命名等)。

这是一个简单的例子:

from flask.ext.admin.contrib.fileadmin import FileAdmin
 
import os.path as op
 
# Flask setup here
 
admin = Admin(app)
 
path = op.join(op.dirname(__file__), 'static')
admin.add_view(FileAdmin(path, '/static/', name='Static Files'))
Copy after login

例子截图:

201547152006840.png (623×539)

你可以禁用上传、禁用文件或目录删除、限制文件上传类型等等。关于怎么做这些请查看flask.ext.admin.contrib.fileadmin文档。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles