biggr_models.handlers.utils
===========================

.. py:module:: biggr_models.handlers.utils


Attributes
----------

.. autoapisummary::

   biggr_models.handlers.utils.MODELS_CLASS_MAP
   biggr_models.handlers.utils.env
   biggr_models.handlers.utils.directory
   biggr_models.handlers.utils.static_model_dir
   biggr_models.handlers.utils.REGEX_COL_NUMBER_1
   biggr_models.handlers.utils.REGEX_COL_NUMBER_2


Classes
-------

.. autoapisummary::

   biggr_models.handlers.utils.BiGGrJSONEncoder
   biggr_models.handlers.utils.BaseHandler
   biggr_models.handlers.utils.TemplateHandler
   biggr_models.handlers.utils.DataColumnSpec
   biggr_models.handlers.utils.DataColumn
   biggr_models.handlers.utils.DataHandler
   biggr_models.handlers.utils.HealthHandler
   biggr_models.handlers.utils.APIVersionHandler
   biggr_models.handlers.utils.StaticFileDownloadHandler
   biggr_models.handlers.utils.StaticFileHandlerWithEncoding


Functions
---------

.. autoapisummary::

   biggr_models.handlers.utils.biggr_json_object_hook
   biggr_models.handlers.utils.format_bigg_id
   biggr_models.handlers.utils.format_reference
   biggr_models.handlers.utils.format_gene_reaction_rule
   biggr_models.handlers.utils.safe_query
   biggr_models.handlers.utils.do_safe_query
   biggr_models.handlers.utils.col_str_search
   biggr_models.handlers.utils.col_bool_search
   biggr_models.handlers.utils.col_number_search
   biggr_models.handlers.utils.get_reverse_url


Module Contents
---------------

.. py:data:: MODELS_CLASS_MAP

.. py:class:: BiGGrJSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)

   Bases: :py:obj:`json.JSONEncoder`


   Handle exporting database entities to the BiGGr API return format.


   .. py:method:: 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)




.. py:function:: biggr_json_object_hook(o)

   Hook function to use with JSONDecoder and cobradb objects.


.. py:function:: format_bigg_id(bigg_id: str, format_type: Optional[str] = None) -> str

   Generate a HTML string that formats any BiGG ID.

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

   :param bigg_id: Input BiGG ID to format.
   :type bigg_id: str
   :param format_type: 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).
   :type format_type: str, optional

   :returns: HTML string containing formatted BiGG ID.
   :rtype: str


.. py:function:: format_reference(identifier: str) -> str

   Format a reference identifier.


.. py:function:: format_gene_reaction_rule(grr: str) -> str

   Format a Gene Reaction Rule.


.. py:data:: env

.. py:data:: directory
   :value: b'.'


.. py:data:: static_model_dir

.. py:function:: safe_query(func, *args, **kwargs)

.. py:function:: do_safe_query(func, *args, **kwargs)

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

   :param func:
   :type func: The function to run. A session object is passed as first argument to
   :param this function:
   :param \*args and **kwargs are passed subsequently.:

   :rtype: The result of `func`.

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


.. py:class:: BaseHandler(application: Application, request: tornado.httputil.HTTPServerRequest, **kwargs: Any)

   Bases: :py:obj:`tornado.web.RequestHandler`


   Base RequestHandler that handles standard requests.


   .. py:method:: 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.



   .. py:method:: head()


   .. py:method:: 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
      https://github.com/facebook/tornado/issues/1009



   .. py:method:: 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




   .. py:method:: get()


.. py:class:: TemplateHandler(application: Application, request: tornado.httputil.HTTPServerRequest, **kwargs: Any)

   Bases: :py:obj:`BaseHandler`


   Simple handler that only requires a template name.


   .. py:method:: 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)),
              ])



.. py:function:: 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.

   :param query: Extra filters are added upon this query to achieve the search.
   :type query: sqlalchemy query object
   :param col_spec: All column information, including search query.
   :type col_spec: DataColumn

   :returns: * **has_changed** (*bool*) -- True when any filter was applied to the query. Helps with optimizations.
             * *query* -- The new query object.


.. py:function:: 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.

   :param query: Extra filters are added upon this query to achieve the search.
   :type query: sqlalchemy query object
   :param col_spec: All column information, including search query.
   :type col_spec: DataColumn

   :returns: * **has_changed** (*bool*) -- True when any filter was applied to the query. Helps with optimizations.
             * *query* -- The new query object.


.. py:data:: REGEX_COL_NUMBER_1

.. py:data:: REGEX_COL_NUMBER_2

.. py:function:: 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.

   :param query: Extra filters are added upon this query to achieve the search.
   :type query: sqlalchemy query object
   :param col_spec: All column information, including search query.
   :type col_spec: DataColumn

   :returns: * **has_changed** (*bool*) -- True when any filter was applied to the query. Helps with optimizations.
             * *query* -- The new query object.


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

   This class holds all information of a data tables column.


   .. py:attribute:: prop


   .. py:attribute:: identifier
      :type:  str
      :value: ''



   .. py:attribute:: name
      :type:  str


   .. py:attribute:: global_search
      :value: True



   .. py:attribute:: requires
      :type:  List[Any]
      :value: []



   .. py:attribute:: search_type
      :value: 'str'



   .. py:attribute:: hyperlink
      :value: None



   .. py:attribute:: apply_search_query
      :value: True



   .. py:attribute:: score_modes
      :value: None



   .. py:attribute:: search_query_remove_namespace
      :value: False



   .. py:attribute:: priority
      :value: None



   .. py:attribute:: visible
      :value: True



.. py:class:: DataColumn(spec: DataColumnSpec)

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


   .. py:attribute:: spec


   .. py:attribute:: search_value
      :type:  str
      :value: ''



   .. py:attribute:: order_priority
      :type:  Optional[int]
      :value: None



   .. py:attribute:: order_asc
      :type:  bool
      :value: True



   .. py:attribute:: search_regex
      :type:  bool
      :value: False



   .. py:attribute:: searchable
      :type:  bool
      :value: True



   .. py:attribute:: orderable
      :type:  bool
      :value: True



   .. py:method:: search(query)


.. py:function:: get_reverse_url(handler, name, path_kwargs)

.. py:class:: DataHandler(application: Application, request: tornado.httputil.HTTPServerRequest, **kwargs: Any)

   Bases: :py:obj:`BaseHandler`


   Request handler that implements data tables (API) logic.


   .. py:attribute:: template


   .. py:attribute:: title
      :value: None



   .. py:attribute:: column_specs
      :type:  List[DataColumnSpec]
      :value: []



   .. py:attribute:: columns
      :type:  List[DataColumn]
      :value: []



   .. py:attribute:: start
      :type:  int
      :value: 0



   .. py:attribute:: length
      :type:  Optional[int]
      :value: None



   .. py:attribute:: draw
      :type:  Optional[int]
      :value: None



   .. py:attribute:: name
      :value: None



   .. py:attribute:: search_value
      :type:  str
      :value: ''



   .. py:attribute:: search_regex
      :type:  bool
      :value: False



   .. py:attribute:: api
      :type:  bool
      :value: False



   .. py:attribute:: page_data
      :type:  Optional[Dict[str, Any]]
      :value: None



   .. py:method:: 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)),
              ])



   .. py:method:: breadcrumbs() -> Any


   .. py:method:: pre_filter(query)


   .. py:method:: post_filter(query)


   .. py:method:: get(*args, **kwargs)


   .. py:method:: return_page(*args, **kwargs)


   .. py:method:: post(*args, **kwargs)


   .. py:method:: return_data(*args, **kwargs)


   .. py:property:: data_url


   .. py:method:: 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.

      .. versionadded:: 3.1
         Asynchronous support.



   .. py:method:: data_query(f, **kwargs)


   .. py:method:: write_data(data: Any, total_count: int, filtered_count: int)


.. py:class:: HealthHandler(application: Application, request: tornado.httputil.HTTPServerRequest, **kwargs: Any)

   Bases: :py:obj:`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).



   .. py:method:: 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.



   .. py:method:: get()


   .. py:method:: head()


.. py:class:: APIVersionHandler(application: Application, request: tornado.httputil.HTTPServerRequest, **kwargs: Any)

   Bases: :py:obj:`BaseHandler`


   Base RequestHandler that handles standard requests.


   .. py:method:: get()


.. py:class:: StaticFileDownloadHandler(application: Application, request: tornado.httputil.HTTPServerRequest, **kwargs: Any)

   Bases: :py:obj:`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`.

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


   .. py:method:: get_content_type()

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



   .. py:method:: set_extra_headers(path: str) -> None

      For subclass to add extra headers to the response



.. py:class:: StaticFileHandlerWithEncoding(application: Application, request: tornado.httputil.HTTPServerRequest, **kwargs: Any)

   Bases: :py:obj:`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`.

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


   .. py:method:: 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`.

      .. versionadded:: 3.1



   .. py:method:: get_content_type()

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



