context.py 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. class BottleContext(ContextInterface):
  25. def get_request_parameters(self, *args, **kwargs) -> RequestParameters:
  26. return RequestParameters(
  27. path_parameters=bottle.request.url_args,
  28. query_parameters=bottle.request.params,
  29. body_parameters=bottle.request.json,
  30. form_parameters=bottle.request.forms,
  31. header_parameters=bottle.request.headers,
  32. )
  33. def get_response(
  34. self,
  35. response: dict,
  36. http_code: int,
  37. ) -> bottle.HTTPResponse:
  38. return bottle.HTTPResponse(
  39. body=json.dumps(response),
  40. headers=[
  41. ('Content-Type', 'application/json'),
  42. ],
  43. status=http_code,
  44. )
  45. def get_validation_error_response(
  46. self,
  47. error: ProcessValidationError,
  48. http_code: HTTPStatus=HTTPStatus.BAD_REQUEST,
  49. ) -> typing.Any:
  50. # TODO
  51. from hapic.hapic import _default_global_error_schema
  52. unmarshall = _default_global_error_schema.dump(error)
  53. if unmarshall.errors:
  54. raise OutputValidationException(
  55. 'Validation error during dump of error response: {}'.format(
  56. str(unmarshall.errors)
  57. )
  58. )
  59. return bottle.HTTPResponse(
  60. body=json.dumps(unmarshall.data),
  61. headers=[
  62. ('Content-Type', 'application/json'),
  63. ],
  64. status=int(http_code),
  65. )