为什么80%的码农都做不了架构师?>>>   

#Flask-Admin入门介绍 ##让我们荡起双桨

初始化

Introduction To Flask-Admin
Getting Started
Initialization

第一步,先把大象装冰箱,哦错了。第一步是为你的Flask应用初始化一个空的管理界面。

The first step is to initialize an empty admin interface for your Flask app:

from flask import Flask
from flask_admin import Adminapp = Flask(__name__)admin = Admin(app, name='microblog', template_mode='bootstrap3')
# Add administrative views hereapp.run()

name和template_mode参数是可选的,作为备选,你可以使用 init_app() 方法(译者注:参见Flask-Admin APIs)

Here, both the name and template_mode parameters are optional. Alternatively, you could use the init_app() method.

你可以尝试启动你的应用,然后在浏览器中访问 http://localhost:5000/admin/ ,你可以看到一个上部 带了导航条的(没有内容)空页面。

If you start this application and navigate to http://localhost:5000/admin/, you should see an empty page with a navigation bar on top.

添加模型视图

模型视图允许你添加一组专用的管理页面来维护自己的数据库的任何模型。如何做到呢?你只需要创建一个ModelView类的实例即可。当然你可以引进你所喜欢的ORM支持包。下面是一个使用SQLAlchemy 持久化支持的栗子:

Adding Model Views
Model views allow you to add a dedicated set of admin pages for managing any model in your database. Do this by creating instances of the ModelView class, which you can import from one of Flask-Admin’s built-in ORM backends. An example is the SQLAlchemy backend, which you can use as follows:

from flask_admin.contrib.sqla import ModelView# Flask and Flask-SQLAlchemy initialization hereadmin = Admin(app, name='microblog', template_mode='bootstrap3')
admin.add_view(ModelView(User, db.session))
admin.add_view(ModelView(Post, db.session))

开箱即用,她给你的模型带来了一组完整CRUD视图功能

  • 列表页面,包含搜索、排序、过滤和删除记录的功能;
  • 新建页面,添加新的记录;
  • 编辑页面,更新存在的记录;
  • 详情页面,(这是可选的)提供了记录的详细信息展示(只读)

Straight out of the box, this gives you a set of fully featured CRUD views for your model:

  • A list view, with support for searching, sorting, filtering, and deleting records.
  • A create view for adding new records.
  • An edit view for updating existing records.
  • An optional, read-only details view.

当然,Flask-Admin也支持很多选项,在内嵌视图里自定义展现和其他功能。更多信息,可以看 自定义 内嵌视图。关于支持其他ORM的信息,请参考这里:使用不同的数据库后台组件;

There are many options available for customizing the display and functionality of these built-in views. For more details on that, see Customizing Built-in Views. For more details on the other ORM backends that are available, see Using Different Database Backends.

为你的页面添加内容

在上文,你会注意到,访问了http://localhost:5000/admin/ 页面只能看到一个有导航菜单的(内容)空页面。来,让我们为这个页面添加点儿什么,新建admin/index.html页面,填入如下代码,保存到工程的模版目录:

Adding Content to the Index Page
The first thing you’ll notice when you visit http://localhost:5000/admin/ is that it’s just an empty page with a navigation menu. To add some content to this page, save the following text as admin/index.html in your project’s templates directory:

{% extends 'admin/master.html' %}{% block body %}<p>Hello world</p>
{% endblock %}

这会覆盖调默认的index模版,但是仍旧会给你一个内嵌的导航菜单。所以,现在你可以添加任何内容到index页面,同时保证一致的用户体验。

This will override the default index template, but still give you the built-in navigation menu. So, now you can add any content to the index page, while maintaining a consistent user experience.

认证和权限

当你为应用创建一个管理界面时,首要问题就是要解决安全问题:将不受欢迎的人拒之门外。在Flask-Admin这里,有一些方案可以处理这个问题。

** Authorization & Permissions**
When setting up an admin interface for your application, one of the first problems you’ll want to solve is how to keep unwanted users out. With Flask-Admin there are a few different ways of approaching this.

HTTP基础认证

最简单的认证是HTTP Basic Auth。她不需要入侵你的数据库数据模型进行交互,当然也不需要你写任何新的视图逻辑或模版代码。当你,在你想发布(让所有人都看到)之前,你可以以开发模式部署应用,这看起来很爽。 移步这里看看:Flask-BasicAuth如何轻松地将你的应用罩上一层HTTP Basic Auth防护。 不幸的是,她没有提供一种简单可行的UI将HTTP Basic Auth应用于你的项目。

HTTP Basic Auth
The simplest form of authentication is HTTP Basic Auth. It doesn’t interfere with your database models, and it doesn’t require you to write any new view logic or template code. So it’s great for when you’re deploying something that’s still under development, before you want the whole world to see it.

Have a look at Flask-BasicAuth to see just how easy it is to put your whole application behind HTTP Basic Auth.

Unfortunately, there is no easy way of applying HTTP Basic Auth just to your admin interface.

构造你自己的(认证)

更为灵活的解决方式是,Flask-Admin提供了一个方法,你可以在管理视图类中通过简单的重载 is_accessible 方法即可自定义访问控制规则。由你自己决定如何落地其中的逻辑,但是如果你用了一个简单|初级的认证库比如Flask-Login时,访问控制代码会非常简单:

Rolling Your Own
For a more flexible solution, Flask-Admin lets you define access control rules on each of your admin view classes by simply overriding the is_accessible method. How you implement the logic is up to you, but if you were to use a low-level library like Flask-Login, then restricting access could be as simple as:

class MicroBlogModelView(sqla.ModelView):def is_accessible(self):return login.current_user.is_authenticated()def inaccessible_callback(self, name, **kwargs):# redirect to login page if user doesn't have accessreturn redirect(url_for('login', next=request.url))

如果一个用户没有权限去访问某菜单项,则不会在导航菜单中显示此项。这里有一个Flask-Admin整合Flask-Login的栗子,传送门在这里: https://github.com/flask-admin/Flask-Admin/tree/master/examples/auth-flask-login. (使用Flask-Login)最主要的缺点是,你仍旧需要自己去实现相关登录、注册和账户管理视图。

In the navigation menu, components that are not accessible to a particular user will not be displayed for that user. For an example of using Flask-Login with Flask-Admin, have a look at https://github.com/flask-admin/Flask-Admin/tree/master/examples/auth-flask-login.

The main drawback is that you still need to implement all of the relevant login, registration, and account management views yourself.

使用Flask-Security

什么,你需要一个闪闪发光的解决方案?来我们看看高段位的Flask-Security库。她自带了大量通用的视图比如:用户注册、登录、Email地址验证、密码重置等等。 唯一复杂一点儿的,就是将Flask-Security视图平滑地整合到Flask-Admin模版,以带来一个一致的用户体验。你只需要重写Flask-Security自带的模版,让她们继承一下Flask-Admin基础模版就可以了,声明代码如下:

Using Flask-Security
If you want a more polished solution, you could use Flask-Security, which is a higher-level library. It comes with lots of built-in views for doing common things like user registration, login, email address confirmation, password resets, etc.

The only complicated bit is making the built-in Flask-Security views integrate smoothly with the Flask-Admin templates to create a consistent user experience. To do this, you will need to override the built-in Flask-Security templates and have them extend the Flask-Admin base template by adding the following to the top of each file:

{% extends 'admin/master.html' %}

现在,你需要手动地为Flask-Admin模版去注册下 上下文变量,以便她们在Flask-Security视图被访问时能导向正确的页面。定义一个security_context_processor函数就能轻松做到。

Now, you’ll need to manually pass in some context variables for the Flask-Admin templates to render correctly when they’re being called from the Flask-Security views. Defining a security_context_processor function will take care of this for you:

def security_context_processor():return dict(admin_base_template=admin.base_template,admin_view=admin.index_view,h=admin_helpers,)

想看一个整合好的栗子么,移步这里:https://github.com/flask-admin/Flask-Admin/tree/master/examples/auth. 这个栗子只用到了自带的注册和登录页面,但是你可以用比葫芦画瓢实现其他页面视图,比如:忘记密码,发送验证等等。

For a working example of using Flask-Security with Flask-Admin, have a look at https://github.com/flask-admin/Flask-Admin/tree/master/examples/auth. The example only uses the built-in register and login views, but you could follow the same approach for including the other views, like forgot_password, send_confirmation, etc.

自定义内嵌视图

使用自带的ModelView 类可以快速地迈出万里长征第一步。但是,你可以给你的特定模型自定义配置一些功能。要做到这些,只需要在ModelView类中配置属性有效值即可。 (方法就是:)继承ModelView类,配置一些指定的参数,使用此子类添加模型到页面上,栗子如下:

** Customizing Built-in Views**
The built-in ModelView class is great for getting started quickly. But, you’ll want to configure its functionality to suit your particular models. This is done by setting values for the configuration attributes that are made available in the ModelView class.

To specify some global configuration parameters, you can subclass ModelView and use that subclass when adding your models to the interface:

from flask_admin.contrib.sqla import ModelView# Flask and Flask-SQLAlchemy initialization hereclass UserView(ModelView):@expose('/new/', methods=('GET', 'POST'))def create_view(self):"""Custom create view."""return self.render('create_user.html')

或者,使用同样的途径,你可以在一个独立的模型中每次配置指定的选项。

Or, in much the same way, you can specify options for a single model at a time:

class UserView(ModelView):can_delete = False  # disable model deletionclass PostView(ModelView):page_size = 50  # the number of entries to display on the list viewadmin.add_view(UserView(User, db.session))
admin.add_view(PostView(Post, db.session))

模型视图配置属性

完整的自定义属性清单,可以去看看API中BaseModelView()的文档。下面列出了一些常用的属性: 我们可以通过配置布尔参数,来关闭部分CRUD操作:

ModelView Configuration Attributes
For a complete list of the attributes that are defined, have a look at the API documentation for BaseModelView(). Here are some of the most commonly used attributes:

To disable some of the CRUD operations, set any of these boolean parameters:

can_create = False
can_edit = False
can_delete = False

如果你得模型拥有太多的数据需要在页面上显示,你可以添加一个只读页面的参数设置:

If your model has too much data to display in the list view, you can add a read-only details view by setting:

can_view_details = True

通过配置一个列名字的清单,你可以在列表视图中轻松地移除不需要的列:

Removing columns from the list view is easy, just pass a list of column names for the column_excludes_list parameter:

column_exclude_list = ['password', ]

当然也可以配置某列是否可以被搜索,或者过滤,只需指定一个列名清单即可:

To make columns searchable, or to use them for filtering, specify a list of column names:

column_searchable_list = ['name', 'email']
column_filters = ['country']

想多快好省地建设社会主义?只需要在列表视图中配置inline参数enable即可:

For a faster editing experience, enable inline editing in the list view:

column_editable_list = ['name', 'last_name']

更炫酷地是,你可以通过配置以下参数,从列表页面弹出模态窗口替代独立的创建和编辑页面

Or, have the add & edit forms display inside a modal window on the list page, instead of the dedicated create & edit pages:

create_modal = True
edit_modal = True

你还可以限定文本框输入指定的值,通过配置一个字典清单:

You can restrict the possible values for a text-field by specifying a list of select choices:

form_choices = {'title': [('MR', 'Mr'),('MRS', 'Mrs'),('MS', 'Ms'),('DR', 'Dr'),('PROF', 'Prof.')]
}

想从创建和编辑forms中移除一些字段?你可以这么写:

To remove fields from the create and edit forms:

form_excluded_columns = ['last_name', 'email']

想给WTForms传参?你可以这么写:

To specify WTForms field arguments:

form_args = {'name': {'label': 'First Name','validators': [required()]}
}

想给 WTForms widgets传参?你可以这么写:

Or, to specify arguments to the WTForms widgets used to render those fields:

form_widget_args = {'description': {'rows': 10,'style': 'color: black'}
}

如果你的form包含了一个外键,可以通过ajax来关联对应模型:

When your forms contain foreign keys, have those related models loaded via ajax, using:

form_ajax_refs = {'user': {'fields': ['first_name', 'last_name', 'email'],'page_size': 10}
}

想管理关联模型:

To manage related models inline:

inline_models = ['post', ]

这些行forms可以自定义,参考 inline_models()的API文档

These inline forms can be customized. Have a look at the API documentation for inline_models().

配置页面模型可以导出csv文件:

To enable csv export of the model view:

can_export = True

这个设置会在页面上显示一个按钮,点击导出对应模型的数据,最大数量受 export_max_rows限制。

This will add a button to the model view that exports records, truncating at export_max_rows.

添加自己的页面

在这种场景中:你想在ModelView类中处理非常细节的需求时,Flask-Admin支持很容易地让你完全控制和添加你自己的页面到管理接口上。

** Adding Your Own Views**
For situations where your requirements are really specific and you struggle to meet them with the built-in ModelView class, Flask-Admin makes it easy for you to take full control and add your own views to the interface.

标准视图

一组标配的视图(不用和特殊的模型绑定)可以通过继承BaseView类来添加,并轻易你自己的视图方法。举个栗子,添加一个使用第三方API显示分析数据的页面,你可以:

Standalone Views

A set of standalone views (not tied to any particular model) can be added by extending the BaseView class and defining your own view methods. For example, to add a page that displays some analytics data from a 3rd-party API:

from flask_admin import BaseView, exposeclass AnalyticsView(BaseView):@expose('/')def index(self):return self.render('analytics_index.html')admin.add_view(AnalyticsView(name='Analytics', endpoint='analytics'))

此处会为你的页面添加一个菜单到导航条。注意她被指定以"/"根目录提供。这是标准视图的一个限制:每一个视图类里最少一个方法被标识为她的根目录。 上面栗子提到的analytics_index.html 模版,看起来长这样:

This will add a link to the navbar for your view. Notice that it is served at ‘/’, the root URL. This is a restriction on standalone views: at the very minimum, each view class needs at least one method to serve a view at its root. The analytics_index.html template for the example above, could look something like:

{% extends 'admin/master.html' %}
{% block body %}<p>Here I'm going to display some data.</p>
{% endblock %}

通过继承admin/master.html模版,你可以保持始终如一的用户体验,为你的页面内容配备强有力的控制。 By extending the admin/master.html template, you can maintain a consistent user experience, even while having tight control over your page’s content.

重写内嵌视图

内嵌的视图大多数情况下可以满足你的基本需求,不过,你仍然可以替换掉默认的CRU视图。只需要重写视图,所有的一切都会如你所愿的正常工作。

Overriding the Built-in Views
There may be some scenarios where you want most of the built-in ModelView functionality, but you want to replace one of the default create, edit, or list views. For this you could override only the view in question, and all the links to it will still function as you would expect:

from flask_admin.contrib.sqla import ModelView# Flask and Flask-SQLAlchemy initialization hereclass UserView(ModelView):@expose('/new/', methods=('GET', 'POST'))def create_view(self):"""Custom create view."""return self.render('create_user.html')

Working With the Built-in Templates

Flask-Admin uses the Jinja2 templating engine.

Extending the Built-in Templates

Rather than overriding the built-in templates completely, it’s best to extend them. This will make it simpler for you to upgrade to new Flask-Admin versions in future.

Internally, the Flask-Admin templates are derived from the admin/master.html template. The three most interesting templates for you to extend are probably:

admin/model/list.html admin/model/create.html admin/model/edit.html To extend the default edit template with your own functionality, create a template in templates/microblog_edit.html to look something like:

{% extends 'admin/model/edit.html' %}

{% block body %} <h1>MicroBlog Edit View</h1> {{ super() }} {% endblock %} Now, to make your view classes use this template, set the appropriate class property:

class MicroBlogModelView(ModelView): edit_template = 'microblog_edit.html' # create_template = 'microblog_create.html' # list_template = 'microblog_list.html' If you want to use your own base template, then pass the name of the template to the admin constructor during initialization:

admin = Admin(app, base_template='microblog_master.html') Overriding the Built-in Templates To take full control over the style and layout of the admin interface, you can override all of the built-in templates. Just keep in mind that the templates will change slightly from one version of Flask-Admin to the next, so once you start overriding them, you need to take care when upgrading your package version.

To override any of the built-in templates, simply copy them from the Flask-Admin source into your project’s templates/admin/ directory. As long as the filenames stay the same, the templates in your project directory should automatically take precedence over the built-in ones.

Available Template Blocks

Flask-Admin defines one base template at admin/master.html that all other admin templates are derived from. This template is a proxy which points to admin/base.html, which defines the following blocks:

Block Name Description head_meta Page metadata in the header title Page title head_css Various CSS includes in the header head Empty block in HTML head, in case you want to put something there page_body Page layout brand Logo in the menu bar main_menu Main menu menu_links Links menu access_control Section to the right of the menu (can be used to add login/logout buttons) messages Alerts and various messages body Content (that’s where your view will be displayed) tail Empty area below content In addition to all of the blocks that are inherited from admin/master.html, the admin/model/list.html template also contains the following blocks:

Block Name Description model_menu_bar Menu bar model_list_table Table container list_header Table header row list_row_actions_header Actions header list_row Single row list_row_actions Row action cell with edit/remove/etc buttons empty_list_message Message that will be displayed if there are no models found Have a look at the layout example at https://github.com/flask-admin/flask-admin/tree/master/examples/layout to see how you can take full stylistic control over the admin interface.

Environment Variables

While working in any of the templates that extend admin/master.html, you have access to a small number of environment variables:

Variable Name Description

admin_view Current administrative view admin_base_template Base template name _gettext Babel gettext _ngettext Babel ngettext h Helpers from helpers module Generating URLs To generate the URL for a specific view, use url_for with a dot prefix:

from flask import url_forclass MyView(BaseView):@expose('/')def index(self):# Get URL for the test view methoduser_list_url = url_for('user.index_view')return self.render('index.html', user_list_url=user_list_url)

A specific record can also be referenced with:

# Edit View for record #1 (redirect back to index_view)
url_for('user.edit_view', id=1, url=url_for('user.index_view'))

When referencing ModelView instances, use the lowercase name of the model as the prefix when calling url_for. Other views can be referenced by specifying a unique endpoint for each, and using that as the prefix. So, you could use:

url_for('analytics.index')

If your view endpoint was defined like:

admin.add_view(CustomView(name='Analytics', endpoint='analytics'))

未完,待续

转载于:https://my.oschina.net/hexie/blog/730271

[翻译][1.4.2]Flask-Admin入门介绍相关推荐

  1. 独家 | 集成学习入门介绍

    作者:Jason Brownlee 翻译:wwl 校对:王琦 本文约3300字,建议阅读8分钟. 本文介绍了我们在生活中的许多决定包括了其他人的意见,由于群体的智慧,有的时候群体的决策优于个体.在机器 ...

  2. Asp.Net MVC4.0 官方教程 入门指南之一-- 入门介绍

    本教程将为您讲解使用微软的Visual Studio  2012 来建立一个ASP.NET MVC4 Web应用程序所需要的基础知识. 本示例将构建什么样的应用程序? 您将实现一个简单的电影管理应用程 ...

  3. (XGBoost)提升树入门介绍(Inrtoduction to Boosted Trees)

    提升树入门介绍(Inrtoduction to Boosted Trees) Author : Jasper Yang School : Bupt 这是一篇翻译文,翻译的内容是 XGBoost 官网的 ...

  4. RESTFUL协议入门介绍

    PHP高级工程师之RESTFUL协议 在这里和大家分享一下在写接口中要遵循的协议,这里我们介绍RESTFUL. 如有不善,多提意见(QQ:1595068971-邮箱:1595068971@qq.com ...

  5. Python 01:Pyton历史和入门介绍

    Pyton历史和入门介绍 Python是在1991年诞生的一门面向对象.解释型计算机程序设计语言.Python能做很多事情,小到简单脚本大到后端架构设计,也可以使用python来做胶水语言.学习程序设 ...

  6. STM32系列微控制器入门介绍

    文章目录 目的 基础需求 电路基础 编程语言 入门介绍 官方网站 型号选择 开发方式 开发工具 程序调试 固件烧录 资料说明 总结 目的 STM32是意法半导体(ST)推出的主要基于ARM Corte ...

  7. 数据科学系列:plotly可视化入门介绍

    导读 在入道数据岗位之初,曾系列写过多个数据科学工具包的入门教程,包括Numpy.Pandas.Matplotlib.Seaborn.Sklearn等,这些也构成了自己当初的核心工具栈.在这5个工具包 ...

  8. WebSocket入门介绍及编程实战

    前言:最近看了几天的WebSocket,从以前的只闻其名,到现在也算是有一点点的了解了.所以就准备用博客记录一下自己的学习过程,希望也能帮助其它学习的人,因为我本人学习的过程中也是参考了很多其它人的博 ...

  9. Android Framework入门介绍

    Android Framework入门介绍 https://blog.csdn.net/fu_kevin0606/article/details/79532710 framework概述 Androi ...

最新文章

  1. AJAX技术入门 第五节 Javascript高级知识
  2. Python深入04 闭包
  3. C++中类的静态成员变量和静态成员函数
  4. Sql 中取小数点后面两位小数.
  5. 如何计算数据集均值和方差
  6. ajax 三种数据格式
  7. 中国生物医药行业供需形势透析及未来投资风险评估报告2022-2027年版
  8. 冻结拆分_还不会固定表头?速来围观Excel冻结窗格实战教程
  9. 1-3 交换变量(算法竞赛入门经典)
  10. .NET Core WebAPI Swagger使用
  11. [转]关于c#winform禁用关闭按钮的方法
  12. Android开发案例源码解析之使用sqlite数据库记录并读取GPS信息
  13. Python贴吧小爬虫
  14. ESP32实现Wave(.wav)音频文件输出
  15. 来自CSDN的精华网址
  16. 瘦手臂最快最有效的方法
  17. 计算机图形学实验四 OpenGL的鼠标交互绘制
  18. 【刷题日记】网易——瞌睡
  19. MATLAB——基于图像相减的纸牌识别系统
  20. 7个半月股价涨了40%多,DXC做对了什么?

热门文章

  1. 技巧:Silverlight应用程序中如何获取ASP.NET页面参数
  2. 如何在Spring Boot中使用Hibernate Natural ID
  3. Docker渐入佳境
  4. CentOS 6.3编译安装Nginx1.2.2+MySQL5.5.25a+PHP5.4.5
  5. ArcSDE建Table在ArcCatalog中不可见
  6. 学网络好帮手:路由器模拟软件RouteSim3.31
  7. spring 04-Spring框架依赖注入基本使用
  8. 智能合约遇到的三个大坑
  9. stl-----全排列
  10. Scala中集合类型与java中集合类型转换