Grid Class

class webgrid.BaseGrid(ident=None, per_page=<class 'webgrid._None'>, on_page=<class 'webgrid._None'>, qs_prefix='', class_='datagrid', **kwargs)[source]

WebGrid grid base class.

Handles class declarative-style grid description of columns, filterers, and rendering.

The constructor is responsible for:

  • setting initial attributes

  • initializing renderers

  • setting up columns for the grid instance

  • running the grid’s post_init method

Args:

ident (str, optional): Identifier value for ident instance property. Defaults to None.

per_page (int, optional): Default number of records per page. Defaults to _None.

on_page (int, optional): Default starting page. Defaults to _None.

qs_prefix (str, optional): Arg name prefix to apply in query string. Useful for having multiple unconnected grids on a single page. Defaults to ‘’.

class_ (str, optional): CSS class name for main grid div. Defaults to ‘datagrid’.

Class Attributes:

identifier (str): Optional string identifier used for the ident property.

sorter_on (bool): Enable HTML sorting UX. Default True.

pager_on (bool): Enable record limits in queries and HTML pager UX. Default True.

per_page (int): Default number of records per page, can be overridden in constructor or through query string args. Default 50.

on_page (int): Default page number, can be overridden in constructor or through query string args. Default 1.

hide_controls_box (bool): Hides HTML filter/page/sort/count UX. Default False.

session_on (bool): Enable web context session storage of grid filter/page/sort args. Default True.

subtotals (string): Enable subtotals. Can be none|page|grand|all. Default “none”.

manager (Manager): Framework plugin for the web context, such as webgrid.flask.WebGrid.

allowed_export_targets (dict[str, Renderer]): Map non-HTML export targets to the Renderer classes.

enable_search (bool): Enable single-search UX. Default True.

unconfirmed_export_limit (int): Ask for confirmation before exporting more than this many records. Set to None to disable. Default 10000.

query_select_from (selectable): Entity, table, or other selectable(s) to use as the query from. If attributes like query_filter are used along with select_from, SQLAlchemy may require the select_from to precede the filtering.

query_joins (tuple): Tuple of joins to bring the query together for all columns. May have just the join object, or also conditions. e.g. [Blog], ([Blog.category], ), or [(Blog, Blog.active == sa.true())] Note, relationship attributes must be referenced within tuples, due to SQLAlchemy magic.

query_outer_joins (tuple): Tuple of outer joins. See query_joins.

query_filter (tuple): Filter parameter(s) tuple to be used on the query. Note, relationship attributes must be referenced within tuples, due to SQLAlchemy magic.

query_default_sort (tuple): Parameter(s) tuple to be passed to order_by if sort options are not set on the grid. Note, relationship attributes must be referenced within tuples, due to SQLAlchemy magic.

apply_qs_args(add_user_warnings=True, grid_args=None)[source]

Process args from manager for filter/page/sort/export.

Args:

add_user_warnings (bool, optional): Add flash messages for warnings. Defaults to True. grid_args (MultiDict, optional): Supply args directly to the grid.

Modify the query by applying a filter term constructed from search clauses.

Calls each filter search expression factory with the search value to get a search clause, then ORs them all together for the main query.

Args:

query (Query): SQLAlchemy query. value (str): Search value.

Returns:

Query: SQLAlchemy query

apply_validator(validator, value, qs_arg_key)[source]

Apply a webgrid validator to value, and produce a warning if invalid.

Args:

validator (Validator): webgrid validator. value (str): Value to validate. qs_arg_key (str): Arg name to include in warning if value is invalid.

Returns:

Any: Output of validator.to_python(value), or None if invalid.

before_query_hook()[source]

Hook to give subclasses a chance to change things before executing the query.

build(grid_args=None)[source]

Apply query args, run before_query_hook, and execute a record count query.

Calling build is preferred to simply calling apply_qs_args in a view. Otherwise, AttributeErrors can be hidden when the grid is used in Jinja templates.

build_qs_args(include_session=False)[source]

Build a URL query string based on current grid attributes.

This is designed to be framework-agnostic and not require a request context. Usually the result would be used in a background task or similar (i.e. outside the flow of the rendered grid), so typically the session key is unnecessary.

Args:

include_session (bool, optional): Include session_key in the string. Defaults to False.

build_query(for_count=False)[source]

Constructs, but does not execute, a grid query from columns and configuration.

This is the query the grid functions trust for results for records, count, page count, etc. Customization of the query should happen here or in the methods called within.

Build sequence: - query_base - query_prep - query_filters - query_sort - query_paging

Args:

for_count (bool, optional): Excludes sort/page from query. Defaults to False.

Returns:

Query: SQLAlchemy query object

Grid enable_search attr turns on search, but check if there are supporting filters.

Returns:

bool: search enabled and supporting filters exist

check_auth()[source]

For API usage, provides a hook for grids to specify authorization that should be applied for the API responder method.

If a 40* response is warranted, take that action here.

Note, this method is not part of normal grid/render operation. It will only be executed if run by a calling layer, such as the Flask WebGridAPI manager/extension.

clear_record_cache(preserve_count=False)[source]

Reset records and record count cached from previous queries.

Args:

preserve_count (bool): Direct grid to retain count of records, effectively removing only the table of records itself.

column(ident)[source]

Retrieve a grid column instance via either the key string or index int.

Args:

ident (Union[str, int]): Key/index for lookup.

Returns:

Column: Instance column matching the ident.

Raises:

KeyError when ident is a string not matching any column.

IndexError when ident is an int but out of bounds for the grid.

export_as_response(wb=None, sheet_name=None)[source]

Return renderer response for view layer to provide as a file.

Args:

wb (Workbook, optional): XlsxWriter Workbook. Defaults to None. sheet_name (Worksheet, optional): XlsxWriter Worksheet. Defaults to None.

Raises:

ValueError: No export parameter given.

Returns:

Response: Return response processed through renderer and manager.

get_unique_column_key(key)[source]

Apply numeric suffix to a field key to make the key unique to the grid.

Helpful for when multiple entities are represented in grid columns but have the same field names.

For instance, Blog.label and Author.label both have the field name label. The first column will have the label key, and the second will get label_1.

Args:

key (str): field key to make unique.

Returns:

str: unique key that may be assigned in the grid’s key_column_map.

property grand_totals

Executes query to retrieve subtotals for the filtered query.

For grand totals to be queried/returned, the grid’s subtotals must be grand/all and one or more columns must have subtotals configured.

A single result record is returned, which will have fields corresponding to all of the grid columns (same as a record returned in the general records query).

Returns:

Any: Single result record, or None if grand totals are not configured.

has_column(ident)[source]

Verify string key or int index is defined for the grid instance.

Args:

ident (Union[str, int]): Key/index for lookup.

Returns:

bool: Indicates whether key/index is in the grid columns.

property has_filters

Indicates whether filters will be applied in build_query.

Returns:

bool: True if filter(s) have op/value set or single search value is given.

property has_sort

Indicates whether ordering will be applied in build_query.

Returns:

bool: True if grid’s order_by list is populated.

iter_columns(render_type)[source]

Generator yielding columns that are visible and enabled for target render_type.

Args:

render_type (str): [description]

Yields:

Column: Grid instance’s column instance that is renderable for render_type.

property page_count

Page count, or 1 if no per_page is set.

property page_totals

Executes query to retrieve subtotals for the filtered query on the current page.

For page totals to be queried/returned, the grid’s subtotals must be page/all and one or more columns must have subtotals configured.

A single result record is returned, which will have fields corresponding to all of the grid columns (same as a record returned in the general records query).

Returns:

Any: Single result record, or None if page totals are not configured.

post_init()[source]

Provided for subclasses to run post-initialization customizations.

prefix_qs_arg_key(key)[source]

Given a bare arg key, return the prefixed version that will actually be in the request.

This is necessary for render targets that will construct ensuing requests. Prefixing is not needed for incoming args on internal grid ops, as long as the grid manager’s args loaders sanitize the args properly.

Args:

key (str): Bare arg key.

Returns:

str: Prefixed arg key.

query_base(has_sort, has_filters)[source]

Construct a query from grid columns, using grid’s join/filter/sort attributes.

Used by build_query to establish the basic query from column spec. If query is to be modified, it is recommended to do so in query_prep if possible, rather than overriding query_base.

Args:

has_sort (bool): Tells method not to order query, since the grid has sort params. has_filters (bool): Tells method if grid has filter params. Not used.

Returns:

Query: SQLAlchemy query

query_filters(query)[source]

Modify the query by applying filter terms.

Called by build_query to apply any column filters as needed. Also enacts the single-search value if specified.

Args:

query (Query): SQLAlchemy query object.

Returns:

Query: SQLAlchemy query

query_paging(query)[source]

Modify the query by applying limit/offset to match grid parameters.

Args:

query (Query): SQLAlchemy query.

Returns:

Query: SQLAlchemy query

query_prep(query, has_sort, has_filters)[source]

Modify the query that was constructed in query_base.

Joins, query filtering, and default sorting can be applied via grid attributes. However, sometimes grid queries need columns added, instance-time modifications applied, etc.

Called by build_query.

Args:

query (Query): SQLAlchemy query object. has_sort (bool): Tells method grid has sort params defined. has_filters (bool): Tells method if grid has filter params.

Returns:

Query: SQLAlchemy query

query_sort(query)[source]

Modify the query by applying sort to match grid parameters.

Args:

query (Query): SQLAlchemy query.

Returns:

Query: SQLAlchemy query

property record_count

Count of records for current filtered query.

Value is cached to prevent duplicate query execution. Methods changing the query (e.g. set_filter) will reset the cached value.

Returns:

int: Count of records.

property records

Records returned for current filtered/sorted/paged query.

Result is cached to prevent duplicate query execution. Methods changing the query (e.g. set_filter) will reset the cached result.

Returns:

list(Any): Result records from SQLAlchemy query.

property search_expression_generators

Get single-search query modifier factories from the grid filters.

Raises:

Exception: filter’s get_search_expr did not return None or callable

Returns:

tuple(callable): search expression callables from grid filters

property search_uses_aggregate

Determine whether search should use aggregate filtering.

By default, only use the HAVING clause if all search-enabled filters are marked as aggregate. Otherwise, we’d be requiring all grid columns to be in query grouping. If there are filters for search that are not aggregate, the grid will only search on the non-aggregate columns.

Returns:

bool: search aggregate usage determined from filter info

set_column_order(column_keys)[source]

Most renderers output columns in the order they appear in the grid’s columns list. When bringing mixins together or subclassing a grid, however, the order is often not what is intended.

This method allows a manual override of column order, based on keys.

set_export_to(to)[source]

Set export parameter after validating it exists in known targets.

Args:

to (str): Renderer attribute if it is known. Invalid value ignored.

set_filter(key, op, value, value2=None)[source]

Set filter parameters on a column’s filter. Resets record cache.

Args:

key (str): Column identifier op (str): Operator value (Any): First filter value value2 (Any, optional): Second filter value if applicable. Defaults to None.

set_paging(per_page, on_page)[source]

Set paging parameters for the main query. Resets record cache.

Args:

per_page (int): Record limit for each page. on_page (int): With per_page, computes the offset.

set_records(records)[source]

Assign a set of records to the grid’s cache.

Useful for simple grids that simply need to be rendered as a table. Note that any ops performed on the grid, such as setting filter/sort/page options, will clear this cached information.

Args:

records (list(Any)): List of record objects that can be referenced for column data.

set_renderers()[source]

Renderers assigned as attributes on the grid instance, named by render target.

set_sort(*args)[source]

Set sort parameters for main query. Resets record cache.

If keys are passed in that do not belong to this grid, raise user warnings (not exceptions). These warnings are suppressed if the grid has a “foreign” session assigned (i.e. two grids share some of the same columns, and should load as much information as possible from the shared session key).

Args:

Each arg is expected to be a column key. If the sort is to be descending for that key, prepend with a “-“. E.g. grid.set_sort(‘author’, ‘-post_date’)