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() print_exc()
log.error_msg(version, uri, new_context, kwargs, 'call', err) log.error_msg(version, uri, new_context, kwargs, 'call', err)
raise CallError(str(err)) raise CallError(str(err))
# FIXME notification
# FIXME valider le retour!
log.info_msg(version, uri, new_context, kwargs, 'call', _(f'returns {returns}')) log.info_msg(version, uri, new_context, kwargs, 'call', _(f'returns {returns}'))
return 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 .dispatcher import dispatcher
from .utils import _ from .utils import _
from .context import Context from .context import Context
from .error import CallError, NotAllowedError from .error import CallError, NotAllowedError
from .message import get_messages
from .logger import log
async def handle(request): 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 = Context()
context.username = request.match_info.get('username', "Anonymous") context.username = request.match_info.get('username', "Anonymous")
kwargs = await request.json()
try: try:
text = await dispatcher.call(version, text = await dispatcher.call(version,
uri, uri,
context, context,
# FIXME public_only=True,
id=2, **kwargs)
public_only=True)
except NotAllowedError as err: except NotAllowedError as err:
raise HTTPNotFound(reason=str(err)) raise HTTPNotFound(reason=str(err))
except CallError as err: except CallError as err:
raise HTTPBadRequest(reason=str(err)) raise HTTPBadRequest(reason=str(err))
except Exception as err: except Exception as err:
raise HTTPInternalServerError(reason=str(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(): def get_app():
@ -36,13 +56,17 @@ def get_app():
print() print()
print(_('======== Registered messages ========')) print(_('======== Registered messages ========'))
for uri in uris: for uri in uris:
web_uri = f'/{version}/{uri}' web_uri = f'/api/{version}/{uri}'
if dispatcher.messages[uri]['public']: if dispatcher.messages[uri]['public']:
print(f' - {web_uri}') print(f' - {web_uri}')
else: else:
pattern = dispatcher.messages[uri]['pattern'] pattern = dispatcher.messages[uri]['pattern']
print(f' - {web_uri} (private {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() print()
app.add_routes(routes) app.add_routes(routes)
return app return app
tiramisu = None

View File

@ -40,8 +40,17 @@ class Logger:
msg: str=''): msg: str=''):
""" send message with common information """ send message with common information
""" """
if risotto_context.paths:
paths_msg = self._get_message_paths(risotto_context, type) paths_msg = self._get_message_paths(risotto_context, type)
print(_(f'{risotto_context.username}: INFO: {paths_msg} with arguments "{arguments}" {msg}')) 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() log = Logger()

View File

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