biggr_models.handlers.utils#
Attributes#
Classes#
Handle exporting database entities to the BiGGr API return format. |
|
Base RequestHandler that handles standard requests. |
|
Simple handler that only requires a template name. |
|
This class holds all information of a data tables column. |
|
This class adds user specified filters etc. on top of a DataColumnSpec. |
|
Request handler that implements data tables (API) logic. |
|
Base class for HTTP request handlers. |
|
Base RequestHandler that handles standard requests. |
|
A simple handler that can serve static content from a directory. |
|
A simple handler that can serve static content from a directory. |
Functions#
Hook function to use with JSONDecoder and cobradb objects. |
|
|
Generate a HTML string that formats any BiGG ID. |
|
Format a reference identifier. |
|
Format a Gene Reaction Rule. |
|
|
|
Run the given function, and raise a 404 if it fails. |
|
Implements searching string columns in data tables. |
|
Implements searching string columns in data tables. |
|
Implements searching number columns in data tables. |
|
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.JSONEncoderHandle 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 aTypeError).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:
- 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.RequestHandlerBase 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
Serverheader. 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 differentContent-Type, callset_headerafter callingwrite()).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:
BaseHandlerSimple 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
URLSpecwill be supplied as keyword arguments toinitialize().Example:
class ProfileHandler(RequestHandler): def initialize(self, database): self.database = database def get(self, username): ... app = Application([ (r'/user/(.*)', ProfileHandler, dict(database=database)), ])
- biggr_models.handlers.utils.col_str_search(query, col_spec: DataColumn)#
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.col_bool_search(query, col_spec: DataColumn)#
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#
- biggr_models.handlers.utils.col_number_search(query: sqlalchemy.sql.expression.Select, col_spec: DataColumn) Tuple[bool, sqlalchemy.sql.expression.Select]#
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#
- global_search = True#
- requires: List[Any] = []#
- search_type = 'str'#
- hyperlink = None#
- 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(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:
BaseHandlerRequest handler that implements data tables (API) logic.
- template#
- title = None#
- column_specs: List[DataColumnSpec] = []#
- columns: List[DataColumn] = []#
- name = None#
- initialize(**kwargs)#
Hook for subclass initialization. Called for each request.
A dictionary passed as the third argument of a
URLSpecwill be supplied as keyword arguments toinitialize().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
preparewill be called if an error occurs that is handled by the framework.Asynchronous support: Use
async defor decorate this method with .gen.coroutine to make it asynchronous. If this method returns anAwaitableexecution will not proceed until theAwaitableis done.Added in version 3.1: Asynchronous support.
- data_query(f, **kwargs)#
- class biggr_models.handlers.utils.HealthHandler(application: Application, request: tornado.httputil.HTTPServerRequest, **kwargs: Any)#
Bases:
tornado.web.RequestHandlerBase 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
Serverheader. 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:
BaseHandlerBase RequestHandler that handles standard requests.
- get()#
- class biggr_models.handlers.utils.StaticFileDownloadHandler(application: Application, request: tornado.httputil.HTTPServerRequest, **kwargs: Any)#
Bases:
tornado.web.StaticFileHandlerA simple handler that can serve static content from a directory.
A StaticFileHandler is configured automatically if you pass the
static_pathkeyword argument to Application. This handler can be customized with thestatic_url_prefix,static_handler_class, andstatic_handler_argssettings.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
pathargument, 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
pathargument to the get() method (different than the constructor argument above); see URLSpec for details.To serve a file like
index.htmlautomatically when a directory is requested, setstatic_handler_args=dict(default_filename="index.html")in your application settings, or adddefault_filenameas an initializer argument for yourStaticFileHandler.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-Rangesmechanism 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
@classmethoddecorator when overriding a class method. Instance methods may use the attributesself.pathself.absolute_path, andself.modified.Subclasses should only override methods discussed in this section; overriding other methods is error-prone. Overriding
StaticFileHandler.getis particularly problematic due to the tight coupling withcompute_etagand 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.
- class biggr_models.handlers.utils.StaticFileHandlerWithEncoding(application: Application, request: tornado.httputil.HTTPServerRequest, **kwargs: Any)#
Bases:
tornado.web.StaticFileHandlerA simple handler that can serve static content from a directory.
A StaticFileHandler is configured automatically if you pass the
static_pathkeyword argument to Application. This handler can be customized with thestatic_url_prefix,static_handler_class, andstatic_handler_argssettings.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
pathargument, 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
pathargument to the get() method (different than the constructor argument above); see URLSpec for details.To serve a file like
index.htmlautomatically when a directory is requested, setstatic_handler_args=dict(default_filename="index.html")in your application settings, or adddefault_filenameas an initializer argument for yourStaticFileHandler.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-Rangesmechanism 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
@classmethoddecorator when overriding a class method. Instance methods may use the attributesself.pathself.absolute_path, andself.modified.Subclasses should only override methods discussed in this section; overriding other methods is error-prone. Overriding
StaticFileHandler.getis particularly problematic due to the tight coupling withcompute_etagand 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
pathrelative toroot.rootis the path configured for this StaticFileHandler (in most cases thestatic_pathApplication 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.