context.py 4.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. # -*- coding: utf-8 -*-
  2. import json
  3. import re
  4. import typing
  5. try: # Python 3.5+
  6. from http import HTTPStatus
  7. except ImportError:
  8. from http import client as HTTPStatus
  9. import bottle
  10. from multidict import MultiDict
  11. from hapic.context import ContextInterface
  12. from hapic.context import RouteRepresentation
  13. from hapic.decorator import DecoratedController
  14. from hapic.decorator import DECORATION_ATTRIBUTE_NAME
  15. from hapic.exception import OutputValidationException
  16. from hapic.exception import NoRoutesException
  17. from hapic.exception import RouteNotFound
  18. from hapic.processor import RequestParameters
  19. from hapic.processor import ProcessValidationError
  20. # Bottle regular expression to locate url parameters
  21. BOTTLE_RE_PATH_URL = re.compile(r'<([^:<>]+)(?::[^<>]+)?>')
  22. class BottleContext(ContextInterface):
  23. def __init__(self, app: bottle.Bottle):
  24. self.app = app
  25. def get_request_parameters(self, *args, **kwargs) -> RequestParameters:
  26. path_parameters = dict(bottle.request.url_args)
  27. query_parameters = MultiDict(bottle.request.query.allitems())
  28. body_parameters = dict(bottle.request.json or {})
  29. form_parameters = MultiDict(bottle.request.forms.allitems())
  30. header_parameters = dict(bottle.request.headers)
  31. files_parameters = dict(bottle.request.files)
  32. return RequestParameters(
  33. path_parameters=path_parameters,
  34. query_parameters=query_parameters,
  35. body_parameters=body_parameters,
  36. form_parameters=form_parameters,
  37. header_parameters=header_parameters,
  38. files_parameters=files_parameters,
  39. )
  40. def get_response(
  41. self,
  42. response: dict,
  43. http_code: int,
  44. ) -> bottle.HTTPResponse:
  45. return bottle.HTTPResponse(
  46. body=json.dumps(response),
  47. headers=[
  48. ('Content-Type', 'application/json'),
  49. ],
  50. status=http_code,
  51. )
  52. def get_validation_error_response(
  53. self,
  54. error: ProcessValidationError,
  55. http_code: HTTPStatus=HTTPStatus.BAD_REQUEST,
  56. ) -> typing.Any:
  57. # TODO BS 20171010: Manage error schemas, see #4
  58. from hapic.hapic import _default_global_error_schema
  59. unmarshall = _default_global_error_schema.dump(error)
  60. if unmarshall.errors:
  61. raise OutputValidationException(
  62. 'Validation error during dump of error response: {}'.format(
  63. str(unmarshall.errors)
  64. )
  65. )
  66. return bottle.HTTPResponse(
  67. body=json.dumps(unmarshall.data),
  68. headers=[
  69. ('Content-Type', 'application/json'),
  70. ],
  71. status=int(http_code),
  72. )
  73. def find_route(
  74. self,
  75. decorated_controller: DecoratedController,
  76. ) -> RouteRepresentation:
  77. if not self.app.routes:
  78. raise NoRoutesException('There is no routes in your bottle app')
  79. reference = decorated_controller.reference
  80. for route in self.app.routes:
  81. route_token = getattr(
  82. route.callback,
  83. DECORATION_ATTRIBUTE_NAME,
  84. None,
  85. )
  86. match_with_wrapper = route.callback == reference.wrapper
  87. match_with_wrapped = route.callback == reference.wrapped
  88. match_with_token = route_token == reference.token
  89. if match_with_wrapper or match_with_wrapped or match_with_token:
  90. return RouteRepresentation(
  91. rule=self.get_swagger_path(route.rule),
  92. method=route.method.lower(),
  93. original_route_object=route,
  94. )
  95. # TODO BS 20171010: Raise exception or print error ? see #10
  96. raise RouteNotFound(
  97. 'Decorated route "{}" was not found in bottle routes'.format(
  98. decorated_controller.name,
  99. )
  100. )
  101. def get_swagger_path(self, contextualised_rule: str) -> str:
  102. return BOTTLE_RE_PATH_URL.sub(r'{\1}', contextualised_rule)
  103. def by_pass_output_wrapping(self, response: typing.Any) -> bool:
  104. if isinstance(response, bottle.HTTPResponse):
  105. return True
  106. return False