53 lines
1.7 KiB
Python
53 lines
1.7 KiB
Python
import sys
|
|
from functools import partial
|
|
|
|
from cpl_core.dependency_injection import ServiceProviderABC
|
|
from flask import Flask, request
|
|
|
|
from bot_api.logging.api_logger import ApiLogger
|
|
from bot_api.route.route import Route
|
|
|
|
|
|
class Api(Flask):
|
|
|
|
def __init__(
|
|
self,
|
|
logger: ApiLogger,
|
|
services: ServiceProviderABC,
|
|
*args, **kwargs
|
|
):
|
|
if not args:
|
|
kwargs.setdefault('import_name', __name__)
|
|
|
|
Flask.__init__(self, *args, **kwargs)
|
|
|
|
self._logger = logger
|
|
self._services = services
|
|
|
|
# register before request
|
|
self.before_request_funcs.setdefault(None, []).append(self.before_request)
|
|
|
|
def _register_routes(self):
|
|
for path, f in Route.registered_routes.items():
|
|
cls = None
|
|
qual_name_split = f.__qualname__.split('.')
|
|
if len(qual_name_split) > 0:
|
|
cls_type = vars(sys.modules[f.__module__])[qual_name_split[0]]
|
|
cls = self._services.get_service(cls_type)
|
|
|
|
partial_f = partial(f, self if cls is None else cls)
|
|
partial_f.__name__ = f.__name__
|
|
self.route(path)(partial_f)
|
|
|
|
def before_request(self, *args, **kwargs):
|
|
self._logger.debug(__name__, f'Received GET @{request.url}')
|
|
headers = str(request.headers).replace("\n", "\n\t")
|
|
self._logger.trace(__name__, f'Headers: \n\t{headers}')
|
|
self._logger.trace(__name__, f'Body: {request.get_json(force=True, silent=True)}')
|
|
|
|
def start(self):
|
|
self._logger.info(__name__, f'Starting API')
|
|
self._register_routes()
|
|
from waitress import serve
|
|
serve(self, host="0.0.0.0", port=5000)
|