From 19240489dbae6b0cbcbec197c1a1dafc5643bd0b Mon Sep 17 00:00:00 2001 From: Emmanuel Garette Date: Sat, 24 Apr 2021 10:12:32 +0200 Subject: [PATCH] add http static support --- src/risotto/http.py | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/src/risotto/http.py b/src/risotto/http.py index f501397..b5779b3 100644 --- a/src/risotto/http.py +++ b/src/risotto/http.py @@ -1,4 +1,4 @@ -from aiohttp.web import Application, Response, get, post, HTTPBadRequest, HTTPInternalServerError, HTTPNotFound +from aiohttp.web import Application, Response, get, post, HTTPBadRequest, HTTPInternalServerError, HTTPNotFound, static from json import dumps from traceback import print_exc try: @@ -12,12 +12,13 @@ from .utils import _ from .context import Context from .error import CallError, NotAllowedError, RegistrationError from .message import get_messages -from .logger import log +#from .logger import log from .config import get_config from . import services extra_routes = {} +extra_statics = {} def create_context(request): @@ -35,12 +36,21 @@ def register(version: str, """ def decorator(function): if path in extra_routes: - raise RegistrationError(f'the route {path} is already registered') + raise RegistrationError(f'the route "{path}" is already registered') extra_routes[path] = {'function': function, - 'version': version} + 'version': version, + } return decorator +def register_static(path: str, + directory: str, + ) -> None: + if path in extra_statics: + raise RegistrationError(f'the static path "{path}" is already registered') + extra_statics[path] = directory + + class extra_route_handler: async def __new__(cls, request, @@ -70,7 +80,8 @@ class extra_route_handler: # await log.info_msg(kwargs['risotto_context'], # dict(request.match_info)) return Response(text=dumps(returns), - content_type='application/json') + content_type='application/json', + ) async def handle(request): @@ -135,7 +146,7 @@ async def api(request, async def get_app(loop): """ build all routes """ - global extra_routes + global extra_routes, extra_statics services.link_to_dispatcher(dispatcher) app = Application(loop=loop) routes = [] @@ -175,7 +186,14 @@ async def get_app(loop): extra_handler = type(path, (extra_route_handler,), extra) routes.append(get(path, extra_handler)) print(f' - {path} (http_get)') + if extra_statics: + if not extra_routes: + print(_('======== Registered static routes ========')) + for path, directory in extra_statics.items(): + routes.append(static(path, directory)) + print(f' - {path} (static)') del extra_routes + del extra_statics app.router.add_routes(routes) await dispatcher.register_remote() print()