[lib.domain] handle modules without ROUTES attribute

This commit is contained in:
Maxime Alves LIRMM@home 2021-06-14 17:18:47 +02:00
parent 78c75cd60e
commit 7227e2d7f1
2 changed files with 20 additions and 6 deletions

View File

@ -3,12 +3,15 @@
lib/domain.py The domain-scoped utility functions
"""
import os
import sys
import importlib
import logging
from types import ModuleType, FunctionType
from typing import Generator, Dict, List
from halfapi.lib import acl
logger = logging.getLogger("uvicorn.asgi")
VERBS = ('GET', 'POST', 'PUT', 'PATCH', 'DELETE')
@ -106,7 +109,8 @@ def gen_routes(route_params: Dict, path: List, m_router: ModuleType) -> Generato
d_res[verb] = {'fct': fct, 'params': params}
yield f"/{'/'.join([ elt for elt in path if elt ])}", d_res
if len(d_res.keys()) > 1:
yield f"/{'/'.join([ elt for elt in path if elt ])}", d_res
def gen_router_routes(m_router: ModuleType, path: List[str]) -> Generator:
@ -125,11 +129,21 @@ def gen_router_routes(m_router: ModuleType, path: List[str]) -> Generator:
"""
if not hasattr(m_router, 'ROUTES'):
logger.error('Missing *ROUTES* constant in *%s*', m_router.__name__)
raise Exception(f'No ROUTES constant for {m_router.__name__}')
routes = {'':{}}
for verb in VERBS:
if hasattr(m_router, verb.lower()):
routes[''][verb.upper()] = [{
'acl': acl.public
}]
else:
print(f'no {verb.lower()} in {m_router}')
routes = m_router.ROUTES
routes['']['SUBROUTES'] = []
for item in os.listdir(list(m_router.__path__)[0]):
if os.path.isdir(os.path.join(list(m_router.__path__)[0], item)):
routes['']['SUBROUTES'].append(item)
else:
routes = getattr(m_router, 'ROUTES')
for subpath, route_params in routes.items():
path.append(subpath)

View File

@ -34,7 +34,7 @@ def test_create_route(dummy_project, create_route):
assert hasattr(mod, 'post')
assert hasattr(mod, 'put')
def test_create_route(dummy_project, create_route):
def test_has_route(dummy_project, create_route):
create_route(os.path.join(dummy_project[0], dummy_project[1]),
'get', '/test')