In my recent projects I often ran into the important but boring task of building admin interfaces on top of data models. It is important because using an admin interface it is the preferred way to edit, add and delete information. It is boring because it basically means you have to create two interfaces dealing with exactly the same data: the layout of the website that is shown to public and the interface for data administration. Flask-Admin is an addon for the Flask microframework that takes care of the boring part. With little effort, it lets you manage your web service’s data through a user-friendly interface.

A basic example

My first shot was to try a basic example for editing the user table of a Flask application. The User class is a simple model containing just the id and username. I use the great Flask-SQLAlchemy extension here.

import os
from flask import Flask
from flask_admin import Admin
from flask.ext.sqlalchemy import SQLAlchemy
from flask_admin.contrib.sqla import ModelView

basedir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = (
    'sqlite:///' + os.path.join(basedir, 'data-dev.sqlite'))
app.config['SECRET_KEY'] = 'my secret'

db = SQLAlchemy(app)
admin = Admin(app, name='microblog', template_mode='bootstrap3')

class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64))

# Add administrative views here
admin.add_view(ModelView(User, db.session))

db.create_all()
app.run(debug=True)

The admin interface is added by simply creating an instance of the Admin class. A model view is added by calling the add_view() function on the admin object. Run the example above and visit http://localhost:5000/admin and you will see the new admin interface:

flask-admin1

When clicking on one of the entries you get a nice detail view that allows you to edit the available model data:

flask-admin2

I find this super-easy. We can now add, edit and delete users in a very convenient way. Some more advanced examples can be found onhttp://examples.flask-admin.org/.