risotto/src/risotto/http.py

73 lines
2.4 KiB
Python
Raw Normal View History

2019-11-29 09:13:16 +01:00
from aiohttp.web import Application, Response, get, post, HTTPBadRequest, HTTPInternalServerError, HTTPNotFound
from tiramisu import Config
from json import dumps
2019-11-28 14:50:53 +01:00
from .dispatcher import dispatcher
from .utils import _
from .context import Context
from .error import CallError, NotAllowedError
2019-11-29 09:13:16 +01:00
from .message import get_messages
from .logger import log
2019-11-28 14:50:53 +01:00
async def handle(request):
2019-11-29 09:13:16 +01:00
version, uri = request.match_info.get_info()['path'].rsplit('/', 2)[-2:]
2019-11-28 14:50:53 +01:00
context = Context()
2019-11-28 14:58:38 +01:00
context.username = request.match_info.get('username', "Anonymous")
2019-11-29 09:13:16 +01:00
kwargs = await request.json()
2019-11-28 14:50:53 +01:00
try:
2019-11-28 16:51:56 +01:00
text = await dispatcher.call(version,
uri,
context,
2019-11-29 09:13:16 +01:00
public_only=True,
**kwargs)
2019-11-28 14:50:53 +01:00
except NotAllowedError as err:
2019-11-28 16:51:56 +01:00
raise HTTPNotFound(reason=str(err))
2019-11-28 14:50:53 +01:00
except CallError as err:
raise HTTPBadRequest(reason=str(err))
except Exception as err:
raise HTTPInternalServerError(reason=str(err))
2019-11-29 09:13:16 +01:00
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))
2019-11-28 14:50:53 +01:00
def get_app():
2019-11-28 16:51:56 +01:00
""" build all routes
"""
2019-11-28 14:50:53 +01:00
app = Application()
routes = []
uris = list(dispatcher.uris.items())
uris.sort()
for version, uris in dispatcher.uris.items():
print()
print(_('======== Registered messages ========'))
for uri in uris:
2019-11-29 09:13:16 +01:00
web_uri = f'/api/{version}/{uri}'
2019-11-28 16:51:56 +01:00
if dispatcher.messages[uri]['public']:
2019-11-28 14:50:53 +01:00
print(f' - {web_uri}')
else:
2019-11-28 16:51:56 +01:00
pattern = dispatcher.messages[uri]['pattern']
print(f' - {web_uri} (private {pattern})')
2019-11-29 09:13:16 +01:00
routes.append(post(web_uri, handle))
routes.append(get(f'/api/{version}', api))
2019-11-28 14:50:53 +01:00
print()
app.add_routes(routes)
return app
2019-11-29 09:13:16 +01:00
tiramisu = None