vtn_service.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 = 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 = create_message(response_type, **response_payload)
  40. response = web.Response(text=msg,
  41. status=HTTPStatus.OK,
  42. content_type='application/xml')
  43. else:
  44. template = templates.get_template('oadrResponse.xml')
  45. response = web.Response(
  46. text=template.render(status_code=errorcodes.COMPLIANCE_ERROR,
  47. status_description=f'A message of type {message_type} should not be sent to this endpoint'),
  48. status=HTTPStatus.BAD_REQUEST,
  49. content_type='application/xml')
  50. print(f"Sending {response.text}")
  51. return response