vtn_service.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. from asyncio import iscoroutine
  2. from http import HTTPStatus
  3. import random
  4. import string
  5. from . import api
  6. from .. import config, errors
  7. from ..utils import parse_message, indent_xml
  8. class VTNService:
  9. """
  10. This is the default OpenADR handler. You should subclass this with your
  11. specific services.
  12. """
  13. def __init__(self):
  14. self.handlers = {}
  15. for method in [getattr(self, attr) for attr in dir(self) if callable(getattr(self, attr))]:
  16. if hasattr(method, '__message_type__'):
  17. print(f"Adding {method.__name__} as handler for {method.__message_type__}")
  18. self.handlers[method.__message_type__] = method
  19. async def on_request(self, request, response):
  20. """
  21. This is the default handler that is used by python-responder. It will
  22. look for a handler of the message type in one of the subclasses.
  23. """
  24. print()
  25. print()
  26. print("================================================================================")
  27. print(f" NEW REQUEST to {request.url.path} ")
  28. print("================================================================================")
  29. content = await request.content
  30. print(f"Received: {content.decode('utf-8')}")
  31. message_type, message_payload = parse_message(content)
  32. print(f"Interpreted message: {message_type}: {message_payload}")
  33. if message_type in self.handlers:
  34. handler = self.handlers[message_type]
  35. result = handler(message_payload)
  36. if iscoroutine(result):
  37. response_type, response_payload = await result
  38. else:
  39. response_type, response_payload = result
  40. response.html = indent_xml(api.template(f'{response_type}.xml', **response_payload))
  41. print(f"Sending {response.html}")
  42. else:
  43. response.html = indent_xml(api.template('oadrResponse.xml',
  44. status_code=errorcodes.COMPLIANCE_ERROR,
  45. status_description=f'A message of type {message_type} should not be sent to this endpoint'))
  46. print(f"Sending {response.html}")
  47. response.status_code = HTTPStatus.BAD_REQUEST