risotto/src/risotto/http.py

49 lines
1.6 KiB
Python
Raw Normal View History

2019-11-28 14:50:53 +01:00
from aiohttp.web import Application, Response, get, HTTPBadRequest, HTTPInternalServerError, HTTPNotFound
from .dispatcher import dispatcher
from .utils import _
from .context import Context
from .error import CallError, NotAllowedError
async def handle(request):
version, uri = request.match_info.get_info()['path'].split('/', 2)[-2:]
context = Context()
2019-11-28 14:58:38 +01:00
context.username = request.match_info.get('username', "Anonymous")
2019-11-28 14:50:53 +01:00
try:
2019-11-28 16:51:56 +01:00
text = await dispatcher.call(version,
uri,
context,
# FIXME
id=2,
public_only=True)
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))
return Response(text=str(text))
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:
web_uri = f'/{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-28 14:50:53 +01:00
routes.append(get(web_uri, handle))
print()
app.add_routes(routes)
return app