add GET /api/v1 to get API description

This commit is contained in:
Emmanuel Garette 2019-11-29 09:13:16 +01:00
parent 51df2a1ba7
commit e74391b77a
4 changed files with 49 additions and 14 deletions

View File

@ -278,6 +278,8 @@ class Dispatcher(RegisterDispatcher):
print_exc()
log.error_msg(version, uri, new_context, kwargs, 'call', err)
raise CallError(str(err))
# FIXME notification
# FIXME valider le retour!
log.info_msg(version, uri, new_context, kwargs, 'call', _(f'returns {returns}'))
return returns

View File

@ -1,28 +1,48 @@
from aiohttp.web import Application, Response, get, HTTPBadRequest, HTTPInternalServerError, HTTPNotFound
from aiohttp.web import Application, Response, get, post, HTTPBadRequest, HTTPInternalServerError, HTTPNotFound
from tiramisu import Config
from json import dumps
from .dispatcher import dispatcher
from .utils import _
from .context import Context
from .error import CallError, NotAllowedError
from .message import get_messages
from .logger import log
async def handle(request):
version, uri = request.match_info.get_info()['path'].split('/', 2)[-2:]
version, uri = request.match_info.get_info()['path'].rsplit('/', 2)[-2:]
context = Context()
context.username = request.match_info.get('username', "Anonymous")
kwargs = await request.json()
try:
text = await dispatcher.call(version,
uri,
context,
# FIXME
id=2,
public_only=True)
public_only=True,
**kwargs)
except NotAllowedError as err:
raise HTTPNotFound(reason=str(err))
except CallError as err:
raise HTTPBadRequest(reason=str(err))
except Exception as err:
raise HTTPInternalServerError(reason=str(err))
return Response(text=str(text))
return Response(text=dumps({'response': text}))
async def api(request):
context = Context()
context.username = request.match_info.get('username', "Anonymous")
path = request.match_info.get_info()['path']
if path.endswith('/'):
path = path[:-1]
version = path.rsplit('/', 1)[-1]
log.info_msg(version, None, context, {}, None, _(f'get {version} API'))
global tiramisu
if not tiramisu:
config = Config(get_messages(load_shortarg=True,
only_public=True)[1])
tiramisu = config.option.dict(remotable='none')
return Response(text=dumps(tiramisu))
def get_app():
@ -36,13 +56,17 @@ def get_app():
print()
print(_('======== Registered messages ========'))
for uri in uris:
web_uri = f'/{version}/{uri}'
web_uri = f'/api/{version}/{uri}'
if dispatcher.messages[uri]['public']:
print(f' - {web_uri}')
else:
pattern = dispatcher.messages[uri]['pattern']
print(f' - {web_uri} (private {pattern})')
routes.append(get(web_uri, handle))
routes.append(post(web_uri, handle))
routes.append(get(f'/api/{version}', api))
print()
app.add_routes(routes)
return app
tiramisu = None

View File

@ -12,9 +12,9 @@ class Logger:
type: str):
paths = risotto_context.paths
if len(paths) == 1:
paths_msg = f'messages {type}ed: {paths[0]}'
paths_msg = f' messages {type}ed: {paths[0]}'
else:
paths_msg = f'sub-messages {type}ed: '
paths_msg = f' sub-messages {type}ed: '
paths_msg += ' > '.join(paths)
return paths_msg
@ -40,8 +40,17 @@ class Logger:
msg: str=''):
""" send message with common information
"""
paths_msg = self._get_message_paths(risotto_context, type)
print(_(f'{risotto_context.username}: INFO: {paths_msg} with arguments "{arguments}" {msg}'))
if risotto_context.paths:
paths_msg = self._get_message_paths(risotto_context, type)
else:
paths_msg = ''
tmsg = _(f'{risotto_context.username}: INFO:{paths_msg}')
if arguments:
tmsg += _(f' with arguments "{arguments}"')
if msg:
tmsg += f' {msg}'
print(tmsg)
log = Logger()

View File

@ -9,8 +9,8 @@ class Risotto(Controller):
@register('v1.config.session.server.start', None)
async def get_configuration(self, risotto_context, id):
stop = await self.call('v1.config.session.server.stop', risotto_context, sessionid=str(id))
await self.publish('v1.config.configuration.server.updated', risotto_context, server_id=1, deploy=True)
#stop = await self.call('v1.config.session.server.stop', risotto_context, sessionid=str(id))
#await self.publish('v1.config.configuration.server.updated', risotto_context, server_id=1, deploy=True)
return {'start': id}
@register('v1.config.session.server.stop', None)