[0.5.3] ajout de la config actuelle dans les arguments des routes

This commit is contained in:
Maxime Alves LIRMM 2021-06-15 18:12:13 +02:00
parent aa7ec62c7a
commit 86e8dd3465
6 changed files with 34 additions and 15 deletions

View File

@ -1,5 +1,5 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
__version__ = '0.5.2' __version__ = '0.5.3'
def version(): def version():
return f'HalfAPI version:{__version__}' return f'HalfAPI version:{__version__}'

View File

@ -23,7 +23,7 @@ from timing_asgi import TimingMiddleware
from timing_asgi.integrations import StarletteScopeToName from timing_asgi.integrations import StarletteScopeToName
# module libraries # 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.domain_middleware import DomainMiddleware
from .lib.timing import HTimingClient from .lib.timing import HTimingClient
@ -76,7 +76,7 @@ application = Starlette(
if DOMAINSDICT: if DOMAINSDICT:
application.add_middleware( application.add_middleware(
DomainMiddleware, DomainMiddleware,
config=config config=CONFIG
) )
if SECRET: if SECRET:

View File

@ -47,6 +47,7 @@ logger = logging.getLogger('halfapi')
PROJECT_NAME = os.path.basename(os.getcwd()) PROJECT_NAME = os.path.basename(os.getcwd())
DOMAINSDICT = lambda: {} DOMAINSDICT = lambda: {}
DOMAINS = {}
PRODUCTION = False PRODUCTION = False
LOGLEVEL = 'info' LOGLEVEL = 'info'
HOST = '127.0.0.1' HOST = '127.0.0.1'
@ -56,6 +57,12 @@ SECRET = ''
IS_PROJECT = os.path.isfile('.halfapi/config') IS_PROJECT = os.path.isfile('.halfapi/config')
CONFIG = {
'project_name': PROJECT_NAME,
'production': PRODUCTION,
'secret': SECRET,
'domains': DOMAINS
}
default_config = { default_config = {
'project': { 'project': {
@ -123,12 +130,14 @@ if IS_PROJECT:
raise Exception('Need a project name as argument') raise Exception('Need a project name as argument')
DOMAINSDICT = lambda: d_domains(config) DOMAINSDICT = lambda: d_domains(config)
DOMAINS = DOMAINSDICT()
HOST = config.get('project', 'host') HOST = config.get('project', 'host')
PORT = config.getint('project', 'port') PORT = config.getint('project', 'port')
try: try:
with open(config.get('project', 'secret')) as secret_file: 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 # Set the secret so we can use it in domains
os.environ['HALFAPI_SECRET'] = SECRET os.environ['HALFAPI_SECRET'] = SECRET
except FileNotFoundError as exc: except FileNotFoundError as exc:

View File

@ -26,7 +26,9 @@ def route_decorator(fct: Callable = None, ret_type: str = 'json'):
@acl.args_check @acl.args_check
async def wrapped(request, *args, **kwargs): async def wrapped(request, *args, **kwargs):
return ORJSONResponse( 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: else:
raise Exception('Return type not available') 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'): if not hasattr(m_router, 'ROUTES'):
routes = {'':{}} routes = {'':{}}
acls = m_router.ACLS if hasattr(m_router, 'ACLS') else {}
for verb in VERBS: for verb in VERBS:
if hasattr(m_router, verb.lower()): if not hasattr(m_router, verb.lower()):
routes[''][verb.upper()] = [{ continue
'acl': acl.public
}] """ 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'] = [] routes['']['SUBROUTES'] = []
for item in os.listdir(list(m_router.__path__)[0]): for item in os.listdir(list(m_router.__path__)[0]):
@ -198,14 +209,14 @@ def d_domains(config) -> Dict[str, ModuleType]:
dict[str, ModuleType] dict[str, ModuleType]
""" """
if not config.has_section('domains'): if not 'domains' in config:
return {} return {}
try: try:
sys.path.append('.') sys.path.append('.')
return { return {
domain: importlib.import_module(''.join((domain, module))) 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: except ImportError as exc:
logger.error('Could not load a domain : %s', exc) logger.error('Could not load a domain : %s', exc)

View File

@ -57,8 +57,7 @@ class DomainMiddleware(BaseHTTPMiddleware):
current_domain = cur_path.split('/')[0] current_domain = cur_path.split('/')[0]
try: try:
config_section = self.config.items(current_domain) scope_['config'] = self.config.copy()
scope_['config'] = dict(config_section)
except configparser.NoSectionError: except configparser.NoSectionError:
logger.debug( logger.debug(
'No specific configuration for domain **%s**', current_domain) 'No specific configuration for domain **%s**', current_domain)

View File

@ -74,5 +74,5 @@ def test_get_route(dummy_project, create_route):
from halfapi.app import application from halfapi.app import application
c = TestClient(application) c = TestClient(application)
r = c.get('/test') r = c.get(f'/{dummy_project[1]}/test')
assert r.status_code == 500 assert r.status_code == 200