[翻译][1.4.2]Flask-Admin入门介绍
為什么80%的碼農(nóng)都做不了架構(gòu)師?>>> ??
#Flask-Admin入門介紹 ##讓我們蕩起雙槳
初始化
Introduction To Flask-Admin
Getting Started
Initialization
第一步,先把大象裝冰箱,哦錯了。第一步是為你的Flask應(yīng)用初始化一個空的管理界面。
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參數(shù)是可選的,作為備選,你可以使用 init_app() 方法(譯者注:參見Flask-Admin APIs)
Here, both the name and template_mode parameters are optional. Alternatively, you could use the init_app() method.
你可以嘗試啟動你的應(yīng)用,然后在瀏覽器中訪問 http://localhost:5000/admin/ ,你可以看到一個上部 帶了導(dǎo)航條的(沒有內(nèi)容)空頁面。
If you start this application and navigate to http://localhost:5000/admin/, you should see an empty page with a navigation bar on top.
添加模型視圖
模型視圖允許你添加一組專用的管理頁面來維護自己的數(shù)據(jù)庫的任何模型。如何做到呢?你只需要創(chuàng)建一個ModelView類的實例即可。當(dāng)然你可以引進你所喜歡的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:
開箱即用,她給你的模型帶來了一組完整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.
當(dāng)然,Flask-Admin也支持很多選項,在內(nèi)嵌視圖里自定義展現(xiàn)和其他功能。更多信息,可以看 自定義 內(nèi)嵌視圖。關(guān)于支持其他ORM的信息,請參考這里:使用不同的數(shù)據(jù)庫后臺組件;
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.
為你的頁面添加內(nèi)容
在上文,你會注意到,訪問了http://localhost:5000/admin/ 頁面只能看到一個有導(dǎo)航菜單的(內(nèi)容)空頁面。來,讓我們?yōu)檫@個頁面添加點兒什么,新建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:
這會覆蓋調(diào)默認的index模版,但是仍舊會給你一個內(nèi)嵌的導(dǎo)航菜單。所以,現(xiàn)在你可以添加任何內(nèi)容到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.
認證和權(quán)限
當(dāng)你為應(yīng)用創(chuàng)建一個管理界面時,首要問題就是要解決安全問題:將不受歡迎的人拒之門外。在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基礎(chǔ)認證
最簡單的認證是HTTP Basic Auth。她不需要入侵你的數(shù)據(jù)庫數(shù)據(jù)模型進行交互,當(dāng)然也不需要你寫任何新的視圖邏輯或模版代碼。當(dāng)你,在你想發(fā)布(讓所有人都看到)之前,你可以以開發(fā)模式部署應(yīng)用,這看起來很爽。 移步這里看看:Flask-BasicAuth如何輕松地將你的應(yīng)用罩上一層HTTP Basic Auth防護。 不幸的是,她沒有提供一種簡單可行的UI將HTTP Basic Auth應(yīng)用于你的項目。
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.
構(gòu)造你自己的(認證)
更為靈活的解決方式是,Flask-Admin提供了一個方法,你可以在管理視圖類中通過簡單的重載 is_accessible 方法即可自定義訪問控制規(guī)則。由你自己決定如何落地其中的邏輯,但是如果你用了一個簡單|初級的認證庫比如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:
如果一個用戶沒有權(quán)限去訪問某菜單項,則不會在導(dǎo)航菜單中顯示此項。這里有一個Flask-Admin整合Flask-Login的栗子,傳送門在這里: https://github.com/flask-admin/Flask-Admin/tree/master/examples/auth-flask-login. (使用Flask-Login)最主要的缺點是,你仍舊需要自己去實現(xiàn)相關(guān)登錄、注冊和賬戶管理視圖。
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
什么,你需要一個閃閃發(fā)光的解決方案?來我們看看高段位的Flask-Security庫。她自帶了大量通用的視圖比如:用戶注冊、登錄、Email地址驗證、密碼重置等等。 唯一復(fù)雜一點兒的,就是將Flask-Security視圖平滑地整合到Flask-Admin模版,以帶來一個一致的用戶體驗。你只需要重寫Flask-Security自帶的模版,讓她們繼承一下Flask-Admin基礎(chǔ)模版就可以了,聲明代碼如下:
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' %}現(xiàn)在,你需要手動地為Flask-Admin模版去注冊下 上下文變量,以便她們在Flask-Security視圖被訪問時能導(dǎo)向正確的頁面。定義一個security_context_processor函數(shù)就能輕松做到。
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. 這個栗子只用到了自帶的注冊和登錄頁面,但是你可以用比葫蘆畫瓢實現(xiàn)其他頁面視圖,比如:忘記密碼,發(fā)送驗證等等。
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.
自定義內(nèi)嵌視圖
使用自帶的ModelView 類可以快速地邁出萬里長征第一步。但是,你可以給你的特定模型自定義配置一些功能。要做到這些,只需要在ModelView類中配置屬性有效值即可。 (方法就是:)繼承ModelView類,配置一些指定的參數(shù),使用此子類添加模型到頁面上,栗子如下:
** 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()的文檔。下面列出了一些常用的屬性: 我們可以通過配置布爾參數(shù),來關(guān)閉部分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如果你得模型擁有太多的數(shù)據(jù)需要在頁面上顯示,你可以添加一個只讀頁面的參數(shù)設(shè)置:
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', ]當(dāng)然也可以配置某列是否可以被搜索,或者過濾,只需指定一個列名清單即可:
To make columns searchable, or to use them for filtering, specify a list of column names:
column_searchable_list = ['name', 'email'] column_filters = ['country']想多快好省地建設(shè)社會主義?只需要在列表視圖中配置inline參數(shù)enable即可:
For a faster editing experience, enable inline editing in the list view:
column_editable_list = ['name', 'last_name']更炫酷地是,你可以通過配置以下參數(shù),從列表頁面彈出模態(tài)窗口替代獨立的創(chuàng)建和編輯頁面
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.')] }想從創(chuàng)建和編輯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來關(guān)聯(lián)對應(yīng)模型:
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} }想管理關(guān)聯(lián)模型:
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().
配置頁面模型可以導(dǎo)出csv文件:
To enable csv export of the model view:
can_export = True這個設(shè)置會在頁面上顯示一個按鈕,點擊導(dǎo)出對應(yīng)模型的數(shù)據(jù),最大數(shù)量受 export_max_rows限制。
This will add a button to the model view that exports records, truncating at export_max_rows.
添加自己的頁面
在這種場景中:你想在ModelView類中處理非常細節(jié)的需求時,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.
標(biāo)準(zhǔn)視圖
一組標(biāo)配的視圖(不用和特殊的模型綁定)可以通過繼承BaseView類來添加,并輕易你自己的視圖方法。舉個栗子,添加一個使用第三方API顯示分析數(shù)據(jù)的頁面,你可以:
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'))此處會為你的頁面添加一個菜單到導(dǎo)航條。注意她被指定以"/"根目錄提供。這是標(biāo)準(zhǔn)視圖的一個限制:每一個視圖類里最少一個方法被標(biāo)識為她的根目錄。 上面栗子提到的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模版,你可以保持始終如一的用戶體驗,為你的頁面內(nèi)容配備強有力的控制。 By extending the admin/master.html template, you can maintain a consistent user experience, even while having tight control over your page’s content.
重寫內(nèi)嵌視圖
內(nèi)嵌的視圖大多數(shù)情況下可以滿足你的基本需求,不過,你仍然可以替換掉默認的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:
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'))未完,待續(xù)
轉(zhuǎn)載于:https://my.oschina.net/hexie/blog/730271
總結(jié)
以上是生活随笔為你收集整理的[翻译][1.4.2]Flask-Admin入门介绍的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 面向过程与面向对象引入三大特性事务
- 下一篇: Vertica集群扩容实验过程记录