From 86e8dd3465e0bd0f3d49f28fd9e05a52874e969a Mon Sep 17 00:00:00 2001 From: Maxime Alves LIRMM Date: Tue, 15 Jun 2021 18:12:13 +0200 Subject: [PATCH] [0.5.3] ajout de la config actuelle dans les arguments des routes --- halfapi/__init__.py | 2 +- halfapi/app.py | 4 ++-- halfapi/conf.py | 11 ++++++++++- halfapi/lib/domain.py | 25 ++++++++++++++++++------- halfapi/lib/domain_middleware.py | 3 +-- tests/test_dummy_project_router.py | 4 ++-- 6 files changed, 34 insertions(+), 15 deletions(-) diff --git a/halfapi/__init__.py b/halfapi/__init__.py index 9274551..7876ed0 100644 --- a/halfapi/__init__.py +++ b/halfapi/__init__.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -__version__ = '0.5.2' +__version__ = '0.5.3' def version(): return f'HalfAPI version:{__version__}' diff --git a/halfapi/app.py b/halfapi/app.py index 5b471f3..7e72090 100644 --- a/halfapi/app.py +++ b/halfapi/app.py @@ -23,7 +23,7 @@ from timing_asgi import TimingMiddleware from timing_asgi.integrations import StarletteScopeToName # module libraries -from halfapi.conf import config, SECRET, PRODUCTION, DOMAINSDICT +from halfapi.conf import CONFIG, SECRET, PRODUCTION, DOMAINSDICT from .lib.domain_middleware import DomainMiddleware from .lib.timing import HTimingClient @@ -76,7 +76,7 @@ application = Starlette( if DOMAINSDICT: application.add_middleware( DomainMiddleware, - config=config + config=CONFIG ) if SECRET: diff --git a/halfapi/conf.py b/halfapi/conf.py index 6d0d751..c69ecc7 100644 --- a/halfapi/conf.py +++ b/halfapi/conf.py @@ -47,6 +47,7 @@ logger = logging.getLogger('halfapi') PROJECT_NAME = os.path.basename(os.getcwd()) DOMAINSDICT = lambda: {} +DOMAINS = {} PRODUCTION = False LOGLEVEL = 'info' HOST = '127.0.0.1' @@ -56,6 +57,12 @@ SECRET = '' IS_PROJECT = os.path.isfile('.halfapi/config') +CONFIG = { + 'project_name': PROJECT_NAME, + 'production': PRODUCTION, + 'secret': SECRET, + 'domains': DOMAINS +} default_config = { 'project': { @@ -123,12 +130,14 @@ if IS_PROJECT: raise Exception('Need a project name as argument') DOMAINSDICT = lambda: d_domains(config) + DOMAINS = DOMAINSDICT() HOST = config.get('project', 'host') PORT = config.getint('project', 'port') try: with open(config.get('project', 'secret')) as secret_file: - SECRET = secret_file.read() + SECRET = secret_file.read().strip() + CONFIG['secret'] = SECRET.strip() # Set the secret so we can use it in domains os.environ['HALFAPI_SECRET'] = SECRET except FileNotFoundError as exc: diff --git a/halfapi/lib/domain.py b/halfapi/lib/domain.py index 10babab..01db66d 100644 --- a/halfapi/lib/domain.py +++ b/halfapi/lib/domain.py @@ -26,7 +26,9 @@ def route_decorator(fct: Callable = None, ret_type: str = 'json'): @acl.args_check async def wrapped(request, *args, **kwargs): return ORJSONResponse( - fct(**request.path_params, data=kwargs.get('data'))) + fct(**request.path_params, halfapi={'user': request.user if + 'user' in request else None, + 'config': request.scope['config']}, data=kwargs.get('data'))) else: raise Exception('Return type not available') @@ -150,11 +152,20 @@ def gen_router_routes(m_router: ModuleType, path: List[str]) -> Generator: if not hasattr(m_router, 'ROUTES'): routes = {'':{}} + acls = m_router.ACLS if hasattr(m_router, 'ACLS') else {} + for verb in VERBS: - if hasattr(m_router, verb.lower()): - routes[''][verb.upper()] = [{ - 'acl': acl.public - }] + if not hasattr(m_router, verb.lower()): + continue + + """ There is a "verb" route in the router + """ + + if verb.upper() not in acls: + continue + + routes[''][verb.upper()] = [] + routes[''][verb.upper()] = m_router.ACLS[verb.upper()].copy() routes['']['SUBROUTES'] = [] for item in os.listdir(list(m_router.__path__)[0]): @@ -198,14 +209,14 @@ def d_domains(config) -> Dict[str, ModuleType]: dict[str, ModuleType] """ - if not config.has_section('domains'): + if not 'domains' in config: return {} try: sys.path.append('.') return { domain: importlib.import_module(''.join((domain, module))) - for domain, module in config.items('domains') + for domain, module in config['domains'].items() } except ImportError as exc: logger.error('Could not load a domain : %s', exc) diff --git a/halfapi/lib/domain_middleware.py b/halfapi/lib/domain_middleware.py index 5215fec..7427d86 100644 --- a/halfapi/lib/domain_middleware.py +++ b/halfapi/lib/domain_middleware.py @@ -57,8 +57,7 @@ class DomainMiddleware(BaseHTTPMiddleware): current_domain = cur_path.split('/')[0] try: - config_section = self.config.items(current_domain) - scope_['config'] = dict(config_section) + scope_['config'] = self.config.copy() except configparser.NoSectionError: logger.debug( 'No specific configuration for domain **%s**', current_domain) diff --git a/tests/test_dummy_project_router.py b/tests/test_dummy_project_router.py index 5351a1f..abf88f7 100644 --- a/tests/test_dummy_project_router.py +++ b/tests/test_dummy_project_router.py @@ -74,5 +74,5 @@ def test_get_route(dummy_project, create_route): from halfapi.app import application c = TestClient(application) - r = c.get('/test') - assert r.status_code == 500 + r = c.get(f'/{dummy_project[1]}/test') + assert r.status_code == 200