A simple guide to flask-admin libraries in the flask framework of Python

Source: Internet
Author: User
Flask-admin is a full-featured, easy-to-use Flask extension that allows you to add a management interface to your Flask application. It is affected by the Django-admin package, but is implemented in such a way that the developer has full control over the look, feel, and functionality of the final application.

This article is a quick start on the Flask-admin library. This article assumes that the reader has some knowledge of the flask framework beforehand.

    1. Introduced
    2. Initialization
    3. Add view
    4. Identity verification
    5. Generate URL
    6. Model View
    7. File Management

Introduced

This library is intended to be as flexible as possible. And developers do not need any monkey patches to get the desired functionality.

This library uses a simple and powerful concept--managing widgets (administrative pieces, not very well translated)--is a class built with a view method.

For example, this is an absolutely effective management component:

Class MyView (Baseview):  @expose ('/')  def index (self):    return Self.render (' admin/myindex.html ')   @ Expose ('/test/')  def Test (self):    return Self.render (' admin/test.html ')

If the user accesses the index view, the template file admin/myindex.html will be rendered. Similarly, the result of accessing the Test view is that admin/test.html is rendered.

So how does this approach help to structure the management interface? With these built-in parts, you can implement highly customizable, reusable features.

For example, Flask-admin provides an off-the-shelf SQLAlchemy model interface. It executes and accepts 2 parameters in a class: Model classes and database sessions. When it shows some class-level variables that change the behavior of the interface (a bit like django.contrib.admin), nothing prevents you from inheriting it and overwriting the form creation logic, the database storage method, or extending the existing functionality by adding more views.
Initialization

To get started with flask-admin, you need to create an instance of the Admin class and associate it with the Flask application instance.

From flask import flaskfrom flask.ext.admin import Admin app = Flask (__name__) admin = admin (APP) # ADD Administrative View s here App.run ()

If you run this program and visit http://localhost:5000/admin/, you will see an empty "Home" page with a navigation bar at the top:

You can change the application name by passing the value to the name parameter of the Admin class constructor:

admin = admin (app, name= ' My app ')

As a selection scenario, after the admin instance is initialized, you can call the Init_app () function to pass the Flask Application object to the Admin constructor:

admin = admin (name= ' My app ') # Add views Hereadmin.init_app (APP)

Add view

Now, let's add a management view. The following example causes two items to appear in the navigation menu: Home and hello. To do this, you need to derive from the Baseview class:

From flask import flaskfrom 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 ()

An important constraint on managing views is that each view class should have a default page view method that starts with the root url/. The following example is correct:

Class MyView (Baseview):  @expose ('/')  def index (self):    return Self.render (' index.html ')

However, this does not work:

Class MyView (Baseview):  @expose ('/index/')  def index (self):    return Self.render (' index.html ')

Now, create a new index.html file and write the following:

{% extends ' admin/master.html '%} {% block body%}  Hello World from myview! {% Endblock%}

Then put it in the templates directory. To maintain a consistent look and feel, all administration pages should be extended to the admin/master.html template.

You should now see the new administration page for the Hello page working.
To add another level of menu items, you can specify the category parameter of the worth Transfer management view to the admin instance. Category specifies the name of the top-level menu item, and all views associated with it are entered through the drop-down menu. For example:

From flask import flaskfrom 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 ' Hello 2 ', name= ' endpoint= ', test2 ' Test ')) Admin.add_view (MyView (name= ' Hello 3 ', endpoint= ' test3 ', category= ' Test ')) App.run ()

It looks like this:

To add another level of menu items, you can specify the category parameter of the worth Transfer management view to the admin instance. Category specifies the name of the top-level menu item, and all views associated with it are entered through the drop-down menu. For example:

From flask import flaskfrom 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 ' Hello 2 ', name= ' endpoint= ', test2 ' Test ')) Admin.add_view (MyView (name= ' Hello 3 ', endpoint= ' test3 ', category= ' Test ')) App.run ()

It looks like this:

Identity verification

Flask-admin does not envisage any authentication system that you can use. So, by default, the Admin interface is completely open.

To control the use of the administration interface, you can specify the Is_accessible method when extending the Baseview class. So, for example, if you use Flask-login for authentication, the following code ensures that only the logged-in user has access to the view:

Class MyView (Baseview):  def is_accessible (self):    return login.current_user.is_authenticated ()

You can also implement policy-based secrecy, conditionally permitting or not allowing certain portions of the management interface to be used. If a user does not have permission to use a particular view, the menu item is not visible.
Generate URL

Internally, the view class works at the top of the Flask blueprint, so you can use the url_for with a. Prefix to get the URL of the detail view:

From flask import Url_for class MyView (Baseview):  @expose ('/')  def index (self)    # Get URL for the test view met Hod    url = url_for ('. Test ')    return Self.render (' index.html ', Url=url)   @expose ('/test/')  def test ( Self):    return Self.render (' test.html ')

If you want to generate a URL for a particular view externally, apply the following rule:

You can override the endpoint name by passing the endpoint parameter to the view class constructor:

  admin = admin (APP)  Admin.add_view (MyView (endpoint= ' testadmin '))     # in the case, can generate links by Conca Tenating The View method name with an endpoint:     url_for (' Testadmin.index ')

If you do not overwrite the endpoint name, the lowercase form of the class name is used to generate the URL, like this:

Url_for (' Myview.index ')

The model-based view rule is different-the model class name is used if the endpoint name is not provided. The model-based view is explained in the next section.

Model View

The model view allows you to add a dedicated administration page for each model in the database. By creating a Modelview class instance to do this, the Modelview class can be introduced from the Flask-admin built-in ORM backend. An example of a sqlalchemy backend, which you can use:

From Flask.ext.admin.contrib.sqla import Modelview # flask and Flask-sqlalchemy initialization here Admin = admin (APP) Admi N.add_view (Modelview (User, db.session))

This creates a management interface for the user model. By default, the list view looks like this:

To customize these model views, you have two choices: one is to overwrite the public property of the Modelview class, and the other is to overwrite it.

For example, if you want to disable the model creation feature and only display certain columns in the list vision, you can do this:

From Flask.ext.admin.contrib.sqla import Modelview # flask and Flask-sqlalchemy initialization here class MyView (Modelvie W):  # Disable model creation  can_create = False   # Override displayed fields  column_list = (' login ', ' Emai L ')   def __init__ (self, Session, **kwargs):    # Your can pass name and other parameters if you want to    super (Myvie W, self). __init__ (User, Session, **kwargs) admin = admin (APP) Admin.add_view (MyView (db.session))

Overwriting form elements is tricky, but still possible. This example is about creating a form that contains a column named status with only the predefined values allowed, and using 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_pro Gress '), (2, ' finished ')])    )

It is relatively easy to add support for different database backend (such as MONGO, etc.) by inheriting the Basemodelview class and implementing database-related methods.

For information on how to customize the behavior of model-based management views, refer to the FLASK.EXT.ADMIN.CONTRIB.SQLA documentation.
File Management

Flask-admin has another convenient feature-file management. It gives you the ability to manage server files (upload, delete, rename, etc.).

This is a simple example:

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 ')

Example:

You can disable uploads, disable file or directory deletions, restrict file upload types, and more. For more information on how to do this, see the flask.ext.admin.contrib.fileadmin documentation.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.