text stringlengths 81 112k |
|---|
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
... |
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:
... |
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:
resu... |
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:... |
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
... |
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,... |
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(sel... |
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... |
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(nam... |
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)
... |
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 sele... |
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
... |
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)):
... |
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... |
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, heig... |
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:
... |
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()
... |
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 y... |
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 ... |
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... |
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, **... |
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... |
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] = s... |
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... |
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)
... |
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 []
s... |
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:
... |
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:... |
Get list of items from Model
---
get:
parameters:
- $ref: '#/components/parameters/get_list_schema'
responses:
200:
description: Items from Model
content:
application/json:
schema:
... |
POST item to Model
---
post:
requestBody:
description: Model schema
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/{{self.__class__.__name__}}.post'
responses:
... |
POST item to Model
---
put:
parameters:
- in: path
schema:
type: integer
name: pk
requestBody:
description: Model schema
required: true
content:
application/json:
schema:... |
Delete item from Model
---
delete:
parameters:
- in: path
schema:
type: integer
name: pk
responses:
200:
description: Item deleted
content:
application/json:
sche... |
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 d... |
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.g... |
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... |
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 ... |
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 ... |
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_lis... |
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... |
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... |
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... |
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... |
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
... |
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:
i... |
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_... |
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]... |
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_" + modelv... |
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))
... |
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... |
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, e... |
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(... |
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... |
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:... |
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"
)
... |
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) / aggreg... |
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:
:... |
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... |
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 end... |
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 wil... |
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_... |
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_... |
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 ... |
: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_view... |
get joined base filter and current active filter for query
def _get_list_widget(
self,
filters,
actions=None,
order_column="",
order_direction="",
page=None,
page_size=None,
widgets=None,
**args
):
""" get joined base filter and curre... |
list function logic, override to implement different logic
returns list and search widget
def _list(self):
"""
list function logic, override to implement different logic
returns list and search widget
"""
if get_order_args().get(self.__class__.__name__):
... |
show function logic, override to implement different logic
returns show and related list widget
def _show(self, pk):
"""
show function logic, override to implement different logic
returns show and related list widget
"""
pages = get_page_args()
page_s... |
Add function logic, override to implement different logic
returns add widget or None
def _add(self):
"""
Add function logic, override to implement different logic
returns add widget or None
"""
is_valid_form = True
get_filter_args(self._filters)
... |
Edit function logic, override to implement different logic
returns Edit widget and related list or None
def _edit(self, pk):
"""
Edit function logic, override to implement different logic
returns Edit widget and related list or None
"""
is_valid_form = True
... |
Delete function logic, override to implement different logic
deletes the record with primary_key = pk
:param pk:
record primary key to delete
def _delete(self, pk):
"""
Delete function logic, override to implement different logic
deletes the reco... |
fill the form with the suppressed cols, generated from exclude_cols
def _fill_form_exclude_cols(self, exclude_cols, form):
"""
fill the form with the suppressed cols, generated from exclude_cols
"""
for filter_key in exclude_cols:
filter_value = self._filters.get_filter_... |
Download a file from the current connection to the local filesystem.
:param str remote:
Remote file to download.
May be absolute, or relative to the remote working directory.
.. note::
Most SFTP servers set the remote working directory to the
... |
Upload a file from the local filesystem to the current connection.
:param local:
Local path of file to upload, or a file-like object.
**If a string is given**, it should be a path to a local (regular)
file (not a directory).
.. note::
When deali... |
Load SSH config file(s) from disk.
Also (beforehand) ensures that Invoke-level config re: runtime SSH
config file paths, is accounted for.
.. versionadded:: 2.0
def load_ssh_config(self):
"""
Load SSH config file(s) from disk.
Also (beforehand) ensures that Invoke-lev... |
Trigger loading of configured SSH config file paths.
Expects that ``base_ssh_config`` has already been set to an
`~paramiko.config.SSHConfig` object.
:returns: ``None``.
def _load_ssh_files(self):
"""
Trigger loading of configured SSH config file paths.
Expects that `... |
Attempt to open and parse an SSH config file at ``path``.
Does nothing if ``path`` is not a path to a valid file.
:returns: ``None``.
def _load_ssh_file(self, path):
"""
Attempt to open and parse an SSH config file at ``path``.
Does nothing if ``path`` is not a path to a vali... |
Default configuration values and behavior toggles.
Fabric only extends this method in order to make minor adjustments and
additions to Invoke's `~invoke.config.Config.global_defaults`; see its
documentation for the base values, such as the config subtrees
controlling behavior of ``run``... |
Read ``chunk_size`` from ``reader``, writing result to ``writer``.
Returns ``None`` if successful, or ``True`` if the read was empty.
.. versionadded:: 2.0
def read_and_write(self, reader, writer, chunk_size):
"""
Read ``chunk_size`` from ``reader``, writing result to ``writer``.
... |
Return the local executing username, or ``None`` if one can't be found.
.. versionadded:: 2.0
def get_local_user():
"""
Return the local executing username, or ``None`` if one can't be found.
.. versionadded:: 2.0
"""
# TODO: I don't understand why these lines were added outside the
# try... |
Parameterize a Call with its Context set to a per-host Config.
def parameterize(self, call, host):
"""
Parameterize a Call with its Context set to a per-host Config.
"""
debug("Parameterizing {!r} for host {!r}".format(call, host))
# Generate a custom ConnectionCall that knows h... |
Run command truly locally, and over SSH via localhost
def mixed_use_of_local_and_run(self):
"""
Run command truly locally, and over SSH via localhost
"""
cxn = Connection("localhost")
result = cxn.local("echo foo", hide=True)
assert result.stdout == "foo\n"
asser... |
Initiate an SSH connection to the host/port this object is bound to.
This may include activating the configured gateway connection, if one
is set.
Also saves a handle to the now-set Transport object for easier access.
Various connect-time settings (and/or their corresponding :ref:`SSH... |
Obtain a socket-like object from `gateway`.
:returns:
A ``direct-tcpip`` `paramiko.channel.Channel`, if `gateway` was a
`.Connection`; or a `~paramiko.proxy.ProxyCommand`, if `gateway`
was a string.
.. versionadded:: 2.0
def open_gateway(self):
"""
... |
Terminate the network connection to the remote end, if open.
If no connection is open, this method does nothing.
.. versionadded:: 2.0
def close(self):
"""
Terminate the network connection to the remote end, if open.
If no connection is open, this method does nothing.
... |
Execute a shell command on the remote end of this connection.
This method wraps an SSH-capable implementation of
`invoke.runners.Runner.run`; see its documentation for details.
.. warning::
There are a few spots where Fabric departs from Invoke's default
settings/behavi... |
Execute a shell command, via ``sudo``, on the remote end.
This method is identical to `invoke.context.Context.sudo` in every way,
except in that -- like `run` -- it honors per-host/per-connection
configuration overrides in addition to the generic/global ones. Thus,
for example, per-host... |
Execute a shell command on the local system.
This method is effectively a wrapper of `invoke.run`; see its docs for
details and call signature.
.. versionadded:: 2.0
def local(self, *args, **kwargs):
"""
Execute a shell command on the local system.
This method is effe... |
Return a `~paramiko.sftp_client.SFTPClient` object.
If called more than one time, memoizes the first result; thus, any
given `.Connection` instance will only ever have a single SFTP client,
and state (such as that managed by
`~paramiko.sftp_client.SFTPClient.chdir`) will be preserved.
... |
Open a tunnel connecting ``local_port`` to the server's environment.
For example, say you want to connect to a remote PostgreSQL database
which is locked down and only accessible via the system it's running
on. You have SSH access to this server, so you can temporarily make
port 5432 on... |
Open a tunnel connecting ``remote_port`` to the local environment.
For example, say you're running a daemon in development mode on your
workstation at port 8080, and want to funnel traffic to it from a
production or staging environment.
In most situations this isn't possible as your of... |
Given a list (l) will removing duplicates from the list,
preserving the original order of the list. Assumes that
the list entrie are hashable.
def dedup_list(l):
"""Given a list (l) will removing duplicates from the list,
preserving the original order of the list. Assumes that
the list ... |
Parses sentence 's' using CNF grammar 'g'.
def _parse(s, g):
"""Parses sentence 's' using CNF grammar 'g'."""
# The CYK table. Indexed with a 2-tuple: (start pos, end pos)
table = defaultdict(set)
# Top-level structure is similar to the CYK table. Each cell is a dict from
# rule name to the best (l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.