biggr_models.handlers.utils

Contents

biggr_models.handlers.utils#

Attributes#

Classes#

BiGGrJSONEncoder

Handle exporting database entities to the BiGGr API return format.

BaseHandler

Base RequestHandler that handles standard requests.

TemplateHandler

Simple handler that only requires a template name.

DataColumnSpec

This class holds all information of a data tables column.

DataColumn

This class adds user specified filters etc. on top of a DataColumnSpec.

DataHandler

Request handler that implements data tables (API) logic.

HealthHandler

Base class for HTTP request handlers.

APIVersionHandler

Base RequestHandler that handles standard requests.

StaticFileDownloadHandler

A simple handler that can serve static content from a directory.

StaticFileHandlerWithEncoding

A simple handler that can serve static content from a directory.

Functions#

biggr_json_object_hook(o)

Hook function to use with JSONDecoder and cobradb objects.

format_bigg_id(→ str)

Generate a HTML string that formats any BiGG ID.

format_reference(→ str)

Format a reference identifier.

format_gene_reaction_rule(→ str)

Format a Gene Reaction Rule.

safe_query(func, *args, **kwargs)

do_safe_query(func, *args, **kwargs)

Run the given function, and raise a 404 if it fails.

col_str_search(query, col_spec)

Implements searching string columns in data tables.

col_bool_search(query, col_spec)

Implements searching string columns in data tables.

col_number_search(→ Tuple[bool, ...)

Implements searching number columns in data tables.

get_reverse_url(handler, name, path_kwargs)

Module Contents#

biggr_models.handlers.utils.MODELS_CLASS_MAP#
class biggr_models.handlers.utils.BiGGrJSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)#

Bases: json.JSONEncoder

Handle exporting database entities to the BiGGr API return format.

default(o)#

Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).

For example, to support arbitrary iterators, you could implement default like this:

def default(self, o):
    try:
        iterable = iter(o)
    except TypeError:
        pass
    else:
        return list(iterable)
    # Let the base class default method raise the TypeError
    return super().default(o)
biggr_models.handlers.utils.biggr_json_object_hook(o)#

Hook function to use with JSONDecoder and cobradb objects.

biggr_models.handlers.utils.format_bigg_id(bigg_id: str, format_type: str | None = None) str#

Generate a HTML string that formats any BiGG ID.

The output results in accentuation of important parts of the BiGG ID.

Parameters:
  • bigg_id (str) – Input BiGG ID to format.

  • format_type (str, optional) – The object type represented by the BiGG ID. Determines the exact formatting used. If format_type is None, no formatting is applied. Argument can be any of: ‘comp’ (Component), ‘comp_comp’ (CompartmentalizedComponent), ‘universal_comp_comp’ (UniversalCompartmentalizedComponent), ‘reaction’ (Reaction).

Returns:

HTML string containing formatted BiGG ID.

Return type:

str

biggr_models.handlers.utils.format_reference(identifier: str) str#

Format a reference identifier.

biggr_models.handlers.utils.format_gene_reaction_rule(grr: str) str#

Format a Gene Reaction Rule.

biggr_models.handlers.utils.env#
biggr_models.handlers.utils.directory = b'.'#
biggr_models.handlers.utils.static_model_dir#
biggr_models.handlers.utils.safe_query(func, *args, **kwargs)#
biggr_models.handlers.utils.do_safe_query(func, *args, **kwargs)#

Run the given function, and raise a 404 if it fails.

Parameters:
  • func (The function to run. A session object is passed as first argument to)

  • function (this)

  • subsequently. (*args and **kwargs are passed) –

Return type:

The result of func.

Raises:

HTTPError – Raises a 404 error if an entity was not found or 400 when a ValueError occurred.

class biggr_models.handlers.utils.BaseHandler(application: Application, request: tornado.httputil.HTTPServerRequest, **kwargs: Any)#

Bases: tornado.web.RequestHandler

Base RequestHandler that handles standard requests.

set_default_headers()#

Override this to set HTTP headers at the beginning of the request.

For example, this is the place to set a custom Server header. Note that setting such headers in the normal flow of request processing may not do what you want, since headers may be reset during error handling.

head()#
write(chunk)#

Writes the given chunk to the output buffer.

To write the output to the network, use the flush() method below.

If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be application/json. (if you want to send JSON as a different Content-Type, call set_header after calling write()).

Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and facebook/tornado#1009

return_result(result=None)#

Returns result as either rendered HTML or JSON

This is suitable for cases where the template takes exactly the same result as the JSON api. This function will serve JSON if the request URI starts with JSON, otherwise it will render the objects template with the data

get()#
class biggr_models.handlers.utils.TemplateHandler(application: Application, request: tornado.httputil.HTTPServerRequest, **kwargs: Any)#

Bases: BaseHandler

Simple handler that only requires a template name.

initialize(template_name)#

Hook for subclass initialization. Called for each request.

A dictionary passed as the third argument of a URLSpec will be supplied as keyword arguments to initialize().

Example:

class ProfileHandler(RequestHandler):
    def initialize(self, database):
        self.database = database

    def get(self, username):
        ...

app = Application([
    (r'/user/(.*)', ProfileHandler, dict(database=database)),
    ])

Implements searching string columns in data tables.

Searching is implemented as an icontains call, meaning that the query is filtered in a case-insensitive manner.

Parameters:
  • query (sqlalchemy query object) – Extra filters are added upon this query to achieve the search.

  • col_spec (DataColumn) – All column information, including search query.

Returns:

  • has_changed (bool) – True when any filter was applied to the query. Helps with optimizations.

  • query – The new query object.

Implements searching string columns in data tables.

Searching is implemented as an icontains call, meaning that the query is filtered in a case-insensitive manner.

Parameters:
  • query (sqlalchemy query object) – Extra filters are added upon this query to achieve the search.

  • col_spec (DataColumn) – All column information, including search query.

Returns:

  • has_changed (bool) – True when any filter was applied to the query. Helps with optimizations.

  • query – The new query object.

biggr_models.handlers.utils.REGEX_COL_NUMBER_1#
biggr_models.handlers.utils.REGEX_COL_NUMBER_2#

Implements searching number columns in data tables.

Many number search patterns are implemented: >, <, >=, and <= can be used to search an open range, i.e. >10 will return all rows where the column value is greater than 10. A closed inclusive range can be specified using a dash (-), i.e. 10-20 means 10 up to and including 20. Commas (,) can be used to separate numbers and thus search for a list of numbers or a list of (open) ranges, effectively functioning as an OR operator. The ampersand symbol (&) can be used as an AND operator, e.g. >10&<20.

Parameters:
  • query (sqlalchemy query object) – Extra filters are added upon this query to achieve the search.

  • col_spec (DataColumn) – All column information, including search query.

Returns:

  • has_changed (bool) – True when any filter was applied to the query. Helps with optimizations.

  • query – The new query object.

class biggr_models.handlers.utils.DataColumnSpec(prop: Any, name: str, requires=None, agg_func=None, process=None, global_search: bool = True, hyperlink: str | None = None, search_type: str = 'str', apply_search_query: bool = True, score_modes: List[str] | None = None, search_query_remove_namespace: bool = False, priority: int | None = None, visible: bool = True)#

This class holds all information of a data tables column.

prop#
identifier: str = ''#
name: str#
requires: List[Any] = []#
search_type = 'str'#
apply_search_query = True#
score_modes = None#
search_query_remove_namespace = False#
priority = None#
visible = True#
class biggr_models.handlers.utils.DataColumn(spec: DataColumnSpec)#

This class adds user specified filters etc. on top of a DataColumnSpec.

spec#
search_value: str = ''#
order_priority: int | None = None#
order_asc: bool = True#
search_regex: bool = False#
searchable: bool = True#
orderable: bool = True#
search(query)#
biggr_models.handlers.utils.get_reverse_url(handler, name, path_kwargs)#
class biggr_models.handlers.utils.DataHandler(application: Application, request: tornado.httputil.HTTPServerRequest, **kwargs: Any)#

Bases: BaseHandler

Request handler that implements data tables (API) logic.

template#
title = None#
column_specs: List[DataColumnSpec] = []#
columns: List[DataColumn] = []#
start: int = 0#
length: int | None = None#
draw: int | None = None#
name = None#
search_value: str = ''#
search_regex: bool = False#
api: bool = False#
page_data: Dict[str, Any] | None = None#
initialize(**kwargs)#

Hook for subclass initialization. Called for each request.

A dictionary passed as the third argument of a URLSpec will be supplied as keyword arguments to initialize().

Example:

class ProfileHandler(RequestHandler):
    def initialize(self, database):
        self.database = database

    def get(self, username):
        ...

app = Application([
    (r'/user/(.*)', ProfileHandler, dict(database=database)),
    ])
breadcrumbs() Any#
pre_filter(query)#
post_filter(query)#
get(*args, **kwargs)#
return_page(*args, **kwargs)#
post(*args, **kwargs)#
return_data(*args, **kwargs)#
property data_url#
prepare()#

Called at the beginning of a request before get/post/etc.

Override this method to perform common initialization regardless of the request method. There is no guarantee that prepare will be called if an error occurs that is handled by the framework.

Asynchronous support: Use async def or decorate this method with .gen.coroutine to make it asynchronous. If this method returns an Awaitable execution will not proceed until the Awaitable is done.

Added in version 3.1: Asynchronous support.

data_query(f, **kwargs)#
write_data(data: Any, total_count: int, filtered_count: int)#
class biggr_models.handlers.utils.HealthHandler(application: Application, request: tornado.httputil.HTTPServerRequest, **kwargs: Any)#

Bases: tornado.web.RequestHandler

Base class for HTTP request handlers.

Subclasses must define at least one of the methods defined in the “Entry points” section below.

Applications should not construct RequestHandler objects directly and subclasses should not override __init__ (override ~RequestHandler.initialize instead).

set_default_headers()#

Override this to set HTTP headers at the beginning of the request.

For example, this is the place to set a custom Server header. Note that setting such headers in the normal flow of request processing may not do what you want, since headers may be reset during error handling.

get()#
head()#
class biggr_models.handlers.utils.APIVersionHandler(application: Application, request: tornado.httputil.HTTPServerRequest, **kwargs: Any)#

Bases: BaseHandler

Base RequestHandler that handles standard requests.

get()#
class biggr_models.handlers.utils.StaticFileDownloadHandler(application: Application, request: tornado.httputil.HTTPServerRequest, **kwargs: Any)#

Bases: tornado.web.StaticFileHandler

A simple handler that can serve static content from a directory.

A StaticFileHandler is configured automatically if you pass the static_path keyword argument to Application. This handler can be customized with the static_url_prefix, static_handler_class, and static_handler_args settings.

To map an additional path to this handler for a static data directory you would add a line to your application like:

application = web.Application([
    (r"/content/(.*)", web.StaticFileHandler, {"path": "/var/www"}),
])

The handler constructor requires a path argument, which specifies the local root directory of the content to be served.

Note that a capture group in the regex is required to parse the value for the path argument to the get() method (different than the constructor argument above); see URLSpec for details.

To serve a file like index.html automatically when a directory is requested, set static_handler_args=dict(default_filename="index.html") in your application settings, or add default_filename as an initializer argument for your StaticFileHandler.

To maximize the effectiveness of browser caching, this class supports versioned urls (by default using the argument ?v=). If a version is given, we instruct the browser to cache this file indefinitely. make_static_url (also available as RequestHandler.static_url) can be used to construct a versioned url.

This handler is intended primarily for use in development and light-duty file serving; for heavy traffic it will be more efficient to use a dedicated static file server (such as nginx or Apache). We support the HTTP Accept-Ranges mechanism to return partial content (because some browsers require this functionality to be present to seek in HTML5 audio or video).

Subclassing notes

This class is designed to be extensible by subclassing, but because of the way static urls are generated with class methods rather than instance methods, the inheritance patterns are somewhat unusual. Be sure to use the @classmethod decorator when overriding a class method. Instance methods may use the attributes self.path self.absolute_path, and self.modified.

Subclasses should only override methods discussed in this section; overriding other methods is error-prone. Overriding StaticFileHandler.get is particularly problematic due to the tight coupling with compute_etag and other methods.

To change the way static urls are generated (e.g. to match the behavior of another server or CDN), override make_static_url, parse_url_path, get_cache_time, and/or get_version.

To replace all interaction with the filesystem (e.g. to serve static content from a database), override get_content, get_content_size, get_modified_time, get_absolute_path, and validate_absolute_path.

Changed in version 3.1: Many of the methods for subclasses were added in Tornado 3.1.

get_content_type()#

Same as the default, but with utf8 encoding for XML and JSON files.

set_extra_headers(path: str) None#

For subclass to add extra headers to the response

class biggr_models.handlers.utils.StaticFileHandlerWithEncoding(application: Application, request: tornado.httputil.HTTPServerRequest, **kwargs: Any)#

Bases: tornado.web.StaticFileHandler

A simple handler that can serve static content from a directory.

A StaticFileHandler is configured automatically if you pass the static_path keyword argument to Application. This handler can be customized with the static_url_prefix, static_handler_class, and static_handler_args settings.

To map an additional path to this handler for a static data directory you would add a line to your application like:

application = web.Application([
    (r"/content/(.*)", web.StaticFileHandler, {"path": "/var/www"}),
])

The handler constructor requires a path argument, which specifies the local root directory of the content to be served.

Note that a capture group in the regex is required to parse the value for the path argument to the get() method (different than the constructor argument above); see URLSpec for details.

To serve a file like index.html automatically when a directory is requested, set static_handler_args=dict(default_filename="index.html") in your application settings, or add default_filename as an initializer argument for your StaticFileHandler.

To maximize the effectiveness of browser caching, this class supports versioned urls (by default using the argument ?v=). If a version is given, we instruct the browser to cache this file indefinitely. make_static_url (also available as RequestHandler.static_url) can be used to construct a versioned url.

This handler is intended primarily for use in development and light-duty file serving; for heavy traffic it will be more efficient to use a dedicated static file server (such as nginx or Apache). We support the HTTP Accept-Ranges mechanism to return partial content (because some browsers require this functionality to be present to seek in HTML5 audio or video).

Subclassing notes

This class is designed to be extensible by subclassing, but because of the way static urls are generated with class methods rather than instance methods, the inheritance patterns are somewhat unusual. Be sure to use the @classmethod decorator when overriding a class method. Instance methods may use the attributes self.path self.absolute_path, and self.modified.

Subclasses should only override methods discussed in this section; overriding other methods is error-prone. Overriding StaticFileHandler.get is particularly problematic due to the tight coupling with compute_etag and other methods.

To change the way static urls are generated (e.g. to match the behavior of another server or CDN), override make_static_url, parse_url_path, get_cache_time, and/or get_version.

To replace all interaction with the filesystem (e.g. to serve static content from a database), override get_content, get_content_size, get_modified_time, get_absolute_path, and validate_absolute_path.

Changed in version 3.1: Many of the methods for subclasses were added in Tornado 3.1.

get_absolute_path(root, file_path)#

Returns the absolute location of path relative to root.

root is the path configured for this StaticFileHandler (in most cases the static_path Application setting).

This class method may be overridden in subclasses. By default it returns a filesystem path, but other strings may be used as long as they are unique and understood by the subclass’s overridden get_content.

Added in version 3.1.

get_content_type()#

Same as the default, but with utf8 encoding for XML and JSON files.