INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Add a registration request for the user.
def add_registration(self, username, first_name, last_name, email, password=""): """ Add a registration request for the user. :rtype : RegisterUser """ register_user = self.appbuilder.sm.add_register_user( username, first_name, last_name, email, password ...
Endpoint to expose an activation url this url is sent to the user by email when accessed the user is inserted and activated
def activation(self, activation_hash): """ Endpoint to expose an activation url, this url is sent to the user by email, when accessed the user is inserted and activated """ reg = self.appbuilder.sm.find_register_user(activation_hash) if not reg: ...
Hackish method to make use of oid. login_handler decorator.
def oid_login_handler(self, f, oid): """ Hackish method to make use of oid.login_handler decorator. """ if request.args.get("openid_complete") != u"yes": return f(False) consumer = Consumer(SessionWrapper(self), oid.store_factory()) openid_response = consu...
Process the Python data applied to this field and store the result. This will be called during form construction by the form s kwargs or obj argument.
def process_data(self, value): """ Process the Python data applied to this field and store the result. This will be called during form construction by the form's `kwargs` or `obj` argument. Converting ORM object to primary key for client form. :param value: The python o...
Process data received over the wire from a form. This will be called during form construction with data supplied through the formdata argument.
def process_formdata(self, valuelist): """ Process data received over the wire from a form. This will be called during form construction with data supplied through the `formdata` argument. Converting primary key to ORM for server processing. :param valuelist: A list of ...
intantiates the processing class ( Direct or Grouped ) and returns it.
def get_group_by_class(self, definition): """ intantiates the processing class (Direct or Grouped) and returns it. """ group_by = definition["group"] series = definition["series"] if "formatter" in definition: formatter = {group_by: definition["formatter"]...
Get page arguments returns a dictionary { <VIEW_NAME >: PAGE_NUMBER }
def get_page_args(): """ Get page arguments, returns a dictionary { <VIEW_NAME>: PAGE_NUMBER } Arguments are passed: page_<VIEW_NAME>=<PAGE_NUMBER> """ pages = {} for arg in request.args: re_match = re.findall("page_(.*)", arg) if re_match: pages[re_...
Get page size arguments returns an int { <VIEW_NAME >: PAGE_NUMBER }
def get_page_size_args(): """ Get page size arguments, returns an int { <VIEW_NAME>: PAGE_NUMBER } Arguments are passed: psize_<VIEW_NAME>=<PAGE_SIZE> """ page_sizes = {} for arg in request.args: re_match = re.findall("psize_(.*)", arg) if re_match: ...
Get order arguments return a dictionary { <VIEW_NAME >: ( ORDER_COL ORDER_DIRECTION ) }
def get_order_args(): """ Get order arguments, return a dictionary { <VIEW_NAME>: (ORDER_COL, ORDER_DIRECTION) } Arguments are passed like: _oc_<VIEW_NAME>=<COL_NAME>&_od_<VIEW_NAME>='asc'|'desc' """ orders = {} for arg in request.args: re_match = re.findall("_oc_(.*)",...
Creates ModelSchema marshmallow - sqlalchemy
def _meta_schema_factory(self, columns, model, class_mixin): """ Creates ModelSchema marshmallow-sqlalchemy :param columns: a list of columns to mix :param model: Model :param class_mixin: a marshamallow Schema to mix :return: ModelSchema """ _model =...
Creates a Marshmallow ModelSchema class
def convert(self, columns, model=None, nested=True, enum_dump_by_name=False): """ Creates a Marshmallow ModelSchema class :param columns: List with columns to include, if empty converts all on model :param model: Override Model to convert :param nested: Generate relation wi...
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.
def protect(allow_browser_login=False): """ 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 obtaine...
Use this decorator to enable granular security permissions to your methods. Permissions will be associated to a role and roles are associated to users.
def has_access(f): """ 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. """ if hasattr(f, '_permission_name'): permis...
Use this decorator to enable granular security permissions to your API methods. Permissions will be associated to a role and roles are associated to users.
def has_access_api(f): """ Use this decorator to enable granular security permissions to your API methods. Permissions will be associated to a role, and roles are associated to users. By default the permission's name is the methods name. this will return a message and HTTP 401 is c...
Use this decorator to expose actions
def action(name, text, confirmation=None, icon=None, multiple=True, single=True): """ Use this decorator to expose actions :param name: Action name :param text: Action text. :param confirmation: Confirmation text. If not provided, action will be e...
Default function to return the current user oauth token from session cookie.
def _oauth_tokengetter(token=None): """ Default function to return the current user oauth token from session cookie. """ token = session.get("oauth") log.debug("Token Get: {0}".format(token)) return token
Override to implement your custom login manager instance
def create_login_manager(self, app) -> LoginManager: """ Override to implement your custom login manager instance :param app: Flask app """ lm = LoginManager(app) lm.login_view = "login" lm.user_loader(self.load_user) return lm
Override to implement your custom JWT manager instance
def create_jwt_manager(self, app) -> JWTManager: """ Override to implement your custom JWT manager instance :param app: Flask app """ jwt_manager = JWTManager() jwt_manager.init_app(app) jwt_manager.user_loader_callback_loader(self.load_user) retu...
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.
def oauth_user_info_getter(self, f): """ 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...
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.
def get_oauth_token_key_name(self, provider): """ 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. """ for _provider in self.oauth_providers: ...
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
def get_oauth_token_secret_name(self, provider): """ 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 """ for _provider in self.oauth_providers: ...
Set the current session with OAuth user secrets
def set_oauth_session(self, provider, oauth_response): """ Set the current session with OAuth user secrets """ # Get this provider key names for token_key and token_secret token_key = self.appbuilder.sm.get_oauth_token_key_name(provider) token_secret = self.appbuilder...
Since there are different OAuth API s with different ways to retrieve user info
def get_oauth_user_info(self, provider, resp): """ Since there are different OAuth API's with different ways to retrieve user info """ # for GITHUB if provider == "github" or provider == "githublocal": me = self.appbuilder.sm.oauth_remotes[provider].ge...
Setups the DB creates admin and public roles if they don t exist.
def create_db(self): """ Setups the DB, creates admin and public roles if they don't exist. """ self.add_role(self.auth_role_admin) self.add_role(self.auth_role_public) if self.count_users() == 0: log.warning(LOGMSG_WAR_SEC_NO_USER)
Change/ Reset a user s password for authdb. Password will be hashed and saved.
def reset_password(self, userid, password): """ Change/Reset a user's password for authdb. Password will be hashed and saved. :param userid: the user.id to reset the password :param password: The clear text password to reset and sa...
Update authentication successful to user.
def update_user_auth_stat(self, user, success=True): """ Update authentication successful to user. :param user: The authenticated user model :param success: Default to true, if false increments fail_login_count on user model """ ...
Method for authenticating user auth db style
def auth_user_db(self, username, password): """ Method for authenticating user, auth db style :param username: The username or registered email address :param password: The password, will be tested against hashed password on db """ ...
Searches LDAP for user assumes ldap_search is set.
def _search_ldap(self, ldap, con, username): """ Searches LDAP for user, assumes ldap_search is set. :param ldap: The ldap module reference :param con: The ldap connection :param username: username to match with auth_ldap_uid_field :return: ldap objec...
If using AUTH_LDAP_BIND_USER bind this user before performing search: param ldap: The ldap module reference: param con: The ldap connection
def _bind_indirect_user(self, ldap, con): """ If using AUTH_LDAP_BIND_USER bind this user before performing search :param ldap: The ldap module reference :param con: The ldap connection """ indirect_user = self.auth_ldap_bind_user if indirect_user: ...
Private to bind/ Authenticate a user. If AUTH_LDAP_BIND_USER exists then it will bind first with it next will search the LDAP server using the username with UID and try to bind to it ( OpenLDAP ). If AUTH_LDAP_BIND_USER does not exit will bind with username/ password
def _bind_ldap(self, ldap, con, username, password): """ Private to bind/Authenticate a user. If AUTH_LDAP_BIND_USER exists then it will bind first with it, next will search the LDAP server using the username with UID and try to bind to it (OpenLDAP). ...
Method for authenticating user auth LDAP style. depends on ldap module that is not mandatory requirement for F. A. B.
def auth_user_ldap(self, username, password): """ Method for authenticating user, auth LDAP style. depends on ldap module that is not mandatory requirement for F.A.B. :param username: The username :param password: The p...
OpenID user Authentication
def auth_user_oid(self, email): """ OpenID user Authentication :param email: user's email to authenticate :type self: User model """ user = self.find_user(email=email) if user is None or (not user.is_active): log.info(LOGMSG_WAR_SEC_LOGIN_...
REMOTE_USER user Authentication
def auth_user_remote_user(self, username): """ REMOTE_USER user Authentication :param username: user's username for remote auth :type self: User model """ user = self.find_user(username=username) # User does not exist, create one if auto user registr...
OAuth user Authentication
def auth_user_oauth(self, userinfo): """ OAuth user Authentication :userinfo: dict with user information the keys have the same name as User model columns. """ if "username" in userinfo: user = self.find_user(username=userinfo["username"]) ...
Check if view has public permissions
def is_item_public(self, permission_name, view_name): """ Check if view has public permissions :param permission_name: the permission: can_show, can_edit... :param view_name: the name of the class view (child of BaseView) """ p...
Check if current user or public has access to view or menu
def has_access(self, permission_name, view_name): """ Check if current user or public has access to view or menu """ if current_user.is_authenticated: return self._has_view_access(g.user, permission_name, view_name) elif current_user_jwt: return self._...
Returns all current user permissions on a certain view/ resource: param view_name: The name of the view/ resource/ menu: return: ( list ) with permissions
def get_user_permissions_on_view(view_name): """ Returns all current user permissions on a certain view/resource :param view_name: The name of the view/resource/menu :return: (list) with permissions """ _ret = list() if current_user.is_authenticat...
Adds a permission on a view menu to the backend
def add_permissions_view(self, base_permissions, view_menu): """ Adds a permission on a view menu to the backend :param base_permissions: list of permissions from view (all exposed methods): 'can_add','can_edit' etc... :param view_menu: ...
Adds menu_access to menu on permission_view_menu
def add_permissions_menu(self, view_menu_name): """ Adds menu_access to menu on permission_view_menu :param view_menu_name: The menu name """ self.add_view_menu(view_menu_name) pv = self.find_permission_view_menu("menu_access", view_menu_name) ...
Will cleanup all unused permissions from the database
def security_cleanup(self, baseviews, menus): """ Will cleanup all unused permissions from the database :param baseviews: A list of BaseViews class :param menus: Menu class """ viewsmenus = self.get_all_view_menu() roles = self.get_all_roles() ...
Send a greeting --- get: responses: 200: description: Greet the user content: application/ json: schema: type: object properties: message: type: string post: responses: 201: description: Greet the user content: application/ json: schema: type: object properties: message: type: string
def greeting2(self): """Send a greeting --- get: responses: 200: description: Greet the user content: application/json: schema: type: object properties: ...
Adds list of dicts
def rest_add_filters(self, data): """ Adds list of dicts :param data: list of dicts :return: """ for _filter in data: filter_class = map_args_filter.get(_filter["opr"], None) if filter_class: self.add_filter(_filter["col"], fil...
Creates a new filters class with active filters joined
def get_joined_filters(self, filters): """ Creates a new filters class with active filters joined """ retfilters = Filters(self.filter_converter, self.datamodel) retfilters.filters = self.filters + filters.filters retfilters.values = self.values + filters.values ...
Returns a copy of this object
def copy(self): """ Returns a copy of this object :return: A copy of self """ retfilters = Filters(self.filter_converter, self.datamodel) retfilters.filters = copy.copy(self.filters) retfilters.values = copy.copy(self.values) return retfilters
Returns the filter active FilterRelation cols
def get_relation_cols(self): """ Returns the filter active FilterRelation cols """ retlst = [] for flt, value in zip(self.filters, self.values): if isinstance(flt, FilterRelation) and value: retlst.append(flt.column_name) return retlst
Returns a list of tuples [ ( FILTER value ) (...... ).... ]
def get_filters_values(self): """ Returns a list of tuples [(FILTER, value),(...,...),....] """ return [(flt, value) for flt, value in zip(self.filters, self.values)]
Returns the filtered value for a certain column
def get_filter_value(self, column_name): """ Returns the filtered value for a certain column :param column_name: The name of the column that we want the value from :return: the filter value of the column """ for flt, value in zip(self.filters, self.values): ...
Finds a menu item by name and returns it.
def find(self, name, menu=None): """ Finds a menu item by name and returns it. :param name: The menu item name. """ menu = menu or self.menu for i in menu: if i.name == name: return i else: i...
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.
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.
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
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.
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: type: string password: type: string provider: type: string enum: - db - ldap refresh: type: boolean responses: 200: description: Authentica...
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: type: object properties: refresh_token: type: string 401: $ref: #/ components/ responses/ 401 500: $ref: #/ component...
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.
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
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
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
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
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
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
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
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.
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
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: param page_size: the current page size
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
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
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::
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 expose API endpoints on your API classes.
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...
Use this decorator to set a new merging response function to HTTP endpoints
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): ```...