A simple introductory guide to the Flask-admin library in the Python flask framework _python

Source: Internet
Author: User

Flask-admin is a full-featured, easy-to-use flask Extension that allows you to add a management interface for flask applications. It is affected by the Django-admin package, but it 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 primer on the Flask-admin library. This paper assumes that the reader has some knowledge of flask framework beforehand.

    1. Introduced
    2. Class
    3. Add view
    4. Authentication
    5. Generate URL
    6. Model View
    7. File Management

Introduced

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

This library uses a simple and powerful concept--managing widgets (administrative pieces, not very good translations), and 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 is rendered. Similarly, the result of accessing the Test view is that admin/test.html is rendered.

So how does this approach help manage the structure of the interface? With these established components, you can implement highly customizable, reusable features.

For example, Flask-admin provides an out-of-the-box SQLAlchemy model interface. It executes with a class and accepts 2 parameters: the model class and the database session. 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, database storage methods, or expanding existing functionality by adding more views.
Initialization of

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

From flask import flask from
flask.ext.admin Import admin
 
app = Flask (__name__)
 
admin = admin (app)
# ADD A dministrative views here
 
App.run ()

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

You can replace the application name by passing the value to the Admin class constructor's name parameter:

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

As a selection, 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 here
Admin.init_app (APP)

Add view

Now, let's add an admin 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 flask from
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 admin pages should be extended to the admin/master.html template.

You should now see the new admin page of the Hello page working.
To add another level of menu item, you can specify the category parameter's worth when transferring admin view to 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 flask from
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 (name= ' Hello 2 ', endpoint = ' test2 ', category= ' test ')
Admin.add_view (MyView (name= ' Hello 3 ', endpoint= ' test3 ', category= ' Test
')) App.run ()

It seems to be like this:

To add another level of menu item, you can specify the category parameter's worth when transferring admin view to 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 flask from
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 (name= ' Hello 2 ', endpoint = ' test2 ', category= ' test ')
Admin.add_view (MyView (name= ' Hello 3 ', endpoint= ' test3 ', category= ' Test
')) App.run ()

It seems to be like this:

Authentication

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 admin 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 logged users can access the view:

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

You can also implement policy-based confidentiality, conditional permission or disallow use of certain parts of the admin interface. 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 url_for with a. Prefix to get the URL for the local view:

From flask import Url_for
 
class MyView (Baseview):
  @expose ('/')
  def index (self)
    # get URL for the test vie W method
    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 argument to the view class constructor:

  admin = admin (APP)
  Admin.add_view (MyView (endpoint= ' testadmin '))
   
  # In this 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 not the same-the model class name is used if the endpoint name is not provided. A model-based view is explained in the next section.

Model View

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

From Flask.ext.admin.contrib.sqla import Modelview
 
# flask and Flask-sqlalchemy initialization here
 
admin = Admin (APP)
Admin.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 override it.

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

From Flask.ext.admin.contrib.sqla import Modelview
 
# flask and Flask-sqlalchemy initialization here
 
class MyView (Modelview):
  # Disable model creation
  can_create = False
 
  # Override displayed fields
  = (' login ', ' email ')
 
  def __init__ (self, Session, **kwargs):
    # with can pass name and other parameters if you want t o
    super (MyView, self). __init__ (User, Session, **kwargs)
 
admin = admin (APP)
Admin.add_view (MyView ( Db.session))

Overwriting a FORM element is tricky, but still possible. This example is about how to create a form that contains a column named status that allows only predefined values, and uses Selectfield:

From Wtforms.fields import Selectfield
 
class MyView (Modelview):
  form_overrides = Dict (Status=selectfield)
  Form_args = dict (
    # Pass of the choices to the ' Selectfield '
    status=dict (
      choices=[(0, ' waiting '), (1, ' In_progress '), (2, ' finished ')])
    

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

Refer to the FLASK.EXT.ADMIN.CONTRIB.SQLA documentation for the behavior of customizing the model-based management view.
File Management

Flask-admin has another handy 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 screenshot:

You can disable uploading, disable file or directory deletion, restrict file upload types, and so on. See the Flask.ext.admin.contrib.fileadmin documentation for how to do this.

Related Article

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.