[翻译][1.4.2]Flask-Admin入门介绍

#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 Admin

app = Flask(__name__)

admin = Admin(app, name='microblog', template_mode='bootstrap3')
# Add administrative views here

app.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 here

admin = 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 access
        return 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 here

class 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 deletion

class PostView(ModelView):
        page_size = 50  # the number of entries to display on the list view

admin.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, expose

class 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 here

class 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_for

class MyView(BaseView):
    @expose('/')
    def index(self):
        # Get URL for the test view method
        user_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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值