Source code for kuha_document_store.serve

#!/usr/bin/env python3
# Author(s): Toni Sissala
# Copyright 2020 Finnish Social Science Data Archive FSD / University of Tampere
# Licensed under the EUPL. See LICENSE.txt for full license.
"""Main entry point for starting Document Store server.
"""
import sys

import logging

import kuha_common.server
from kuha_common import (
    conf,
    cli_setup
)
from kuha_common.document_store.records import COLLECTIONS

from kuha_document_store import database
from kuha_document_store.handlers import (
    RestApiHandler,
    QueryHandler
)


_logger = logging.getLogger(__name__)


[docs]def get_app(api_version, **kw): """Setup routes and return initialized Tornado web application. Additional keyword arguments are passed to WebApplication. :param str api_version: HTTP Api version gets prepended to routes. :returns: Tornado web application. :rtype: :obj:`tornado.web.Application` """ collections = r'|'.join(COLLECTIONS) handlers = [ # REST (kuha_common.server.str_api_endpoint( api_version, r"(?P<collection>{})/?".format(collections) ), RestApiHandler), (kuha_common.server.str_api_endpoint( api_version, r"(?P<collection>{})/(?P<resource_id>\w+)".format(collections) ), RestApiHandler), # QUERY WITH JSON-BODY (kuha_common.server.str_api_endpoint( api_version, r"query/(?P<collection>{})/?".format(collections) ), QueryHandler), ] web_app = kuha_common.server.WebApplication(handlers, **kw) return web_app
def configure(): conf.load('Kuha Document Store', package='kuha_document_store', env_var_prefix='KUHA_', description='Run Kuha document store server.') conf.add_config_arg() conf.add_print_arg() database.add_cli_args(conf) conf.add('--port', help='Port of Kuha document store database.', default=6001, env_var='DS_PORT', type=int) conf.add('--api-version', help='Document Store api version.', default='v0', env_var='DS_API_VERSION', type=str) return cli_setup.setup_common_modules(cli_setup.MOD_LOGGING, cli_setup.MOD_SERVER)
[docs]def main(): """Application main function. Parse commandline for settings. Initialize database and web application. Start serving via :func:`kuha_common.server.serve`. Exit on exceptions propagated at this level. :returns: exit code, 1 on error, 0 on success. :rtype: int """ rval = 0 settings = configure() if settings.print_configuration: print("Print active configuration and exit\n") for key, value in settings._get_kwargs(): print("{} ... {}".format(key, value)) return rval db = database.db_from_settings(settings) web_app = get_app(settings.api_version, db=db) try: kuha_common.server.serve(web_app, settings.port, on_exit=db.close) except KeyboardInterrupt: rval = 1 _logger.warning("Shutdown by CTRL + C") except: rval = 1 _logger.exception("Exception in main()") finally: logging.info("Shutdown") return rval
if __name__ == '__main__': sys.exit(main())