熬夜翻译的flask_admin文档,分享给跟我一样入门flask的朋友们!
from flask import Flask
from flask_admin import Admin
app = Flask(__name__)
# set optional bootswatch theme
app.config['FLASK_ADMIN_SWATCH'] = 'cerulean'
admin = Admin(app, name='microblog', template_mode='bootstrap3')
# Add administrative views here
app.run()
这里,名称和模板模式参数都是可选的。或者,您可以使用init_app()方法。
如果启动此应用程序并导航到http://localhost:5000/admin/,则应该会看到一个顶部带有导航栏的空白页。通过指定适合您需要的引导样本主题自定义外观(有关可用样本,请参阅http://bootswatch.com/3/)。
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))
{% extends 'admin/master.html' %}
{% block body %}
<p>Hello world</p>
{% endblock %}
幸的是,没有简单的方法可以将HTTP基本身份验证仅应用于管理界面。
最简单的身份验证形式是HTTP基本身份验证。它不会干扰数据库模型,也不需要编写任何新的视图逻辑或模板代码。所以当你在部署一些仍在开发中的东西时,在你希望全世界都能看到它之前,它是非常好的。
看看Flask-BasicAuth,看看将整个应用程序置于HTTP Basic Auth之后有多容易。
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 login和flask admin的示例,请查看https://github.com/flask-admin/flask-admin/tree/master/examples/auth-flask-login。
主要的缺点是,您仍然需要实现所有相关的登录、注册和帐户管理视图。
{% extends 'admin/master.html' %}
def security_context_processor():
return dict(
admin_base_template=admin.base_template,
admin_view=admin.index_view,
h=admin_helpers,
)
有关在flask admin中使用flask security的工作示例,请查看https://github.com/flask-admin/flask-admin/tree/master/examples/auth。
该示例只使用内置的注册和登录视图,但您可以使用相同的方法来包括其他视图,如忘记密码、发送确认等。
from flask_admin.contrib.sqla import ModelView
# Flask and Flask-SQLAlchemy initialization here
class MicroBlogModelView(ModelView):
can_delete = False # disable model deletion
page_size = 50 # the number of entries to display on the list view
admin.add_view(MicroBlogModelView(User, db.session))
admin.add_view(MicroBlogModelView(Post, db.session))
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))
can_create = False
can_edit = False
can_delete = False
can_view_details = True
column_exclude_list = ['password', ]
column_searchable_list = ['name', 'email']
column_filters = ['country']
column_editable_list = ['name', 'last_name']
create_modal = True
edit_modal = True
form_choices = {
'title': [
('MR', 'Mr'),
('MRS', 'Mrs'),
('MS', 'Ms'),
('DR', 'Dr'),
('PROF', 'Prof.')
]
}
form_excluded_columns = ['last_name', 'email']
form_args = {
'name': {
'label': 'First Name',
'validators': [required()]
}
}
form_widget_args = {
'description': {
'rows': 10,
'style': 'color: black'
}
}
form_ajax_refs = {
'user': {
'fields': ['first_name', 'last_name', 'email'],
'page_size': 10
}
}
form_ajax_refs = {
'active_user': QueryAjaxModelLoader('user', db.session, User,
filters=["is_active=True", "id>1000"])
}
inline_models = ['post', ]
可以自定义这些内联表单。请查看inline_models()的API文档。
要启用模型视图的csv导出,请执行以下操作:
can_export = True
admin.add_view(UserView(User, db.session, category="Team"))
admin.add_view(ModelView(Role, db.session, category="Team"))
admin.add_view(ModelView(Permission, db.session, category="Team"))
这将创建一个名为“Team”的顶级菜单项,以及一个包含到三个视图的链接的下拉列表。
要在这些下拉列表中嵌套相关视图,请使用添加子类别方法:
admin.add_sub_category(name="Links", parent_name="Team")
admin.add_link(MenuLink(name='Home Page', url='/', category='Links'))
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'))
{% extends 'admin/master.html' %}
{% block body %}
<p>Here I'm going to display some data.</p>
{% endblock %}
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')
与其完全覆盖内置模板,不如对其进行扩展。这将使您将来更容易升级到新的flask管理版本。
在内部,flask管理模板是从admin/master.html 模板派生的。您要扩展的三个最有趣的模板可能是:
要使用你自己的功能扩展默认的编辑模板,请请在templates/microblog_edit.html中创建一个模板,其外观如下:
{% extends 'admin/model/edit.html' %}
{% block body %}
MicroBlog Edit View
{{ super() }}
{% endblock %}
class MicroBlogModelView(ModelView):
edit_template = 'microblog_edit.html'
# create_template = 'microblog_create.html'
# list_template = 'microblog_list.html'
admin = Admin(app, base_template='microblog_master.html')
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 |
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 |
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 |
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)
# Edit View for record #1 (redirect back to index_view)
url_for('user.edit_view', id=1, url=url_for('user.index_view'))
url_for('analytics.index')
admin.add_view(CustomView(name='Analytics', endpoint='analytics'))
flask_admin官方文档链接:https://flask-admin.readthedocs.io/en/latest/introduction/#customizing-builtin-views
翻译:云瑶八千境