context.py 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # -*- coding: utf-8 -*-
  2. import json
  3. import typing
  4. from http import HTTPStatus
  5. import bottle
  6. from hapic.exception import OutputValidationException
  7. # from hapic.hapic import _default_global_error_schema
  8. from hapic.processor import RequestParameters, ProcessValidationError
  9. class ContextInterface(object):
  10. def get_request_parameters(self, *args, **kwargs) -> RequestParameters:
  11. raise NotImplementedError()
  12. def get_response(
  13. self,
  14. response: dict,
  15. http_code: int,
  16. ) -> typing.Any:
  17. raise NotImplementedError()
  18. def get_validation_error_response(
  19. self,
  20. error: ProcessValidationError,
  21. http_code: HTTPStatus=HTTPStatus.BAD_REQUEST,
  22. ) -> typing.Any:
  23. raise NotImplementedError()
  24. # TODO: In extension
  25. class BottleContext(ContextInterface):
  26. def get_request_parameters(self, *args, **kwargs) -> RequestParameters:
  27. return RequestParameters(
  28. path_parameters=bottle.request.url_args,
  29. query_parameters=bottle.request.params,
  30. body_parameters=bottle.request.json,
  31. form_parameters=bottle.request.forms,
  32. header_parameters=bottle.request.headers,
  33. )
  34. def get_response(
  35. self,
  36. response: dict,
  37. http_code: int,
  38. ) -> bottle.HTTPResponse:
  39. return bottle.HTTPResponse(
  40. body=json.dumps(response),
  41. headers=[
  42. ('Content-Type', 'application/json'),
  43. ],
  44. status=http_code,
  45. )
  46. def get_validation_error_response(
  47. self,
  48. error: ProcessValidationError,
  49. http_code: HTTPStatus=HTTPStatus.BAD_REQUEST,
  50. ) -> typing.Any:
  51. # TODO
  52. from hapic.hapic import _default_global_error_schema
  53. unmarshall = _default_global_error_schema.dump(error)
  54. if unmarshall.errors:
  55. raise OutputValidationException(
  56. 'Validation error during dump of error response: {}'.format(
  57. str(unmarshall.errors)
  58. )
  59. )
  60. return bottle.HTTPResponse(
  61. body=json.dumps(unmarshall.data),
  62. headers=[
  63. ('Content-Type', 'application/json'),
  64. ],
  65. status=int(http_code),
  66. )