context.py 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # -*- coding: utf-8 -*-
  2. import json
  3. import typing
  4. from http import HTTPStatus
  5. from pyramid.request import Request
  6. from pyramid.response import Response
  7. from hapic.context import ContextInterface
  8. from hapic.exception import OutputValidationException
  9. from hapic.processor import RequestParameters, ProcessValidationError
  10. class PyramidContext(ContextInterface):
  11. def get_request_parameters(self, *args, **kwargs) -> RequestParameters:
  12. req = args[-1] # TODO : Check
  13. assert isinstance(req, Request)
  14. # TODO : move this code to check_json
  15. # same idea as in : https://bottlepy.org/docs/dev/_modules/bottle.html#BaseRequest.json
  16. if req.body and req.content_type in ('application/json', 'application/json-rpc'):
  17. json_body = req.json_body
  18. # TODO : raise exception if not correct , return 400 if uncorrect instead ?
  19. else:
  20. json_body = None
  21. return RequestParameters(
  22. path_parameters=req.matchdict,
  23. query_parameters=req.GET,
  24. body_parameters=json_body,
  25. form_parameters=req.POST,
  26. header_parameters=req.headers,
  27. )
  28. def get_response(
  29. self,
  30. response: dict,
  31. http_code: int,
  32. ) -> Response:
  33. return Response(
  34. body=json.dumps(response),
  35. headers=[
  36. ('Content-Type', 'application/json'),
  37. ],
  38. status=http_code,
  39. )
  40. def get_validation_error_response(
  41. self,
  42. error: ProcessValidationError,
  43. http_code: HTTPStatus=HTTPStatus.BAD_REQUEST,
  44. ) -> typing.Any:
  45. # TODO BS 20171010: Manage error schemas, see #4
  46. from hapic.hapic import _default_global_error_schema
  47. unmarshall = _default_global_error_schema.dump(error)
  48. if unmarshall.errors:
  49. raise OutputValidationException(
  50. 'Validation error during dump of error response: {}'.format(
  51. str(unmarshall.errors)
  52. )
  53. )
  54. return Response(
  55. body=json.dumps(unmarshall.data),
  56. headers=[
  57. ('Content-Type', 'application/json'),
  58. ],
  59. status=int(http_code),
  60. )