text stringlengths 81 112k |
|---|
Decorate a function/method to check its timings.
To use the function's name:
@sw.decorate
def func():
pass
To name it explicitly:
@sw.decorate("name")
def random_func_name():
pass
Args:
name_or_func: the name or the function to decorate.
Returns:
I... |
Parse the output below to create a new StopWatch.
def parse(s):
"""Parse the output below to create a new StopWatch."""
stopwatch = StopWatch()
for line in s.splitlines():
if line.strip():
parts = line.split(None)
name = parts[0]
if name != "%": # ie not the header line
... |
Return a string representation of the timings.
def str(self, threshold=0.1):
"""Return a string representation of the timings."""
if not self._times:
return ""
total = sum(s.sum for k, s in six.iteritems(self._times) if "." not in k)
table = [["", "% total", "sum", "avg", "dev", "min", "max", "nu... |
Generate the list of units in units.py.
def generate_py_units(data):
"""Generate the list of units in units.py."""
units = collections.defaultdict(list)
for unit in sorted(data.units, key=lambda a: a.name):
if unit.unit_id in static_data.UNIT_TYPES:
units[unit.race].append(unit)
def print_race(name,... |
Run a set of functions in parallel, returning their results.
Make sure any function you pass exits with a reasonable timeout. If it
doesn't return within the timeout or the result is ignored due an exception
in a separate thread it will continue to stick around until it finishes,
including blocking pro... |
Converts a list of dicts from datamodel query results
to google chart json data.
:param xcol:
The name of a string column to be used has X axis on chart
:param ycols:
A list with the names of series cols, that can be used as numeric
:param labels:
A d... |
Endpoint that renders an OpenApi spec for all views that belong
to a certain version
---
get:
parameters:
- in: path
schema:
type: string
name: version
responses:
200:
description: Item from Model
... |
Help function for SQLA filters, checks for dot notation on column names.
If it exists, will join the query with the model
from the first part of the field name.
example:
Contact.created_by: if created_by is a User model,
it will be joined to the query.
def get_field_set... |
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: '... |
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
"""
vi... |
Deletes a ViewMenu from the backend
:param name:
name of the ViewMenu
def del_view_menu(self, name):
"""
Deletes a ViewMenu from the backend
:param name:
name of the ViewMenu
"""
obj = self.find_view_menu(name)
if obj... |
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... |
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):
... |
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:
... |
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:
... |
modified: removing the '_cls' column added by Mongoengine to support
mongodb document inheritance
cf. http://docs.mongoengine.org/apireference.html#documents:
"A Document subclass may be itself subclassed,
to create a specialised version of the document that will be
stored in the... |
Returns the columns that can be ordered
:param list_columns: optional list of columns name, if provided will
use this list only.
def get_order_columns_list(self, list_columns=None):
"""
Returns the columns that can be ordered
:param list_columns: optional l... |
return a list of pk values from object list
def get_keys(self, lst):
"""
return a list of pk values from object list
"""
pk_name = self.get_pk_name()
return [getattr(item, pk_name) for item in lst] |
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))
... |
Get Values: formats values for list template.
returns [{'col_name':'col_value',....},{'col_name':'col_value',....}]
:param lst:
The list of item objects from query
:param list_columns:
The list of columns to include
def _get_values(self, lst, list_co... |
Get Values: formats values for list template.
returns [{'col_name':'col_value',....},{'col_name':'col_value',....}]
:param lst:
The list of item objects from query
:param list_columns:
The list of columns to include
def get_values(self, lst, list_col... |
Converts list of objects from query to JSON
def get_values_json(self, lst, list_columns):
"""
Converts list of objects from query to JSON
"""
result = []
for item in self.get_values(lst, list_columns):
for key, value in list(item.items()):
if isin... |
return a list of pk values from object list
def get_keys(self, lst):
"""
return a list of pk values from object list
"""
pk_name = self.get_pk_name()
if self.is_pk_composite():
return [[getattr(item, pk) for pk in pk_name] for item in lst]
else:
... |
Method for sending the registration Email to the user
def send_email(self, register_user):
"""
Method for sending the registration Email to the user
"""
try:
from flask_mail import Mail, Message
except Exception:
log.error("Install Flask-Mail to use U... |
Add a registration request for the user.
:rtype : RegisterUser
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_us... |
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... |
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... |
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 object containing the value to process.
def process... |
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 strings to process.
def process_formdata(self, valuelist):... |
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 ... |
Get page arguments, returns a dictionary
{ <VIEW_NAME>: PAGE_NUMBER }
Arguments are passed: page_<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>
... |
Get page size arguments, returns an int
{ <VIEW_NAME>: PAGE_NUMBER }
Arguments are passed: psize_<VIEW_NAME>=<PAGE_SIZE>
def get_page_size_args():
"""
Get page size arguments, returns an int
{ <VIEW_NAME>: PAGE_NUMBER }
Arguments are passed: psize_<VIEW_NAME>=<PAGE_SIZE>
... |
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'
def get_order_args():
"""
Get order arguments, return a dictionary
{ <VIEW_NAME>: (ORDER_COL, ORDER_DIRECTION) }... |
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
def _meta_schema_factory(self, columns, model, class_mixin):
"""
Creates ModelSchema marshma... |
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 with nested schemas
:return: ModelSchema object
def convert(self, columns, model=None, nested=T... |
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(Bas... |
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.
def has_access(f):
"""
Use this decorator to enable granular security permissions t... |
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 case of unauthorized access.
def has_ac... |
Use this decorator to expose actions
:param name:
Action name
:param text:
Action text.
:param confirmation:
Confirmation text. If not provided, action will be executed
unconditionally.
:param icon:
Font Awesome icon name
... |
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... |
Override to implement your custom login manager instance
:param app: Flask app
def create_login_manager(self, app) -> LoginManager:
"""
Override to implement your custom login manager instance
:param app: Flask app
"""
lm = LoginManager(app)
lm.logi... |
Override to implement your custom JWT manager instance
:param app: Flask app
def create_jwt_manager(self, app) -> JWTManager:
"""
Override to implement your custom JWT manager instance
:param app: Flask app
"""
jwt_manager = JWTManager()
jwt_manager... |
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.
Us... |
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... |
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
... |
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... |
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"... |
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:
... |
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 save hashed on the db
def reset_password(self, userid, password):
... |
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
def update_user_auth_stat(self, user, success=True):
"""
Update authentica... |
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
def auth_user_db(self, username, password):
"""
Method for aut... |
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 object array
def _search_ldap(self, ldap, con, username):
"""
... |
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 l... |
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 _... |
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 password
def auth_user_ldap(self, username, password):
"""
... |
OpenID user Authentication
:param email: user's email to authenticate
:type self: User model
def auth_user_oid(self, email):
"""
OpenID user Authentication
:param email: user's email to authenticate
:type self: User model
"""
user = ... |
REMOTE_USER user Authentication
:param username: user's username for remote auth
:type self: User model
def auth_user_remote_user(self, username):
"""
REMOTE_USER user Authentication
:param username: user's username for remote auth
:type self: User ... |
OAuth user Authentication
:userinfo: dict with user information the keys have the same name
as User model columns.
def auth_user_oauth(self, userinfo):
"""
OAuth user Authentication
:userinfo: dict with user information the keys have the same name
a... |
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)
def is_item_public(self, permission_name, view_name):
"""
Check if view has pu... |
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_na... |
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/res... |
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:
name of the view or menu to add
def add_permissions_view(self, base_permi... |
Adds menu_access to menu on permission_view_menu
:param view_menu_name:
The menu name
def add_permissions_menu(self, view_menu_name):
"""
Adds menu_access to menu on permission_view_menu
:param view_menu_name:
The menu name
"""
... |
Will cleanup all unused permissions from the database
:param baseviews: A list of BaseViews class
:param menus: Menu class
def security_cleanup(self, baseviews, menus):
"""
Will cleanup all unused permissions from the database
:param baseviews: A list of BaseVi... |
Send a greeting
---
get:
responses:
200:
description: Greet the user
content:
application/json:
schema:
type: object
properties:
message:
... |
Adds list of dicts
:param data: list of dicts
:return:
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)
... |
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
... |
Returns a copy of this object
:return: A copy of self
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)
retf... |
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.app... |
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
:param column_name: The name of the column that we want the value from
:return: the filter value of the column
def get_filter_value(self, column_name):
"""
Returns the filtered value for a certain column
:param co... |
Finds a menu item by name and returns it.
:param name:
The menu item name.
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
f... |
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(e... |
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... |
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, us... |
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-AppBuil... |
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)
... |
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} keyw... |
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
"""
# Spl... |
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... |
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.... |
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)
... |
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... |
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-... |
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 instanti... |
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:
... |
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:
... |
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
"""
registe... |
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:
... |
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.lowe... |
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()... |
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: '... |
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 per... |
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
"""
vi... |
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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.