INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Create all your database objects (SQLAlchemy specific).
def create_db(): """ Create all your database objects (SQLAlchemy specific). """ from flask_appbuilder.models.sqla import Model engine = current_app.appbuilder.get_session.get_bind(mapper=None, clause=None) Model.metadata.create_all(engine) click.echo(click.style("DB objects created", f...
Flask-AppBuilder package version
def version(): """ Flask-AppBuilder package version """ click.echo( click.style( "F.A.B Version: {0}.".format(current_app.appbuilder.version), bg="blue", fg="white" ) )
Creates all permissions and add them to the ADMIN Role.
def create_permissions(): """ Creates all permissions and add them to the ADMIN Role. """ current_app.appbuilder.add_permissions(update_perms=True) click.echo(click.style("Created all permissions", fg="green"))
List all registered views
def list_views(): """ List all registered views """ echo_header("List of registered views") for view in current_app.appbuilder.baseviews: click.echo( "View:{0} | Route:{1} | Perms:{2}".format( view.__class__.__name__, view.route_base, view.base_permissions ...
List all users on the database
def list_users(): """ List all users on the database """ echo_header("List of users") for user in current_app.appbuilder.sm.get_all_users(): click.echo( "username:{0} | email:{1} | role:{2}".format( user.username, user.email, user.roles ) )
Create a Skeleton application (needs internet connection to github)
def create_app(name, engine): """ Create a Skeleton application (needs internet connection to github) """ try: if engine.lower() == "sqlalchemy": url = urlopen(SQLA_REPO_URL) dirname = "Flask-AppBuilder-Skeleton-master" elif engine.lower() == "mongoengine": ...
Create a Skeleton AddOn (needs internet connection to github)
def create_addon(name): """ Create a Skeleton AddOn (needs internet connection to github) """ try: full_name = "fab_addon_" + name dirname = "Flask-AppBuilder-Skeleton-AddOn-master" url = urlopen(ADDON_REPO_URL) zipfile = ZipFile(BytesIO(url.read())) zipfile.e...
Babel, Extracts and updates all messages marked for translation
def babel_extract(config, input, output, target, keywords): """ Babel, Extracts and updates all messages marked for translation """ click.echo( click.style( "Starting Extractions config:{0} input:{1} output:{2} keywords:{3}".format( config, input, output, keywords...
Babel, Compiles all translations
def babel_compile(target): """ Babel, Compiles all translations """ click.echo(click.style("Starting Compile target:{0}".format(target), fg="green")) os.popen("pybabel compile -f -d {0}".format(target))
Will dynamically import a class from a string path :param class_path: string with class path :return: class
def dynamic_class_import(class_path): """ Will dynamically import a class from a string path :param class_path: string with class path :return: class """ # Split first occurrence of path try: tmp = class_path.split(".") module_path = ".".join(tmp[0:-1]) pa...
Will initialize the Flask app, supporting the app factory pattern. :param app: :param session: The SQLAlchemy session
def init_app(self, app, session): """ Will initialize the Flask app, supporting the app factory pattern. :param app: :param session: The SQLAlchemy session """ app.config.setdefault("APP_NAME", "F.A.B.") app.config.setdefault("APP_THEME", "") ...
Registers indexview, utilview (back function), babel views and Security views.
def _add_admin_views(self): """ Registers indexview, utilview (back function), babel views and Security views. """ self.indexview = self._check_and_init(self.indexview) self.add_view_no_menu(self.indexview) self.add_view_no_menu(UtilView()) self.bm.register_vi...
Registers declared addon's
def _add_addon_views(self): """ Registers declared addon's """ for addon in self._addon_managers: addon_class = dynamic_class_import(addon) if addon_class: # Instantiate manager with appbuilder (self) addon_class = addon_class(s...
Add your views associated with menus using this method. :param baseview: A BaseView type class instantiated or not. This method will instantiate the class for you if needed. :param name: The string name that identifies the menu. :param href: Overr...
def add_view( self, baseview, name, href="", icon="", label="", category="", category_icon="", category_label="", ): """ Add your views associated with menus using this method. :param baseview: A BaseView ty...
Add your own links to menu using this method :param name: The string name that identifies the menu. :param href: Override the generated href for the menu. You can use an url string or an endpoint name :param icon: Font-...
def add_link( self, name, href, icon="", label="", category="", category_icon="", category_label="", baseview=None, ): """ Add your own links to menu using this method :param name: The string nam...
Add your views without creating a menu. :param baseview: A BaseView type class instantiated.
def add_view_no_menu(self, baseview, endpoint=None, static_folder=None): """ Add your views without creating a menu. :param baseview: A BaseView type class instantiated. """ baseview = self._check_and_init(baseview) log.info(LOGMSG_INF_FAB_ADD_VIEW.forma...
Login endpoint for the API returns a JWT and optionally a refresh token --- post: requestBody: required: true content: application/json: schema: type: object properties: username: ...
def login(self): """Login endpoint for the API returns a JWT and optionally a refresh token --- post: requestBody: required: true content: application/json: schema: type: object properties: ...
Security endpoint for the refresh token, so we can obtain a new token without forcing the user to login again --- post: responses: 200: description: Refresh Successful content: application/json: schema: ...
def refresh(self): """ Security endpoint for the refresh token, so we can obtain a new token without forcing the user to login again --- post: responses: 200: description: Refresh Successful content: applic...
Add a registration request for the user. :rtype : RegisterUser
def add_register_user( self, username, first_name, last_name, email, password="", hashed_password="" ): """ Add a registration request for the user. :rtype : RegisterUser """ register_user = self.registeruser_model() register_user.username = username ...
Deletes registration object from database :param register_user: RegisterUser object to delete
def del_register_user(self, register_user): """ Deletes registration object from database :param register_user: RegisterUser object to delete """ try: self.get_session.delete(register_user) self.get_session.commit() return True ...
Finds user by username or email
def find_user(self, username=None, email=None): """ Finds user by username or email """ if username: return ( self.get_session.query(self.user_model) .filter(func.lower(self.user_model.username) == func.lower(username)) .fir...
Generic function to create user
def add_user( self, username, first_name, last_name, email, role, password="", hashed_password="", ): """ Generic function to create user """ try: user = self.user_model() user.first_name = fi...
Finds and returns a Permission by name
def find_permission(self, name): """ Finds and returns a Permission by name """ return ( self.get_session.query(self.permission_model).filter_by(name=name).first() )
Adds a permission to the backend, model permission :param name: name of the permission: 'can_add','can_edit' etc...
def add_permission(self, name): """ Adds a permission to the backend, model permission :param name: name of the permission: 'can_add','can_edit' etc... """ perm = self.find_permission(name) if perm is None: try: perm = ...
Deletes a permission from the backend, model permission :param name: name of the permission: 'can_add','can_edit' etc...
def del_permission(self, name): """ Deletes a permission from the backend, model permission :param name: name of the permission: 'can_add','can_edit' etc... """ perm = self.find_permission(name) if perm: try: self.get_s...
Finds and returns a ViewMenu by name
def find_view_menu(self, name): """ Finds and returns a ViewMenu by name """ return self.get_session.query(self.viewmenu_model).filter_by(name=name).first()
Adds a view or menu to the backend, model view_menu param name: name of the view menu to add
def add_view_menu(self, name): """ Adds a view or menu to the backend, model view_menu param name: name of the view menu to add """ view_menu = self.find_view_menu(name) if view_menu is None: try: view_menu = self.viewme...
Finds and returns a PermissionView by names
def find_permission_view_menu(self, permission_name, view_menu_name): """ Finds and returns a PermissionView by names """ permission = self.find_permission(permission_name) view_menu = self.find_view_menu(view_menu_name) if permission and view_menu: return...
Finds all permissions from ViewMenu, returns list of PermissionView :param view_menu: ViewMenu object :return: list of PermissionView objects
def find_permissions_view_menu(self, view_menu): """ Finds all permissions from ViewMenu, returns list of PermissionView :param view_menu: ViewMenu object :return: list of PermissionView objects """ return ( self.get_session.query(self.permissionv...
Adds a permission on a view or menu to the backend :param permission_name: name of the permission to add: 'can_add','can_edit' etc... :param view_menu_name: name of the view menu to add
def add_permission_view_menu(self, permission_name, view_menu_name): """ Adds a permission on a view or menu to the backend :param permission_name: name of the permission to add: 'can_add','can_edit' etc... :param view_menu_name: name of the v...
Add permission-ViewMenu object to Role :param role: The role object :param perm_view: The PermissionViewMenu object
def add_permission_role(self, role, perm_view): """ Add permission-ViewMenu object to Role :param role: The role object :param perm_view: The PermissionViewMenu object """ if perm_view not in role.permissions: try: ...
Remove permission-ViewMenu object to Role :param role: The role object :param perm_view: The PermissionViewMenu object
def del_permission_role(self, role, perm_view): """ Remove permission-ViewMenu object to Role :param role: The role object :param perm_view: The PermissionViewMenu object """ if perm_view in role.permissions: try: ...
Returns a list of all tables relevant for a bind.
def get_tables_for_bind(self, bind=None): """Returns a list of all tables relevant for a bind.""" result = [] tables = Model.metadata.tables for key in tables: if tables[key].info.get("bind_key") == bind: result.append(tables[key]) return result
Completes a dict with the CRUD urls of the API. :param api_urls: A dict with the urls {'<FUNCTION>':'<URL>',...} :return: A dict with the CRUD urls of the base API.
def _get_api_urls(self, api_urls=None): """ Completes a dict with the CRUD urls of the API. :param api_urls: A dict with the urls {'<FUNCTION>':'<URL>',...} :return: A dict with the CRUD urls of the base API. """ view_name = self.__class__.__name__ api_urls =...
Returns a json-able dict for show
def show_item_dict(self, item): """Returns a json-able dict for show""" d = {} for col in self.show_columns: v = getattr(item, col) if not isinstance(v, (int, float, string_types)): v = str(v) d[col] = v return d
Returns list of (pk, object) nice to use on select2. Use only for related columns. Always filters with add_form_query_rel_fields, and accepts extra filters on endpoint arguments. :param col_name: The related column name :return: JSON response
def api_column_add(self, col_name): """ Returns list of (pk, object) nice to use on select2. Use only for related columns. Always filters with add_form_query_rel_fields, and accepts extra filters on endpoint arguments. :param col_name: The related column n...
Returns list of (pk, object) nice to use on select2. Use only for related columns. Always filters with edit_form_query_rel_fields, and accepts extra filters on endpoint arguments. :param col_name: The related column name :return: JSON response
def api_column_edit(self, col_name): """ Returns list of (pk, object) nice to use on select2. Use only for related columns. Always filters with edit_form_query_rel_fields, and accepts extra filters on endpoint arguments. :param col_name: The related column...
Action method to handle actions from a show view
def action(self, name, pk): """ Action method to handle actions from a show view """ pk = self._deserialize_pk_if_composite(pk) if self.appbuilder.sm.has_access(name, self.__class__.__name__): action = self.actions.get(name) return action.func(self.dat...
Action method to handle multiple records selected from a list view
def action_post(self): """ Action method to handle multiple records selected from a list view """ name = request.form["action"] pks = request.form.getlist("rowid") if self.appbuilder.sm.has_access(name, self.__class__.__name__): action = self.actions.get(n...
Allows attaching stateless information to the class using the flask session dict
def set_key(cls, k, v): """Allows attaching stateless information to the class using the flask session dict """ k = cls.__name__ + "__" + k session[k] = v
Matching get method for ``set_key``
def get_key(cls, k, default=None): """Matching get method for ``set_key`` """ k = cls.__name__ + "__" + k if k in session: return session[k] else: return default
Matching get method for ``set_key``
def del_key(cls, k): """Matching get method for ``set_key`` """ k = cls.__name__ + "__" + k session.pop(k)
get joined base filter and current active filter for query
def _get_list_widget(self, **args): """ get joined base filter and current active filter for query """ widgets = super(CompactCRUDMixin, self)._get_list_widget(**args) session_form_widget = self.get_key("session_form_widget", None) form_widget = None if session_form_widget == "a...
Add select load options to query. The goal is to only SQL select what is requested :param query: SQLAlchemy Query obj :param select_columns: (list) of columns :return: SQLAlchemy Query obj
def _query_select_options(self, query, select_columns=None): """ Add select load options to query. The goal is to only SQL select what is requested :param query: SQLAlchemy Query obj :param select_columns: (list) of columns :return: SQLAlchemy Query obj "...
QUERY :param filters: dict with filters {<col_name>:<value,...} :param order_column: name of the column to order :param order_direction: the direction to order <'asc'|'desc'> :param page: the current page ...
def query( self, filters=None, order_column="", order_direction="", page=None, page_size=None, select_columns=None, ): """ QUERY :param filters: dict with filters {<col_name>:<value,...} :param order_...
Returns all model's columns except pk or fk
def get_user_columns_list(self): """ Returns all model's columns except pk or fk """ ret_lst = list() for col_name in self.get_columns_list(): if (not self.is_pk(col_name)) and (not self.is_fk(col_name)): ret_lst.append(col_name) return ret...
Saves an image File :param data: FileStorage from Flask form upload field :param filename: Filename with full path
def save_file(self, data, filename, size=None, thumbnail_size=None): """ Saves an image File :param data: FileStorage from Flask form upload field :param filename: Filename with full path """ max_size = size or self.max_size thumbnail_size = thumbnai...
Resizes the image :param image: The image object :param size: size is PIL tuple (width, heigth, force) ex: (200,100,True)
def resize(self, image, size): """ Resizes the image :param image: The image object :param size: size is PIL tuple (width, heigth, force) ex: (200,100,True) """ (width, height, force) = size if image.size[0] > width or image.size[1] > height: ...
A decorator that catches uncaught exceptions and return the response in JSON format (inspired on Superset code)
def safe(f): """ A decorator that catches uncaught exceptions and return the response in JSON format (inspired on Superset code) """ def wraps(self, *args, **kwargs): try: return f(self, *args, **kwargs) except BadRequest as e: return self.response_400(messag...
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(schema=None): """ 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('/ris...
Use this decorator to set a new merging response function to HTTP endpoints candidate function must have the following signature and be childs of BaseApi: ``` def merge_some_function(self, response, rison_args): ``` :param func: Name of the merge function where ...
def merge_response_func(func, key): """ Use this decorator to set a new merging response function to HTTP endpoints candidate function must have the following signature and be childs of BaseApi: ``` def merge_some_function(self, response, rison_args): ```...
Use this decorator to expose API endpoints on your API classes. :param url: Relative URL for the endpoint :param methods: Allowed HTTP methods. By default only GET is allowed.
def expose(url="/", methods=("GET",)): """ Use this decorator to expose API endpoints on your API classes. :param url: Relative URL for the endpoint :param methods: Allowed HTTP methods. By default only GET is allowed. """ def wrap(f): if not hasattr...
Works like a apispec plugin May return a path as string and mutate operations dict. :param str path: Path to the resource :param dict operations: A `dict` mapping HTTP methods to operation object. See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#ope...
def path_helper(self, path=None, operations=None, **kwargs): """ Works like a apispec plugin May return a path as string and mutate operations dict. :param str path: Path to the resource :param dict operations: A `dict` mapping HTTP methods to operation object. See ...
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
def operation_helper( self, path=None, operations=None, methods=None, func=None, **kwargs ): """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 r...
Generic HTTP JSON response method :param code: HTTP code (int) :param kwargs: Data structure for response (dict) :return: HTTP Json response
def response(code, **kwargs): """ Generic HTTP JSON response method :param code: HTTP code (int) :param kwargs: Data structure for response (dict) :return: HTTP Json response """ _ret_json = jsonify(kwargs) resp = make_response(_ret_json, code) ...
Auto generates pretty label_columns from list of columns
def _gen_labels_columns(self, list_columns): """ Auto generates pretty label_columns from list of columns """ for col in list_columns: if not self.label_columns.get(col): self.label_columns[col] = self._prettify_column(col)
Prepares dict with labels to be JSON serializable
def _label_columns_json(self, cols=None): """ Prepares dict with labels to be JSON serializable """ ret = {} cols = cols or [] d = {k: v for (k, v) in self.label_columns.items() if k in cols} for key, value in d.items(): ret[key] = as_unicode(_(val...
Init Titles if not defined
def _init_titles(self): """ Init Titles if not defined """ super(ModelRestApi, self)._init_titles() class_name = self.datamodel.model_name if not self.list_title: self.list_title = "List " + self._prettify_name(class_name) if not self.add_title: ...
Init Properties
def _init_properties(self): """ Init Properties """ super(ModelRestApi, self)._init_properties() # Reset init props self.description_columns = self.description_columns or {} self.list_exclude_columns = self.list_exclude_columns or [] self.show_exclude_...
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: ...
def info(self, **kwargs): """ 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: ...
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:...
def get(self, pk, **kwargs): """Get item from Model --- get: parameters: - in: path schema: type: integer name: pk - $ref: '#/components/parameters/get_item_schema' responses: 200: description...
Get list of items from Model --- get: parameters: - $ref: '#/components/parameters/get_list_schema' responses: 200: description: Items from Model content: application/json: schema: ...
def get_list(self, **kwargs): """Get list of items from Model --- get: parameters: - $ref: '#/components/parameters/get_list_schema' responses: 200: description: Items from Model content: application/json: ...
POST item to Model --- post: requestBody: description: Model schema required: true content: application/json: schema: $ref: '#/components/schemas/{{self.__class__.__name__}}.post' responses: ...
def post(self): """POST item to Model --- post: requestBody: description: Model schema required: true content: application/json: schema: $ref: '#/components/schemas/{{self.__class__.__name__}}.post' ...
POST item to Model --- put: parameters: - in: path schema: type: integer name: pk requestBody: description: Model schema required: true content: application/json: schema:...
def put(self, pk): """POST item to Model --- put: parameters: - in: path schema: type: integer name: pk requestBody: description: Model schema required: true content: application...
Delete item from Model --- delete: parameters: - in: path schema: type: integer name: pk responses: 200: description: Item deleted content: application/json: sche...
def delete(self, pk): """Delete item from Model --- delete: parameters: - in: path schema: type: integer name: pk responses: 200: description: Item deleted content: applica...
Helper function to handle rison page arguments, sets defaults and impose FAB_API_MAX_PAGE_SIZE :param rison_args: :return: (tuple) page, page_size
def _handle_page_args(self, rison_args): """ Helper function to handle rison page arguments, sets defaults and impose FAB_API_MAX_PAGE_SIZE :param rison_args: :return: (tuple) page, page_size """ page = rison_args.get(API_PAGE_INDEX_RIS_KEY, 0...
Help function to handle rison order arguments :param rison_args: :return:
def _handle_order_args(self, rison_args): """ Help function to handle rison order arguments :param rison_args: :return: """ order_column = rison_args.get(API_ORDER_COLUMN_RIS_KEY, "") order_direction = rison_args.get(API_ORDER_DIRECTION_RIS_KEY, "...
Prepares dict with col descriptions to be JSON serializable
def _description_columns_json(self, cols=None): """ Prepares dict with col descriptions to be JSON serializable """ ret = {} cols = cols or [] d = {k: v for (k, v) in self.description_columns.items() if k in cols} for key, value in d.items(): ret[k...
Return a dict with field details ready to serve as a response :param field: marshmallow field :return: dict with field details
def _get_field_info(self, field, filter_rel_field, page=None, page_size=None): """ Return a dict with field details ready to serve as a response :param field: marshmallow field :return: dict with field details """ ret = dict() ret["name"] = field....
Returns a dict with fields detail from a marshmallow schema :param cols: list of columns to show info for :param model_schema: Marshmallow model schema :param filter_rel_fields: expects add_query_rel_fields or edit_query_rel_fields :param ...
def _get_fields_info(self, cols, model_schema, filter_rel_fields, **kwargs): """ Returns a dict with fields detail from a marshmallow schema :param cols: list of columns to show info for :param model_schema: Marshmallow model schema :param filter_rel_fields: expe...
Return a list of values for a related field :param field: Marshmallow field :param filter_rel_field: Filters for the related field :param page: The page index :param page_size: The page size :return: (int, list) total record count and list of dict with id and value
def _get_list_related_field( self, field, filter_rel_field, page=None, page_size=None ): """ Return a list of values for a related field :param field: Marshmallow field :param filter_rel_field: Filters for the related field :param page: The page index :pa...
Merge a model with a python data structure This is useful to turn PUT method into a PATCH also :param model_item: SQLA Model :param data: python data structure :return: python data structure
def _merge_update_item(self, model_item, data): """ Merge a model with a python data structure This is useful to turn PUT method into a PATCH also :param model_item: SQLA Model :param data: python data structure :return: python data structure """ d...
Creates a WTForm field for many to one related fields, will use a Select box based on a query. Will only work with SQLAlchemy interface.
def _convert_many_to_one(self, col_name, label, description, lst_validators, filter_rel_fields, form_props): """ Creates a WTForm field for many to one related fields, will use a Select box based on a query. Will only ...
Converts a model to a form given :param label_columns: A dictionary with the column's labels. :param inc_columns: A list with the columns to include :param description_columns: A dictionary with a description for cols. :par...
def create_form(self, label_columns=None, inc_columns=None, description_columns=None, validators_columns=None, extra_fields=None, filter_rel_fields=None): """ Converts a model to a form given :param label_columns: A dictionary with...
Returns the object for the key Override it for efficiency.
def get(self, pk): """ Returns the object for the key Override it for efficiency. """ for item in self.store.get(self.query_class): # coverts pk value to correct type pk = item.properties[item.pk].col_type(pk) if getattr(item, item.pk) ...
SQLAlchemy query like method
def query(self, model_cls): """ SQLAlchemy query like method """ self._filters_cmd = list() self.query_filters = list() self._order_by_cmd = None self._offset = 0 self._limit = 0 self.query_class = model_cls._name return self
SQLA like 'all' method, will populate all rows and apply all filters and orders to it.
def all(self): """ SQLA like 'all' method, will populate all rows and apply all filters and orders to it. """ items = list() if not self._filters_cmd: items = self.store.get(self.query_class) else: for item in self.store.get(self.qu...
Arguments are passed like: _oc_<VIEW_NAME>=<COL_NAME>&_od_<VIEW_NAME>='asc'|'desc'
def link_order_filter(self, column, modelview_name): """ Arguments are passed like: _oc_<VIEW_NAME>=<COL_NAME>&_od_<VIEW_NAME>='asc'|'desc' """ new_args = request.view_args.copy() args = request.args.copy() if ("_oc_" + modelview_name) in args: ...
Arguments are passed like: page_<VIEW_NAME>=<PAGE_NUMBER>
def link_page_filter(self, page, modelview_name): """ Arguments are passed like: page_<VIEW_NAME>=<PAGE_NUMBER> """ new_args = request.view_args.copy() args = request.args.copy() args["page_" + modelview_name] = page return url_for( request.endpoin...
Arguments are passed like: psize_<VIEW_NAME>=<PAGE_NUMBER>
def link_page_size_filter(self, page_size, modelview_name): """ Arguments are passed like: psize_<VIEW_NAME>=<PAGE_NUMBER> """ new_args = request.view_args.copy() args = request.args.copy() args["psize_" + modelview_name] = page_size return url_for( re...
Resets a user's password
def reset_password(app, appbuilder, username, password): """ Resets a user's password """ _appbuilder = import_application(app, appbuilder) user = _appbuilder.sm.find_user(username=username) if not user: click.echo("User {0} not found.".format(username)) else: _appbuilder...
Creates an admin user
def create_admin(app, appbuilder, username, firstname, lastname, email, password): """ Creates an admin user """ auth_type = { c.AUTH_DB: "Database Authentications", c.AUTH_OID: "OpenID Authentication", c.AUTH_LDAP: "LDAP Authentication", c.AUTH_REMOTE_USER: "WebServe...
Create a user
def create_user(app, appbuilder, role, username, firstname, lastname, email, password): """ Create a user """ _appbuilder = import_application(app, appbuilder) role_object = _appbuilder.sm.find_role(role) user = _appbuilder.sm.add_user( username, firstname, lastname, email, role_obje...
Runs Flask dev web server.
def run(app, appbuilder, host, port, debug): """ Runs Flask dev web server. """ _appbuilder = import_application(app, appbuilder) _appbuilder.get_app.run(host=host, port=port, debug=debug)
Create all your database objects (SQLAlchemy specific).
def create_db(app, appbuilder): """ Create all your database objects (SQLAlchemy specific). """ from flask_appbuilder.models.sqla import Base _appbuilder = import_application(app, appbuilder) engine = _appbuilder.get_session.get_bind(mapper=None, clause=None) Base.metadata.create_all(en...
Flask-AppBuilder package version
def version(app, appbuilder): """ Flask-AppBuilder package version """ _appbuilder = import_application(app, appbuilder) click.echo( click.style( "F.A.B Version: {0}.".format(_appbuilder.version), bg="blue", fg="white" ) )
Cleanup unused permissions from views and roles.
def security_cleanup(app, appbuilder): """ Cleanup unused permissions from views and roles. """ _appbuilder = import_application(app, appbuilder) _appbuilder.security_cleanup() click.echo(click.style("Finished security cleanup", fg="green"))
List all registered views
def list_views(app, appbuilder): """ List all registered views """ _appbuilder = import_application(app, appbuilder) echo_header("List of registered views") for view in _appbuilder.baseviews: click.echo( "View:{0} | Route:{1} | Perms:{2}".format( view.__cl...
List all users on the database
def list_users(app, appbuilder): """ List all users on the database """ _appbuilder = import_application(app, appbuilder) echo_header("List of users") for user in _appbuilder.sm.get_all_users(): click.echo( "username:{0} | email:{1} | role:{2}".format( use...
Copies flask-appbuilder static files to your projects static folder
def collect_static(static_folder): """ Copies flask-appbuilder static files to your projects static folder """ appbuilder_static_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), "static/appbuilder" ) app_static_path = os.path.join(os.getcwd(), static_folder) if no...
Function to use on Group by Charts. accepts a list and returns the average of the list's items
def aggregate_avg(items, col): """ Function to use on Group by Charts. accepts a list and returns the average of the list's items """ try: return aggregate_sum(items, col) / aggregate_count(items, col) except Exception: log.warning(c.LOGMSG_WAR_DBI_AVG_ZERODIV) re...
Will return a dict with Google JSON structure for charts The Google structure:: { cols: [{id:<COL_NAME>, label:<LABEL FOR COL>, type: <COL TYPE>}, ...] rows: [{c: [{v: <COL VALUE}, ...], ... ] } :param data: :...
def to_json(self, data, labels=None): """ Will return a dict with Google JSON structure for charts The Google structure:: { cols: [{id:<COL_NAME>, label:<LABEL FOR COL>, type: <COL TYPE>}, ...] rows: [{c: [{v: <COL VALUE}, ...], ....
Create Flask blueprint. You will generally not use it :param appbuilder: the AppBuilder object :param endpoint: endpoint override for this blueprint, will assume class name if not provided :param static_folder: the relative...
def create_blueprint(self, appbuilder, endpoint=None, static_folder=None): """ Create Flask blueprint. You will generally not use it :param appbuilder: the AppBuilder object :param endpoint: endpoint override for this blueprint, w...
Use this method on your own endpoints, will pass the extra_args to the templates. :param template: The template relative path :param kwargs: arguments to be passed to the template
def render_template(self, template, **kwargs): """ Use this method on your own endpoints, will pass the extra_args to the templates. :param template: The template relative path :param kwargs: arguments to be passed to the template """ kwargs["base...
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.
def update_redirect(self): """ 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. """ page_history = Stack(session.get("page_history", [])) page_history.push(request.url) session...
Returns the previous url.
def get_redirect(self): """ Returns the previous url. """ index_url = self.appbuilder.get_url_for_index page_history = Stack(session.get("page_history", [])) if page_history.pop() is None: return index_url session["page_history"] = page_history.to...
Prepares dict with labels to be JSON serializable
def _label_columns_json(self): """ Prepares dict with labels to be JSON serializable """ ret = {} for key, value in list(self.label_columns.items()): ret[key] = as_unicode(value.encode("UTF-8")) return ret
Init forms for Add and Edit
def _init_forms(self): """ Init forms for Add and Edit """ super(BaseCRUDView, self)._init_forms() conv = GeneralModelConverter(self.datamodel) if not self.add_form: self.add_form = conv.create_form( self.label_columns, self...
Init Properties
def _init_properties(self): """ Init Properties """ super(BaseCRUDView, self)._init_properties() # Reset init props self.related_views = self.related_views or [] self._related_views = self._related_views or [] self.description_columns = self.descriptio...
:return: Returns a dict with 'related_views' key with a list of Model View widgets
def _get_related_views_widgets( self, item, orders=None, pages=None, page_sizes=None, widgets=None, **args ): """ :return: Returns a dict with 'related_views' key with a list of Model View widgets """ widgets = widgets or {} widgets...