API Reference

flask.ext.appbuilder

AppBuilder

class flask.ext.appbuilder.base.AppBuilder(app=None, session=None, menu=None, indexview=None, base_template='appbuilder/baselayout.html', static_folder='static/appbuilder', static_url_path='/appbuilder', security_manager_class=None)[source]

This is the base class for all the framework. This is were you will register all your views and create the menu structure. Will hold your flask app object, all your views, and security classes.

initialize your application like this for SQLAlchemy:

from flask import Flask
from flask_appbuilder import SQLA, AppBuilder

app = Flask(__name__)
app.config.from_object('config')
db = SQLA(app)
appbuilder = AppBuilder(app, db.session)

When using MongoEngine:

from flask import Flask
from flask_appbuilder import AppBuilder
from flask_appbuilder.security.mongoengine.manager import SecurityManager
from flask_mongoengine import MongoEngine

app = Flask(__name__)
app.config.from_object('config')
dbmongo = MongoEngine(app)
appbuilder = AppBuilder(app, security_manager_class=SecurityManager)

You can also create everything as an application factory.

__init__(app=None, session=None, menu=None, indexview=None, base_template='appbuilder/baselayout.html', static_folder='static/appbuilder', static_url_path='/appbuilder', security_manager_class=None)[source]

AppBuilder constructor

Parameters:
  • app – The flask app object
  • session – The SQLAlchemy session object
  • menu – optional, a previous contructed menu
  • indexview – optional, your customized indexview
  • static_folder – optional, your override for the global static folder
  • static_url_path – optional, your override for the global static url path
  • security_manager_class – optional, pass your own security manager class

Add your own links to menu using this method

Parameters:
  • name – The string name that identifies the menu.
  • href – Override the generated href for the menu. You can use an url string or an endpoint name
  • icon – Font-Awesome icon name, optional.
  • label – The label that will be displayed on the menu, if absent param name will be used
  • category – The menu category where the menu will be included, if non provided the view will be accessible as a top menu.
  • category_icon – Font-Awesome icon name for the category, optional.
  • category_label – The label that will be displayed on the menu, if absent param name will be used
add_separator(category)[source]

Add a separator to the menu, you will sequentially create the menu

Parameters:category – The menu category where the separator will be included.
add_view(baseview, name, href='', icon='', label='', category='', category_icon='', category_label='')[source]

Add your views associated with menus using this method.

Parameters:
  • baseview – A BaseView type class instantiated or not. This method will instantiate the class for you if needed.
  • name – The string name that identifies the menu.
  • href – Override the generated href for the menu. You can use an url string or an endpoint name if non provided default_view from view will be set as href.
  • icon – Font-Awesome icon name, optional.
  • label – The label that will be displayed on the menu, if absent param name will be used
  • category – The menu category where the menu will be included, if non provided the view will be acessible as a top menu.
  • category_icon – Font-Awesome icon name for the category, optional.
  • category_label – The label that will be displayed on the menu, if absent param name will be used

Examples:

appbuilder = AppBuilder(app, db)
# Register a view, rendering a top menu without icon.
appbuilder.add_view(MyModelView(), "My View")
# or not instantiated
appbuilder.add_view(MyModelView, "My View")
# Register a view, a submenu "Other View" from "Other" with a phone icon.
appbuilder.add_view(MyOtherModelView, "Other View", icon='fa-phone', category="Others")
# Register a view, with category icon and translation.
appbuilder.add_view(YetOtherModelView(), "Other View", icon='fa-phone',
                label=_('Other View'), category="Others", category_icon='fa-envelop',
                category_label=_('Other View'))
# Add a link
appbuilder.add_link("google", href="www.google.com", icon = "fa-google-plus")
add_view_no_menu(baseview, endpoint=None, static_folder=None)[source]

Add your views without creating a menu.

Parameters:baseview – A BaseView type class instantiated.
app_icon

Get the App icon location

Returns:String with relative app icon location
app_name

Get the App name

Returns:String with app name
app_theme

Get the App theme name

Returns:String app theme name
get_app

Get current or configured flask app

Returns:Flask App
get_session

Get the current sqlalchemy session.

Returns:SQLAlchemy Session
init_app(app, session)[source]

Will initialize the Flask app, supporting the app factory pattern.

Parameters:
  • app
  • session – The SQLAlchemy session
security_cleanup()[source]

This method is useful if you have changed the name of your menus or classes, changing them will leave behind permissions that are not associated with anything.

You can use it always or just sometimes to perform a security cleanup. Warning this will delete any permission that is no longer part of any registered view or menu.

Remember invoke ONLY AFTER YOU HAVE REGISTERED ALL VIEWS

version

Get the current F.A.B. version

Returns:String with the current F.A.B. version

flask.ext.appbuilder.security.decorators

flask.ext.appbuilder.security.decorators.has_access(f)[source]

Use this decorator to enable granular security permissions to your methods. Permissions will be associated to a role, and roles are associated to users.

By default the permission’s name is the methods name.

flask.ext.appbuilder.security.decorators.permission_name(name)[source]

Use this decorator to override the name of the permission. has_access will use the methods name has the permission name if you want to override this add this decorator to your methods. This is useful if you want to aggregate methods to permissions

It will add ‘_permission_name’ attribute to your method that will be inspected by BaseView to collect your view’s permissions.

Note that you should use @has_access to execute after @permission_name like on the following example.

Use it like this to aggregate permissions for your methods:

class MyModelView(ModelView):
    datamodel = SQLAInterface(MyModel)

    @has_access
    @permission_name('GeneralXPTO_Permission')
    @expose(url='/xpto')
    def xpto(self):
        return "Your on xpto"

    @has_access
    @permission_name('GeneralXPTO_Permission')
    @expose(url='/xpto2')
    def xpto2(self):
        return "Your on xpto2"
Parameters:name – The name of the permission to override

flask.ext.appbuilder.models.decorators

flask.ext.appbuilder.models.decorators.renders(col_name)[source]

Use this decorator to map your custom Model properties to actual Model db properties. As an example:

class MyModel(Model):
    id = Column(Integer, primary_key=True)
    name = Column(String(50), unique = True, nullable=False)
    custom = Column(Integer(20))
    
    @renders('custom')
    def my_custom(self):
        # will render this columns as bold on ListWidget
        return Markup('<b>' + custom + '</b>')
        
class MyModelView(ModelView):
    datamodel = SQLAInterface(MyTable)
    list_columns = ['name', 'my_custom']

flask.ext.appbuilder.baseviews

flask.ext.appbuilder.baseviews.expose(url='/', methods=('GET', ))[source]

Use this decorator to expose views on your view classes.

Parameters:
  • url – Relative URL for the view
  • methods – Allowed HTTP methods. By default only GET is allowed.

BaseView

class flask.ext.appbuilder.baseviews.BaseView[source]

All views inherit from this class. it’s constructor will register your exposed urls on flask as a Blueprint.

This class does not expose any urls, but provides a common base for all views.

Extend this class if you want to expose methods for your own templates

base_permissions = None

List with allowed base permission. Use it like this if you want to restrict your view to readonly:

class MyView(ModelView):
    base_permissions = ['can_list','can_show']
create_blueprint(appbuilder, endpoint=None, static_folder=None)[source]

Create Flask blueprint. You will generally not use it

Parameters:
  • appbuilder – the AppBuilder object
  • endpoint – endpoint override for this blueprint, will assume class name if not provided
  • static_folder – the relative override for static folder, if ommited application will use the appbuilder static
default_view = 'list'

the default view for this BaseView, to be used with url_for (method name)

extra_args = None

dictionary for injecting extra arguments into template

classmethod get_default_url(**kwargs)[source]

Returns the url for this class default endpoint

get_init_inner_views(views)[source]

Sets initialized inner views

get_redirect()[source]

Returns the previous url.

get_uninit_inner_views()[source]

Will return a list with views that need to be initialized. Normally related_views from ModelView

render_template(template, **kwargs)[source]

Use this method on your own endpoints, will pass the extra_args to the templates.

Parameters:
  • template – The template relative path
  • kwargs – arguments to be passed to the template
route_base = None

Override this if you want to define your own relative url

static_folder = 'static'

The static folder relative location

template_folder = 'templates'

The template folder relative location

update_redirect()[source]

Call it on your own endpoint’s to update the back history navigation. If you bypass it, the next submit or back will go over it.

BaseFormView

class flask.ext.appbuilder.baseviews.BaseFormView[source]

Base class FormView’s

default_view = 'this_form_get'

The form view default entry endpoint

edit_widget

Form widget to override

alias of FormWidget

form = None

The WTF form to render

form_columns = None

The form columns to include, if empty will include all

form_fieldsets = None

Form field sets

form_get(form)[source]

Override this method to implement your form processing

form_post(form)[source]

Override this method to implement your form processing

Parameters:form – WTForm form

Return None or a flask response to render a custom template or redirect the user

form_title = ''

The form title to be displayed

BaseModelView

class flask.ext.appbuilder.baseviews.BaseModelView(**kwargs)[source]

The base class of ModelView and ChartView, all properties are inherited Customize ModelView and ChartView overriding this properties

This class supports all the basics for query

base_filters = None

Filter the view use: [[‘column_name’,BaseFilter,’value’],]

example:

def get_user():
    return g.user

class MyView(ModelView):
    datamodel = SQLAInterface(MyTable)
    base_filters = [['created_by', FilterEqualFunction, get_user],
                    ['name', FilterStartsWith, 'a']]
base_order = None

Use this property to set default ordering for lists (‘col_name’,’asc|desc’):

class MyView(ModelView):
    datamodel = SQLAInterface(MyTable)
    base_order = ('my_column_name','asc')
datamodel = None

Your sqla model you must initialize it like:

class MyView(ModelView):
    datamodel = SQLAInterface(MyTable)
label_columns = None

Dictionary of labels for your columns, override this if you want diferent pretify labels

example (will just override the label for name column):

class MyView(ModelView):
    datamodel = SQLAInterface(MyTable)
    label_columns = {'name':'My Name Label Override'}
search_columns = None

List with allowed search columns, if not provided all possible search columns will be used If you want to limit the search (filter) columns possibilities, define it with a list of column names from your model:

class MyView(ModelView):
    datamodel = SQLAInterface(MyTable)
    search_columns = ['name','address']
search_exclude_columns = None

List with columns to exclude from search. Search includes all possible columns by default

search_form = None

To implement your own add WTF form for Search

search_form_extra_fields = None

A dictionary containing column names and a WTForm Form fields to be added to the Add form, these fields do not exist on the model itself ex:

search_form_extra_fields = {‘some_col’:BooleanField(‘Some Col’, default=False)}

search_form_query_rel_fields = None

Add Customized query for related fields on search form. Assign a dictionary where the keys are the column names of the related models to filter, the value for each key, is a list of lists with the same format as base_filter {‘relation col name’:[[‘Related model col’,FilterClass,’Filter Value’],...],...} Add a custom filter to form related fields:

class ContactModelView(ModelView):
    datamodel = SQLAModel(Contact, db.session)
    search_form_query_rel_fields = [('group':[['name',FilterStartsWith,'W']]}
search_widget

Search widget you can override with your own

alias of SearchWidget

BaseCRUDView

class flask.ext.appbuilder.baseviews.BaseCRUDView(**kwargs)[source]

The base class for ModelView, all properties are inherited Customize ModelView overriding this properties

add_columns = None

A list of columns (or model’s methods) to be displayed on the add form view. Use it to control the order of the display

add_exclude_columns = None

A list of columns to exclude from the add form. By default all columns are included.

add_fieldsets = None

add fieldsets django style (look at show_fieldsets for an example)

add_form = None

To implement your own, assign WTF form for Add

add_form_extra_fields = None

A dictionary containing column names and a WTForm Form fields to be added to the Add form, these fields do not exist on the model itself ex:

add_form_extra_fields = {‘some_col’:BooleanField(‘Some Col’, default=False)}

add_form_query_rel_fields = None

Add Customized query for related fields to add form. Assign a dictionary where the keys are the column names of the related models to filter, the value for each key, is a list of lists with the same format as base_filter {‘relation col name’:[[‘Related model col’,FilterClass,’Filter Value’],...],...} Add a custom filter to form related fields:

class ContactModelView(ModelView):
    datamodel = SQLAModel(Contact, db.session)
    add_form_query_rel_fields = {'group':[['name',FilterStartsWith,'W']]}
add_template = 'appbuilder/general/model/add.html'

Your own add jinja2 template for add

add_title = ''

Add Title , if not configured the default is ‘Add ‘ with pretty model name

add_widget

Add widget override

alias of FormWidget

description_columns = None

Dictionary with column descriptions that will be shown on the forms:

class MyView(ModelView):
    datamodel = SQLAModel(MyTable, db.session)

    description_columns = {'name':'your models name column','address':'the address column'}
edit_columns = None

A list of columns (or model’s methods) to be displayed on the edit form view. Use it to control the order of the display

edit_exclude_columns = None

A list of columns to exclude from the edit form. By default all columns are included.

edit_fieldsets = None

edit fieldsets django style (look at show_fieldsets for an example)

edit_form = None

To implement your own, assign WTF form for Edit

edit_form_extra_fields = None

Dictionary to add extra fields to the Edit form using this property

edit_form_query_rel_fields = None

Add Customized query for related fields to edit form. Assign a dictionary where the keys are the column names of the related models to filter, the value for each key, is a list of lists with the same format as base_filter {‘relation col name’:[[‘Related model col’,FilterClass,’Filter Value’],...],...} Add a custom filter to form related fields:

class ContactModelView(ModelView):
    datamodel = SQLAModel(Contact, db.session)
    edit_form_query_rel_fields = {'group':[['name',FilterStartsWith,'W']]}
edit_template = 'appbuilder/general/model/edit.html'

Your own add jinja2 template for edit

edit_title = ''

Edit Title , if not configured the default is ‘Edit ‘ with pretty model name

edit_widget

Edit widget override

alias of FormWidget

formatters_columns = None

Dictionary of formatter used to format the display of columns

formatters_columns = {‘some_date_col’: lambda x: x.isoformat() }

get_init_inner_views()[source]

Get the list of related ModelViews after they have been initialized

get_uninit_inner_views()[source]

Will return a list with views that need to be initialized. Normally related_views from ModelView

list_columns = None

A list of columns (or model’s methods) to be displayed on the list view. Use it to control the order of the display

list_template = 'appbuilder/general/model/list.html'

Your own add jinja2 template for list

list_title = ''

List Title, if not configured the default is ‘List ‘ with pretty model name

list_widget

List widget override

alias of ListWidget

order_columns = None

Allowed order columns

page_size = 10

Use this property to change default page size

post_add(item)[source]

Override this, will be called after update

post_delete(item)[source]

Override this, will be called after delete

post_update(item)[source]

Override this, will be called after update

pre_add(item)[source]

Override this, will be called before add. If an exception is raised by this method, the message is shown to the user and the add operation is aborted.

pre_delete(item)[source]

Override this, will be called before delete If an exception is raised by this method, the message is shown to the user and the delete operation is aborted. Because of this behavior, it can be used as a way to implement more complex logic around deletes. For instance allowing only the original creator of the object to delete it.

pre_update(item)[source]

Override this, this method is called before the update takes place. If an exception is raised by this method, the message is shown to the user and the update operation is aborted. Because of this behavior, it can be used as a way to implement more complex logic around updates. For instance allowing only the original creator of the object to update it.

related_views = None

List with ModelView classes Will be displayed related with this one using relationship sqlalchemy property:

class MyView(ModelView):
    datamodel = SQLAModel(Group, db.session)
    related_views = [MyOtherRelatedView]
show_columns = None

A list of columns (or model’s methods) to be displayed on the show view. Use it to control the order of the display

show_exclude_columns = None

A list of columns to exclude from the show view. By default all columns are included.

show_fieldsets = None

show fieldsets django style [(<’TITLE’|None>, {‘fields’:[<F1>,<F2>,...]}),....]

class MyView(ModelView):
    datamodel = SQLAModel(MyTable, db.session)

    show_fieldsets = [
        ('Summary',{'fields':['name','address','group']}),
        ('Personal Info',{'fields':['birthday','personal_phone'],'expanded':False}),
        ]
show_template = 'appbuilder/general/model/show.html'

Your own add jinja2 template for show

show_title = ''

Show Title , if not configured the default is ‘Show ‘ with pretty model name

show_widget

Show widget override

alias of ShowWidget

validators_columns = None

Dictionary to add your own validators for forms

flask.ext.appbuilder.views

IndexView

class flask.ext.appbuilder.views.IndexView[source]

A simple view that implements the index for the site

SimpleFormView

class flask.ext.appbuilder.views.SimpleFormView[source]

View for presenting your own forms Inherit from this view to provide some base processing for your customized form views.

Notice that this class inherits from BaseView so all properties from the parent class can be overridden also.

Implement form_get and form_post to implement your form pre-processing and post-processing

PublicFormView

class flask.ext.appbuilder.views.PublicFormView[source]

View for presenting your own forms Inherit from this view to provide some base processing for your customized form views.

Notice that this class inherits from BaseView so all properties from the parent class can be overridden also.

Implement form_get and form_post to implement your form pre-processing and post-processing

ModelView

class flask.ext.appbuilder.views.ModelView(**kwargs)[source]

This is the CRUD generic view. If you want to automatically implement create, edit, delete, show, and list from your database tables, inherit your views from this class.

Notice that this class inherits from BaseCRUDView and BaseModelView so all properties from the parent class can be overriden.

action(name, pk)[source]

Action method to handle actions from a show view

action_post()[source]

Action method to handle multiple records selected from a list view

post_add_redirect()[source]

Override this function to control the redirect after add endpoint is called.

post_delete_redirect()[source]

Override this function to control the redirect after edit endpoint is called.

post_edit_redirect()[source]

Override this function to control the redirect after edit endpoint is called.

MultipleView

class flask.ext.appbuilder.views.MultipleView(**kwargs)[source]

Use this view to render multiple views on the same page, exposed on the list endpoint.

example (after defining GroupModelView and ContactModelView):

class MultipleViewsExp(MultipleView):
    views = [GroupModelView, ContactModelView]
list_template = 'appbuilder/general/model/multiple_views.html'

Override this to implement your own template for the list endpoint

views = None

A list of ModelView’s to render on the same page

MasterDetailView

class flask.ext.appbuilder.views.MasterDetailView(**kwargs)[source]

Implements behaviour for controlling two CRUD views linked by PK and FK, in a master/detail type with two lists.

Master view will behave like a left menu:

class DetailView(ModelView):
    datamodel = SQLAInterface(DetailTable, db.session)

class MasterView(MasterDetailView):
    datamodel = SQLAInterface(MasterTable, db.session)
    related_views = [DetailView]
master_div_width = 2

Set to configure bootstrap class for master grid size

CompactCRUDMixin

class flask.ext.appbuilder.views.CompactCRUDMixin(**kwargs)[source]

Mix with ModelView to implement a list with add and edit on the same page.

classmethod del_key(k)[source]

Matching get method for set_key

classmethod get_key(k, default=None)[source]

Matching get method for set_key

classmethod set_key(k, v)[source]

Allows attaching stateless information to the class using the flask session dict

flask.ext.appbuilder.actions

flask.ext.appbuilder.actions.action(name, text, confirmation=None, icon=None, multiple=True, single=True)[source]

Use this decorator to expose actions

Parameters:
  • name – Action name
  • text – Action text.
  • confirmation – Confirmation text. If not provided, action will be executed unconditionally.
  • icon – Font Awesome icon name
  • multiple – If true will display action on list view
  • single – If true will display action on show view

flask.ext.appbuilder.security

BaseSecurityManager

class flask.ext.appbuilder.security.manager.BaseSecurityManager(appbuilder)[source]
add_permission(name)[source]

Adds a permission to the backend, model permission

Parameters:name – name of the permission: ‘can_add’,’can_edit’ etc...
add_permission_role(role, perm_view)[source]

Add permission-ViewMenu object to Role

Parameters:
  • role – The role object
  • perm_view – The PermissionViewMenu object
add_permission_view_menu(permission_name, view_menu_name)[source]

Adds a permission on a view or menu to the backend

Parameters:
  • permission_name – name of the permission to add: ‘can_add’,’can_edit’ etc...
  • view_menu_name – name of the view menu to add
add_permissions_menu(view_menu_name)[source]

Adds menu_access to menu on permission_view_menu

Parameters:view_menu_name – The menu name
add_permissions_view(base_permissions, view_menu)[source]

Adds a permission on a view menu to the backend

Parameters:
  • base_permissions – list of permissions from view (all exposed methods): ‘can_add’,’can_edit’ etc...
  • view_menu – name of the view or menu to add
add_register_user(username, first_name, last_name, email, password='', hashed_password='')[source]

Generic function to add user registration

add_user(username, first_name, last_name, email, role, password='')[source]

Generic function to create user

add_view_menu(name)[source]

Adds a view or menu to the backend, model view_menu param name:

name of the view menu to add
auth_user_db(username, password)[source]

Method for authenticating user, auth db style

Parameters:
  • username – The username
  • password – The password, will be tested against hashed password on db
auth_user_ldap(username, password)[source]

Method for authenticating user, auth LDAP style. depends on ldap module that is not mandatory requirement for F.A.B.

Parameters:
  • username – The username
  • password – The password
auth_user_oauth(userinfo)[source]

OAuth user Authentication

Userinfo:dict with user information the keys have the same name

as User model columns.

auth_user_oid(email)[source]

OpenID user Authentication

auth_user_remote_user(username)[source]

REMOTE_USER user Authentication

auth_view = None

The obj instance for authentication view

authdbview

Override if you want your own Authentication DB view

alias of AuthDBView

authldapview

Override if you want your own Authentication LDAP view

alias of AuthLDAPView

authoauthview

Override if you want your own Authentication OAuth view

alias of AuthOAuthView

authoidview

Override if you want your own Authentication OID view

alias of AuthOIDView

authremoteuserview

Override if you want your own Authentication OAuth view

alias of AuthRemoteUserView

count_users()[source]

Generic function to count the existing users

create_db()[source]

Setups the DB, creates admin and public roles if they don’t exist.

del_permission(name)[source]

Deletes a permission from the backend, model permission

Parameters:name – name of the permission: ‘can_add’,’can_edit’ etc...
del_permission_role(role, perm_view)[source]

Remove permission-ViewMenu object to Role

Parameters:
  • role – The role object
  • perm_view – The PermissionViewMenu object
del_register_user(register_user)[source]

Generic function to delete user registration

del_view_menu(name)[source]

Deletes a ViewMenu from the backend

Parameters:name – name of the ViewMenu
find_permission(name)[source]

Finds and returns a Permission by name

find_permission_view_menu(permission_name, view_menu_name)[source]

Finds and returns a PermissionView by names

find_permissions_view_menu(view_menu)[source]

Finds all permissions from ViewMenu, returns list of PermissionView

Parameters:view_menu – ViewMenu object
Returns:list of PermissionView objects
find_register_user(registration_hash)[source]

Generic function to return user registration

find_user(username=None, email=None)[source]

Generic function find a user by it’s username or email

find_view_menu(name)[source]

Finds and returns a ViewMenu by name

get_all_users()[source]

Generic function that returns all exsiting users

get_oauth_token_key_name(provider)[source]

Returns the token_key name for the oauth provider if none is configured defaults to oauth_token this is configured using OAUTH_PROVIDERS and token_key key.

get_oauth_token_secret_name(provider)[source]

Returns the token_secret name for the oauth provider if none is configured defaults to oauth_secret this is configured using OAUTH_PROVIDERS and token_secret

get_oauth_user_info(provider, resp=None)[source]

Since there are different OAuth API’s with different ways to retrieve user info

get_user_by_id(pk)[source]

Generic function to return user by it’s id (pk)

has_access(permission_name, view_name)[source]

Check if current user or public has access to view or menu

is_item_public(permission_name, view_name)[source]

Check if view has public permissions

Parameters:
  • permission_name – the permission: can_show, can_edit...
  • view_name – the name of the class view (child of BaseView)
lm = None

Flask-Login LoginManager

oauth = None

Flask-OAuth

oauth_remotes = None

Initialized (remote_app) providers dict {‘provider_name’, OBJ }

oauth_tokengetter(token=None)

OAuth tokengetter function override to implement your own tokengetter method

oauth_user_info_getter(f)[source]

Decorator function to be the OAuth user info getter for all the providers, receives provider and response return a dict with the information returned from the provider. The returned user info dict should have it’s keys with the same name as the User Model.

Use it like this an example for GitHub

@appbuilder.sm.oauth_user_info_getter
def my_oauth_user_info(sm, provider, response=None):
    if provider == 'github':
        me = sm.oauth_remotes[provider].get('user')
        return {'username': me.data.get('login')}
    else:
        return {}
oid = None

Flask-OpenID OpenID

permission_model = None

Override to set your own Permission Model

permissionview_model = None

Override to set your own PermissionView Model

registeruser_model = None

Override to set your own RegisterUser Model

registeruser_view = None

The obj instance for registering user view

registeruserdbview

Override if you want your own register user db view

alias of RegisterUserDBView

registeruseroauthview

Override if you want your own register user OAuth view

alias of RegisterUserOAuthView

registeruseroidview

Override if you want your own register user OpenID view

alias of RegisterUserOIDView

reset_password(userid, password)[source]

Change/Reset a user’s password for authdb. Password will be hashed and saved.

Parameters:
  • userid – the user.id to reset the password
  • password – The clear text password to reset and save hashed on the db
resetmypasswordview

Override if you want your own reset my password view

alias of ResetMyPasswordView

resetpasswordview

Override if you want your own reset password view

alias of ResetPasswordView

role_model = None

Override to set your own Role Model

security_cleanup(baseviews, menus)[source]

Will cleanup from the database all unused permissions

Parameters:
  • baseviews – A list of BaseViews class
  • menus – Menu class
set_oauth_session(provider, oauth_response)[source]

Set the current session with OAuth user secrets

update_user(user)[source]

Generic function to update user

Parameters:user – User model to update to database
update_user_auth_stat(user, success=True)[source]

Update authentication successful to user.

Parameters:user – The authenticated user model
user_model = None

Override to set your own User Model

user_view = None

The obj instance for user view

userdbmodelview

Override if you want your own user db view

alias of UserDBModelView

userinfoeditview

Override if you want your own User information edit view

alias of UserInfoEditView

userldapmodelview

Override if you want your own user ldap view

alias of UserLDAPModelView

useroauthmodelview

Override if you want your own user OAuth view

alias of UserOAuthModelView

useroidmodelview

Override if you want your own user OID view

alias of UserOIDModelView

userremoteusermodelview

Override if you want your own user REMOTE_USER view

alias of UserRemoteUserModelView

viewmenu_model = None

Override to set your own ViewMenu Model

BaseRegisterUser

class flask.ext.appbuilder.security.registerviews.BaseRegisterUser[source]

Make your own user registration view and inherit from this class if you want to implement a completely different registration process. If not, just inherit from RegisterUserDBView or RegisterUserOIDView depending on your authentication method. then override SecurityManager property that defines the class to use:

from flask_appbuilder.security.registerviews import RegisterUserDBView

class MyRegisterUserDBView(BaseRegisterUser):
    email_template = 'register_mail.html'
    ...


class MySecurityManager(SecurityManager):
   registeruserdbview = MyRegisterUserDBView

When instantiating AppBuilder set your own SecurityManager class:

appbuilder = AppBuilder(app, db.session, security_manager_class=MySecurityManager)
activation(activation_hash)[source]

Endpoint to expose an activation url, this url is sent to the user by email, when accessed the user is inserted and activated

activation_template = 'appbuilder/general/security/activation.html'

The activation template, shown when the user is activated

add_registration(username, first_name, last_name, email, password='')[source]
Add a registration request for the user.

:rtype : RegisterUser

email_subject = l'Account activation'

The email subject sent to the user

email_template = 'appbuilder/general/security/register_mail.html'

The template used to generate the email sent to the user

error_message = l'Not possible to register you at the moment, try again later'

The message shown on an unsuccessful registration

false_error_message = l'Registration not found'

The message shown on an unsuccessful registration

form_title = l'Fill out the registration form'

The form title

message = l'Registration sent to your email'

The message shown on a successful registration

send_email(register_user)[source]

Method for sending the registration Email to the user

flask.ext.appbuilder.filemanager

flask.ext.appbuilder.filemanager.get_file_original_name(name)[source]

Use this function to get the user’s original filename. Filename is concatenated with <UUID>_sep_<FILE NAME>, to avoid collisions. Use this function on your models on an aditional function

class ProjectFiles(Base):
    id = Column(Integer, primary_key=True)
    file = Column(FileColumn, nullable=False)

    def file_name(self):
        return get_file_original_name(str(self.file))
Parameters:name – The file name from model
Returns:Returns the user’s original filename removes <UUID>_sep_

Aggr Functions for Group By Charts

flask.ext.appbuilder.models.group.aggregate_count(items, col)[source]

Function to use on Group by Charts. accepts a list and returns the count of the list’s items

flask.ext.appbuilder.models.group.aggregate_avg(items, col)[source]

Function to use on Group by Charts. accepts a list and returns the average of the list’s items

flask.ext.appbuilder.models.group.aggregate_sum(items, col)[source]

Function to use on Group by Charts. accepts a list and returns the sum of the list’s items

flask.ext.appbuilder.charts.views

BaseChartView

class flask.ext.appbuilder.charts.views.BaseChartView(**kwargs)[source]

This is the base class for all chart views. Use DirectByChartView or GroupByChartView, override their properties and their base classes (BaseView, BaseModelView, BaseChartView) to customise your charts

chart_3d = 'true'

Will display in 3D?

chart_template = 'appbuilder/general/charts/chart.html'

The chart template, override to implement your own

chart_title = 'Chart'

A title to be displayed on the chart

chart_type = 'PieChart'

The chart type PieChart, ColumnChart, LineChart

chart_widget

Chart widget override to implement your own

alias of ChartWidget

group_by_label = l'Group by'

The label that is displayed for the chart selection

group_bys = {}

New for 0.6.4, on test, don’t use yet

search_widget

Search widget override to implement your own

alias of SearchWidget

width = 400

The width

DirectByChartView

class flask.ext.appbuilder.charts.views.DirectByChartView(**kwargs)[source]

Use this class to display charts with multiple series, based on columns or methods defined on models. You can display multiple charts on the same view.

Default routing point is ‘/chart’

Setup definitions property to configure the chart

Label:(optional) String label to display on chart selection.
Group:String with the column name or method from model.
Formatter:(optional) function that formats the output of ‘group’ key
Series:A list of tuples with the aggregation function and the column name to apply the aggregation

The definitions property respects the following grammar:

definitions = [
        {
         'label': 'label for chart definition',
         'group': '<COLNAME>'|'<MODEL FUNCNAME>',
         'formatter': <FUNC FORMATTER FOR GROUP COL>,
         'series': ['<COLNAME>'|'<MODEL FUNCNAME>',...]
        }, ...
      ]

example:

class CountryDirectChartView(DirectByChartView):
    datamodel = SQLAInterface(CountryStats)
    chart_title = 'Direct Data Example'

    definitions = [
        {
            'label': 'Unemployment',
            'group': 'stat_date',
            'series': ['unemployed_perc',
                'college_perc']
        }
    ]

GroupByChartView

class flask.ext.appbuilder.charts.views.GroupByChartView(**kwargs)[source]
ProcessClass

alias of GroupByProcessData

definitions = []

These charts can display multiple series, based on columns or methods defined on models. You can display multiple charts on the same view. This data can be grouped and aggregated has you like.

Label:(optional) String label to display on chart selection.
Group:String with the column name or method from model.
Formatter:(optional) function that formats the output of ‘group’ key
Series:A list of tuples with the aggregation function and the column name to apply the aggregation
[{
    'label': 'String',
    'group': '<COLNAME>'|'<FUNCNAME>'
    'formatter: <FUNC>
    'series': [(<AGGR FUNC>, <COLNAME>|'<FUNCNAME>'),...]
    }
]

example:

class CountryGroupByChartView(GroupByChartView):
    datamodel = SQLAInterface(CountryStats)
    chart_title = 'Statistics'

definitions = [
    {
        'label': 'Country Stat',
        'group': 'country',
        'series': [(aggregate_avg, 'unemployed_perc'),
               (aggregate_avg, 'population'),
               (aggregate_avg, 'college_perc')
              ]
    }
]
get_group_by_class(definition)[source]

intantiates the processing class (Direct or Grouped) and returns it.

(Deprecated) ChartView

class flask.ext.appbuilder.charts.views.ChartView(**kwargs)[source]

DEPRECATED

Provides a simple (and hopefully nice) way to draw charts on your application.

This will show Google Charts based on group by of your tables.

(Deprecated) TimeChartView

class flask.ext.appbuilder.charts.views.TimeChartView(**kwargs)[source]

DEPRECATED

Provides a simple way to draw some time charts on your application.

This will show Google Charts based on count and group by month and year for your tables.

(Deprecated) DirectChartView

class flask.ext.appbuilder.charts.views.DirectChartView(**kwargs)[source]

DEPRECATED

This class is responsible for displaying a Google chart with direct model values. Chart widget uses json. No group by is processed, example:

class StatsChartView(DirectChartView):
    datamodel = SQLAInterface(Stats)
    chart_title = lazy_gettext('Statistics')
    direct_columns = {'Some Stats': ('X_col_1', 'stat_col_1', 'stat_col_2'),
                      'Other Stats': ('X_col2', 'stat_col_3')}

flask.ext.appbuilder.models.mixins

class flask.ext.appbuilder.models.mixins.BaseMixin[source]
class flask.ext.appbuilder.models.mixins.AuditMixin[source]

Mixin for models, adds 4 columns to stamp, time and user on creation and modification will create the following columns:

Created on:
Changed on:
Created by:
Changed by:

Extra Columns

class flask.ext.appbuilder.models.mixins.FileColumn(*args, **kwargs)[source]

Extends SQLAlchemy to support and mostly identify a File Column

impl

alias of Text

class flask.ext.appbuilder.models.mixins.ImageColumn(thumbnail_size=(20, 20, True), size=(100, 100, True), **kw)[source]

Extends SQLAlchemy to support and mostly identify an Image Column

impl

alias of Text

Generic Data Source (Beta)

flask.ext.appbuilder.models.generic

class flask.ext.appbuilder.models.generic.GenericColumn(col_type, primary_key=False, unique=False, nullable=False)[source]
class flask.ext.appbuilder.models.generic.GenericModel(**kwargs)[source]

Generic Model class to define generic purpose models to use with the framework.

Use GenericSession much like SQLAlchemy’s Session Class. Extend GenericSession to implement specific engine features.

Define your models like:

class MyGenericModel(GenericModel):
    id = GenericColumn(int, primary_key=True)
    age = GenericColumn(int)
    name = GenericColumn(str)
class flask.ext.appbuilder.models.generic.GenericSession[source]

This class is a base, you should subclass it to implement your own generic data source.

Override at least the all method.

GenericSession will implement filter and orders based on your data generation on the all method.

all()[source]

SQLA like ‘all’ method, will populate all rows and apply all filters and orders to it.

clear()[source]

Deletes the entire store

delete_all(model_cls)[source]

Deletes all objects of type model_cls

get(pk)[source]

Returns the object for the key Override it for efficiency.

query(model_cls)[source]

SQLAlchemy query like method