[0.5.3] ajout de la config actuelle dans les arguments des routes
This commit is contained in:
parent
aa7ec62c7a
commit
86e8dd3465
|
@ -1,5 +1,5 @@
|
|||
#!/usr/bin/env python3
|
||||
__version__ = '0.5.2'
|
||||
__version__ = '0.5.3'
|
||||
|
||||
def version():
|
||||
return f'HalfAPI version:{__version__}'
|
||||
|
|
|
@ -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:
|
||||
|
|
|
@ -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:
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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
|
||||
|
|
Loading…
Reference in New Issue