API Reference

flask_appbuilder

AppBuilder

class flask_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, update_perms=True)[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, update_perms=True)[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

  • update_perms – optional, update permissions flag (Boolean) you can use FAB_UPDATE_PERMS config key also

add_api(baseview)[source]

Add a BaseApi class or child to AppBuilder

Parameters

baseview – A BaseApi type class

Returns

The instantiated base view

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.

property app_icon

Get the App icon location

Returns

String with relative app icon location

property app_name

Get the App name

Returns

String with app name

property app_theme

Get the App theme name

Returns

String app theme name

property get_app

Get current or configured flask app

Returns

Flask App

property 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

security_converge(dry=False) → Dict[source]

This method is useful when you use:

  • class_permission_name

  • previous_class_permission_name

  • method_permission_name

  • previous_method_permission_name

migrates all permissions to the new names on all the Roles

Parameters

dry – If True will not change DB

Returns

Dict with all computed necessary operations

property version

Get the current F.A.B. version

Returns

String with the current F.A.B. version

flask_appbuilder.security.decorators

flask_appbuilder.security.decorators.protect(allow_browser_login=False)[source]

Use this decorator to enable granular security permissions to your API methods (BaseApi and child classes). Permissions will be associated to a role, and roles are associated to users.

allow_browser_login will accept signed cookies obtained from the normal MVC app:

class MyApi(BaseApi):
    @expose('/dosonmething', methods=['GET'])
    @protect(allow_browser_login=True)
    @safe
    def do_something(self):
        ....

    @expose('/dosonmethingelse', methods=['GET'])
    @protect()
    @safe
    def do_something_else(self):
        ....

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

flask_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_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_appbuilder.models.decorators

flask_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_appbuilder.api

flask_appbuilder.api.expose(url='/', methods=('GET', ))[source]

Use this decorator to expose API endpoints on your API classes.

Parameters
  • url – Relative URL for the endpoint

  • methods – Allowed HTTP methods. By default only GET is allowed.

flask_appbuilder.api.rison(schema=None)[source]

Use this decorator to parse URI Rison arguments to a python data structure, your method gets the data structure on kwargs[‘rison’]. Response is HTTP 400 if Rison is not correct:

class ExampleApi(BaseApi):
        @expose('/risonjson')
        @rison()
        def rison_json(self, **kwargs):
            return self.response(200, result=kwargs['rison'])

You can additionally pass a JSON schema to validate Rison arguments:

schema = {
    "type": "object",
    "properties": {
        "arg1": {
            "type": "integer"
        }
    }
}

class ExampleApi(BaseApi):
        @expose('/risonjson')
        @rison(schema)
        def rison_json(self, **kwargs):
            return self.response(200, result=kwargs['rison'])
flask_appbuilder.api.safe(f)[source]

A decorator that catches uncaught exceptions and return the response in JSON format (inspired on Superset code)

BaseApi

class flask_appbuilder.api.BaseApi[source]

All apis 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 APIS.

allow_browser_login = False

Will allow flask-login cookie authorization on the API default is False.

apispec_parameter_schemas = None

Set your custom Rison parameter schemas here so that they get registered on the OpenApi spec:

custom_parameter = {
    "type": "object"
    "properties": {
        "name": {
            "type": "string"
        }
    }
}

class CustomApi(BaseApi):
    apispec_parameter_schemas = {
        "custom_parameter": custom_parameter
    }
base_permissions = None

A list of allowed base permissions:

class ExampleApi(BaseApi):
    base_permissions = ['can_get']
class_permission_name = None

Override class permission name default fallback to self.__class__.__name__

csrf_exempt = True

If using flask-wtf CSRFProtect exempt the API from check

exclude_route_methods = {}

Does not register routes for a set of builtin ModelRestApi functions. example:

class ContactModelView(ModelRestApi):
    datamodel = SQLAModel(Contact)
    exclude_route_methods = ("info", "get_list", "get")

The previous examples will only register the put, post and delete routes

get_init_inner_views(views)[source]

Sets initialized inner views

get_method_permission(method_name: str) → str[source]

Returns the permission name for a method

get_uninit_inner_views()[source]

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

method_permission_name = None

Override method permission names, example:

method_permissions_name = {
    'get_list': 'read',
    'get': 'read',
    'put': 'write',
    'post': 'write',
    'delete': 'write'
}
operation_helper(path=None, operations=None, methods=None, func=None, **kwargs)[source]

May mutate operations. :param str path: Path to the resource :param dict operations: A dict mapping HTTP methods to operation object. See :param list methods: A list of methods registered for this path

path_helper(path=None, operations=None, **kwargs)[source]

Works like a apispec plugin May return a path as string and mutate operations dict.

Parameters
Returns

Return value should be a string or None. If a string is returned, it

is set as the path.

previous_class_permission_name = None

If set security converge will replace all permissions tuples with this name by the class_permission_name or self.__class__.__name__

previous_method_permission_name = None

Use same structure as method_permission_name. If set security converge will replace all method permissions by the new ones

resource_name = None

Defines a custom resource name, overrides the inferred from Class name makes no sense to use it with route base

static response(code, **kwargs)[source]

Generic HTTP JSON response method

Parameters
  • code – HTTP code (int)

  • kwargs – Data structure for response (dict)

Returns

HTTP Json response

response_400(message=None)[source]

Helper method for HTTP 400 response

Parameters

message – Error message (str)

Returns

HTTP Json response

response_401()[source]

Helper method for HTTP 401 response

Parameters

message – Error message (str)

Returns

HTTP Json response

response_404()[source]

Helper method for HTTP 404 response

Parameters

message – Error message (str)

Returns

HTTP Json response

response_422(message=None)[source]

Helper method for HTTP 422 response

Parameters

message – Error message (str)

Returns

HTTP Json response

response_500(message=None)[source]

Helper method for HTTP 500 response

Parameters

message – Error message (str)

Returns

HTTP Json response

responses = {'400': {'content': {'application/json': {'schema': {'properties': {'message': {'type': 'string'}}, 'type': 'object'}}}, 'description': 'Bad request'}, '401': {'content': {'application/json': {'schema': {'properties': {'message': {'type': 'string'}}, 'type': 'object'}}}, 'description': 'Unauthorized'}, '404': {'content': {'application/json': {'schema': {'properties': {'message': {'type': 'string'}}, 'type': 'object'}}}, 'description': 'Not found'}, '422': {'content': {'application/json': {'schema': {'properties': {'message': {'type': 'string'}}, 'type': 'object'}}}, 'description': 'Could not process entity'}, '500': {'content': {'application/json': {'schema': {'properties': {'message': {'type': 'string'}}, 'type': 'object'}}}, 'description': 'Fatal error'}}

Override custom OpenApi responses

route_base = None

Define the route base where all methods will suffix from

version = 'v1'

Define the Api version for this resource/class

ModelRestApi

class flask_appbuilder.api.ModelRestApi[source]
add_columns = None

A list of columns (or model’s methods) to be allowed to post

add_exclude_columns = None

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

add_model_schema = None

Override to provide your own marshmallow Schema for JSON to SQLA dumps

add_query_rel_fields = None

Add Customized query for related add fields. 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(ModelRestApi):
    datamodel = SQLAModel(Contact)
    add_query_rel_fields = {'group':[['name',FilterStartsWith,'W']]}
add_title = ''

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

delete(pk)[source]

Delete item from Model — delete:

parameters: - in: path

schema:

type: integer

name: pk

responses:
200:

description: Item deleted content:

application/json:
schema:

type: object properties:

message:

type: string

404:

$ref: ‘#/components/responses/404’

422:

$ref: ‘#/components/responses/422’

500:

$ref: ‘#/components/responses/500’

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 allowed to update

edit_exclude_columns = None

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

edit_model_schema = None

Override to provide your own marshmallow Schema for JSON to SQLA dumps

edit_query_rel_fields = None

Add Customized query for related edit fields. 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(ModelRestApi):
    datamodel = SQLAModel(Contact, db.session)
    edit_query_rel_fields = {'group':[['name',FilterStartsWith,'W']]}
edit_title = ''

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

get(pk, **kwargs)[source]

Get item from Model — get:

parameters: - in: path

schema:

type: integer

name: pk

  • $ref: ‘#/components/parameters/get_item_schema’

responses:
200:

description: Item from Model content:

application/json:
schema:

type: object properties:

label_columns:

type: object

show_columns:

type: array items:

type: string

description_columns:

type: object

show_title:

type: string

id:

type: string

result:

$ref: ‘#/components/schemas/{{self.__class__.__name__}}.get’

400:

$ref: ‘#/components/responses/400’

401:

$ref: ‘#/components/responses/401’

404:

$ref: ‘#/components/responses/404’

422:

$ref: ‘#/components/responses/422’

500:

$ref: ‘#/components/responses/500’

get_list(**kwargs)[source]

Get list of items from Model — get:

parameters: - $ref: ‘#/components/parameters/get_list_schema’ responses:

200:

description: Items from Model content:

application/json:
schema:

type: object properties:

label_columns:

type: object

list_columns:

type: array items:

type: string

description_columns:

type: object

list_title:

type: string

ids:

type: array items:

type: string

order_columns:

type: array items:

type: string

result:

type: array items:

$ref: ‘#/components/schemas/{{self.__class__.__name__}}.get_list’ # noqa

400:

$ref: ‘#/components/responses/400’

401:

$ref: ‘#/components/responses/401’

422:

$ref: ‘#/components/responses/422’

500:

$ref: ‘#/components/responses/500’

info(**kwargs)[source]

Endpoint that renders a response for CRUD REST meta data — get:

parameters: - $ref: ‘#/components/parameters/get_info_schema’ responses:

200:

description: Item from Model content:

application/json:
schema:

type: object properties:

add_columns:

type: object

edit_columns:

type: object

filters:

type: object

permissions:

type: array items:

type: string

400:

$ref: ‘#/components/responses/400’

401:

$ref: ‘#/components/responses/401’

422:

$ref: ‘#/components/responses/422’

500:

$ref: ‘#/components/responses/500’

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_exclude_columns = None

A list of columns to exclude from the get list endpoint. By default all columns are included.

list_model_schema = None

Override to provide your own marshmallow Schema for JSON to SQLA dumps

list_title = ''

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

max_page_size = None

class override for the FAB_API_MAX_SIZE, use special -1 to allow for any page size

model2schemaconverter

alias of flask_appbuilder.api.convert.Model2SchemaConverter

order_columns = None

Allowed order columns

order_rel_fields = None

Impose order on related fields. assign a dictionary where the keys are the related column names:

class ContactModelView(ModelRestApi):
    datamodel = SQLAModel(Contact)
    order_rel_fields = {
        'group': ('name', 'asc')
        'gender': ('name', 'asc')
    }
page_size = 20

Use this property to change default page size

post()[source]

POST item to Model — post:

requestBody:

description: Model schema required: true content:

application/json:
schema:

$ref: ‘#/components/schemas/{{self.__class__.__name__}}.post’

responses:
201:

description: Item inserted content:

application/json:
schema:

type: object properties:

id:

type: string

result:

$ref: ‘#/components/schemas/{{self.__class__.__name__}}.post’

400:

$ref: ‘#/components/responses/400’

401:

$ref: ‘#/components/responses/401’

422:

$ref: ‘#/components/responses/422’

500:

$ref: ‘#/components/responses/500’

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.

pre_delete(item)[source]

Override this, will be called before delete

pre_get(data)[source]

Override this, will be called before data is sent to the requester on get item endpoint. You can use it to mutate the response sent. Note that any new field added will not be reflected on the OpenApi spec.

pre_get_list(data)[source]

Override this, will be called before data is sent to the requester on get list endpoint. You can use it to mutate the response sent Note that any new field added will not be reflected on the OpenApi spec.

pre_update(item)[source]

Override this, this method is called before the update takes place.

put(pk)[source]

PUT item to Model — put:

parameters: - in: path

schema:

type: integer

name: pk

requestBody:

description: Model schema required: true content:

application/json:
schema:

$ref: ‘#/components/schemas/{{self.__class__.__name__}}.put’

responses:
200:

description: Item changed content:

application/json:
schema:

type: object properties:

result:

$ref: ‘#/components/schemas/{{self.__class__.__name__}}.put’

400:

$ref: ‘#/components/responses/400’

401:

$ref: ‘#/components/responses/401’

404:

$ref: ‘#/components/responses/404’

422:

$ref: ‘#/components/responses/422’

500:

$ref: ‘#/components/responses/500’

show_columns = None

A list of columns (or model’s methods) for the get item endpoint. Use it to control the order of the results

show_exclude_columns = None

A list of columns to exclude from the get item endpoint. By default all columns are included.

show_model_schema = None

Override to provide your own marshmallow Schema for JSON to SQLA dumps

show_title = ''

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

validators_columns = None

Dictionary to add your own validators for forms

flask_appbuilder.baseviews

flask_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_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']
class_permission_name = None

Override class permission name default fallback to self.__class__.__name__

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 omitted 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_method_permission(method_name: str) → str[source]

Returns the permission name for a method

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

method_permission_name = None

Override method permission names, example:

method_permissions_name = {
    'get_list': 'read',
    'get': 'read',
    'put': 'write',
    'post': 'write',
    'delete': 'write'
}
previous_class_permission_name = None

If set security cleanup will remove all permissions tuples with this name

previous_method_permission_name = None

Use same structure as method_permission_name. If set security converge will replace all method permissions by the new ones

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_appbuilder.baseviews.BaseFormView[source]

Base class FormView’s

default_view = 'this_form_get'

The form view default entry endpoint

edit_widget

alias of flask_appbuilder.widgets.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_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 different 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

alias of flask_appbuilder.widgets.SearchWidget

BaseCRUDView

class flask_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

alias of flask_appbuilder.widgets.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

alias of flask_appbuilder.widgets.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

alias of flask_appbuilder.widgets.ListWidget

order_columns = None

Allowed order columns

page_size = 25

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.

prefill_form(form, pk)[source]

Override this, will be called only if the current action is rendering an edit form (a GET request), and is used to perform additional action to prefill the form.

This is useful when you have added custom fields that depend on the database contents. Fields that were added by name of a normal column or relationship should work out of the box.

example:

def prefill_form(self, form, pk):
    if form.email.data:
        form.email_confirmation.data = form.email.data
process_form(form, is_created)[source]

Override this, will be called only if the current action is submitting a create/edit form (a POST request), and is used to perform additional action before the form is used to populate the item.

By default does nothing.

example:

def process_form(self, form, is_created):
    if not form.owner:
        form.owner.data = 'n/a'
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

alias of flask_appbuilder.widgets.ShowWidget

validators_columns = None

Dictionary to add your own validators for forms

flask_appbuilder.views

IndexView

class flask_appbuilder.views.IndexView[source]

A simple view that implements the index for the site

SimpleFormView

class flask_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_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_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 overridden.

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

get_action_permission_name(name: str) → str[source]

Get the permission name of an action name

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_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]
get_init_inner_views()[source]

Sets initialized inner views

get_uninit_inner_views()[source]

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

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_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]
list_widget

alias of flask_appbuilder.widgets.ListMasterWidget

master_div_width = 2

Set to configure bootstrap class for master grid size

CompactCRUDMixin

class flask_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_appbuilder.actions

flask_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_appbuilder.security

BaseSecurityManager

class flask_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 or registered email address

  • 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

Parameters

email – user’s email to authenticate

auth_user_remote_user(username)[source]

REMOTE_USER user Authentication

Parameters

username – user’s username for remote auth

auth_view = None

The obj instance for authentication view

authdbview

alias of flask_appbuilder.security.views.AuthDBView

authldapview

alias of flask_appbuilder.security.views.AuthLDAPView

authoauthview

alias of flask_appbuilder.security.views.AuthOAuthView

authoidview

alias of flask_appbuilder.security.views.AuthOIDView

authremoteuserview

alias of flask_appbuilder.security.views.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.

create_jwt_manager(app) → flask_jwt_extended.jwt_manager.JWTManager[source]

Override to implement your custom JWT manager instance

Parameters

app – Flask app

create_login_manager(app) → flask_login.login_manager.LoginManager[source]

Override to implement your custom login manager instance

Parameters

app – Flask app

create_state_transitions(baseviews: List, menus: List) → Dict[source]

Creates a Dict with all the necessary vm/permission transitions

Dict: {

“add”: {(<VM>, <PERM>): ((<VM>, PERM), … )} “del_role_pvm”: ((<VM>, <PERM>), …) “del_views”: (<VM>, … ) “del_perms”: (<PERM>, … )

}

Parameters
  • baseviews – List with all the registered BaseView, BaseApi

  • menus – List with all the menu entries

Returns

Dict with state transitions

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

exist_permission_on_roles(view_name: str, permission_name: str, role_ids: List[int]) → bool[source]

Finds and returns permission views for a group of roles

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)[source]

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

get_public_permissions()[source]

returns all permissions from public role

get_public_role()[source]

returns all permissions from public role

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)

jwt_manager = None

Flask-JWT-Extended

lm = None

Flask-Login LoginManager

oauth = None

Flask-OAuth

oauth_remotes = None

OAuth email whitelists

oauth_tokengetter()

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 {}
oauth_whitelists = {}

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

oid = None

Flask-OpenID OpenID

permission_model = None

Override to set your own Permission Model

permissionmodelview

alias of flask_appbuilder.security.views.PermissionModelView

permissionview_model = None

Override to set your own PermissionView Model

permissionviewmodelview

alias of flask_appbuilder.security.views.PermissionViewModelView

register_views()[source]

Generic function to create the security views

registeruser_model = None

Override to set your own RegisterUser Model

registeruser_view = None

The obj instance for registering user view

registeruserdbview

alias of flask_appbuilder.security.registerviews.RegisterUserDBView

registerusermodelview

alias of flask_appbuilder.security.views.RegisterUserModelView

registeruseroauthview

alias of flask_appbuilder.security.registerviews.RegisterUserOAuthView

registeruseroidview

alias of flask_appbuilder.security.registerviews.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

alias of flask_appbuilder.security.views.ResetMyPasswordView

resetpasswordview

alias of flask_appbuilder.security.views.ResetPasswordView

role_model = None

Override to set your own Role Model

rolemodelview

alias of flask_appbuilder.security.views.RoleModelView

security_api

alias of flask_appbuilder.security.api.SecurityApi

security_cleanup(baseviews, menus)[source]

Will cleanup all unused permissions from the database

Parameters
  • baseviews – A list of BaseViews class

  • menus – Menu class

security_converge(baseviews: List, menus: List, dry=False) → Dict[source]

Converges overridden permissions on all registered views/api will compute all necessary operations from class_permissions_name, previous_class_permission_name, method_permission_name`, previous_method_permission_name class attributes.

Parameters
  • baseviews – List of registered views/apis

  • menus – List of menu items

  • dry – If True will not change DB

Returns

Dict with the necessary operations (state_transitions)

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

  • success – Default to true, if false increments fail_login_count on user model

user_model = None

Override to set your own User Model

user_view = None

The obj instance for user view

userdbmodelview

alias of flask_appbuilder.security.views.UserDBModelView

userinfoeditview

alias of flask_appbuilder.security.views.UserInfoEditView

userldapmodelview

alias of flask_appbuilder.security.views.UserLDAPModelView

useroauthmodelview

alias of flask_appbuilder.security.views.UserOAuthModelView

useroidmodelview

alias of flask_appbuilder.security.views.UserOIDModelView

userremoteusermodelview

alias of flask_appbuilder.security.views.UserRemoteUserModelView

userstatschartview

alias of flask_appbuilder.security.views.UserStatsChartView

viewmenu_model = None

Override to set your own ViewMenu Model

viewmenumodelview

alias of flask_appbuilder.security.views.ViewMenuModelView

BaseRegisterUser

class flask_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_appbuilder.filemanager

flask_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_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_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_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_appbuilder.charts.views

BaseChartView

class flask_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

alias of flask_appbuilder.charts.widgets.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

alias of flask_appbuilder.widgets.SearchWidget

width = 400

The width

DirectByChartView

class flask_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']
        }
    ]
ProcessClass

alias of flask_appbuilder.models.group.DirectProcessData

GroupByChartView

class flask_appbuilder.charts.views.GroupByChartView(**kwargs)[source]
ProcessClass

alias of flask_appbuilder.models.group.GroupByProcessData

chart_widget

alias of flask_appbuilder.charts.widgets.DirectChartWidget

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_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_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_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')}
chart_widget

alias of flask_appbuilder.charts.widgets.DirectChartWidget

flask_appbuilder.models.mixins

class flask_appbuilder.models.mixins.BaseMixin[source]
class flask_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_appbuilder.models.mixins.FileColumn(*args, **kwargs)[source]

Extends SQLAlchemy to support and mostly identify a File Column

impl

alias of sqlalchemy.sql.sqltypes.Text

class flask_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 sqlalchemy.sql.sqltypes.Text

Generic Data Source (Beta)

flask_appbuilder.models.generic

class flask_appbuilder.models.generic.GenericColumn(col_type, primary_key=False, unique=False, nullable=False)[source]
class flask_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_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