vtn_service.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # SPDX-License-Identifier: Apache-2.0
  2. # Copyright 2020 Contributors to OpenLEADR
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS,
  9. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. # See the License for the specific language governing permissions and
  11. # limitations under the License.
  12. from asyncio import iscoroutine
  13. from http import HTTPStatus
  14. import os
  15. from aiohttp import web
  16. from jinja2 import Environment, PackageLoader, select_autoescape
  17. from .. import errors
  18. from ..messaging import create_message, parse_message
  19. class VTNService:
  20. def __init__(self, vtn_id):
  21. self.vtn_id = vtn_id
  22. self.handlers = {}
  23. for method in [getattr(self, attr) for attr in dir(self) if callable(getattr(self, attr))]:
  24. if hasattr(method, '__message_type__'):
  25. self.handlers[method.__message_type__] = method
  26. async def handler(self, request):
  27. """
  28. Handle all incoming POST requests.
  29. """
  30. content = await request.read()
  31. print(f"Received: {content.decode('utf-8')}")
  32. message_type, message_payload = self._parse_message(content)
  33. print(f"Interpreted message: {message_type}: {message_payload}")
  34. if message_type in self.handlers:
  35. handler = self.handlers[message_type]
  36. response_type, response_payload = await handler(message_payload)
  37. response_payload['vtn_id'] = self.vtn_id
  38. # Create the XML response
  39. msg = self._create_message(response_type, **response_payload)
  40. response = web.Response(text=msg,
  41. status=HTTPStatus.OK,
  42. content_type='application/xml')
  43. else:
  44. msg = self._create_message('oadrResponse',
  45. status_code=errorcodes.COMPLIANCE_ERROR,
  46. status_description=f'A message of type {message_type} should not be sent to this endpoint')
  47. response = web.Response(
  48. text=msg,
  49. status=HTTPStatus.BAD_REQUEST,
  50. content_type='application/xml')
  51. print(f"Sending {response.text}")
  52. return response