context.py 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. # -*- coding: utf-8 -*-
  2. import json
  3. import re
  4. import typing
  5. from http import HTTPStatus
  6. import bottle
  7. from hapic.context import ContextInterface
  8. from hapic.exception import OutputValidationException
  9. from hapic.processor import RequestParameters, ProcessValidationError
  10. # Bottle regular expression to locate url parameters
  11. BOTTLE_RE_PATH_URL = re.compile(r'<(?:[^:<>]+:)?([^<>]+)>')
  12. class BottleContext(ContextInterface):
  13. def get_request_parameters(self, *args, **kwargs) -> RequestParameters:
  14. return RequestParameters(
  15. path_parameters=bottle.request.url_args,
  16. query_parameters=bottle.request.params, ## query?
  17. body_parameters=bottle.request.json,
  18. form_parameters=bottle.request.forms,
  19. header_parameters=bottle.request.headers,
  20. )
  21. def get_response(
  22. self,
  23. response: dict,
  24. http_code: int,
  25. ) -> bottle.HTTPResponse:
  26. return bottle.HTTPResponse(
  27. body=json.dumps(response),
  28. headers=[
  29. ('Content-Type', 'application/json'),
  30. ],
  31. status=http_code,
  32. )
  33. def get_validation_error_response(
  34. self,
  35. error: ProcessValidationError,
  36. http_code: HTTPStatus=HTTPStatus.BAD_REQUEST,
  37. ) -> typing.Any:
  38. # TODO BS 20171010: Manage error schemas, see #4
  39. from hapic.hapic import _default_global_error_schema
  40. unmarshall = _default_global_error_schema.dump(error)
  41. if unmarshall.errors:
  42. raise OutputValidationException(
  43. 'Validation error during dump of error response: {}'.format(
  44. str(unmarshall.errors)
  45. )
  46. )
  47. return bottle.HTTPResponse(
  48. body=json.dumps(unmarshall.data),
  49. headers=[
  50. ('Content-Type', 'application/json'),
  51. ],
  52. status=int(http_code),
  53. )