context.py 4.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  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 BaseContext
  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. from hapic.error import DefaultErrorBuilder
  21. from hapic.error import ErrorBuilderInterface
  22. # Bottle regular expression to locate url parameters
  23. BOTTLE_RE_PATH_URL = re.compile(r'<([^:<>]+)(?::[^<>]+)?>')
  24. class BottleContext(BaseContext):
  25. def __init__(
  26. self,
  27. app: bottle.Bottle,
  28. default_error_builder: ErrorBuilderInterface=None,
  29. ):
  30. self.app = app
  31. self.default_error_builder = \
  32. default_error_builder or DefaultErrorBuilder() # FDV
  33. def get_request_parameters(self, *args, **kwargs) -> RequestParameters:
  34. path_parameters = dict(bottle.request.url_args)
  35. query_parameters = MultiDict(bottle.request.query.allitems())
  36. body_parameters = dict(bottle.request.json or {})
  37. form_parameters = MultiDict(bottle.request.forms.allitems())
  38. header_parameters = dict(bottle.request.headers)
  39. files_parameters = dict(bottle.request.files)
  40. return RequestParameters(
  41. path_parameters=path_parameters,
  42. query_parameters=query_parameters,
  43. body_parameters=body_parameters,
  44. form_parameters=form_parameters,
  45. header_parameters=header_parameters,
  46. files_parameters=files_parameters,
  47. )
  48. def get_response(
  49. self,
  50. response: str,
  51. http_code: int,
  52. mimetype: str='application/json',
  53. ) -> bottle.HTTPResponse:
  54. return bottle.HTTPResponse(
  55. body=response,
  56. headers=[
  57. ('Content-Type', mimetype),
  58. ],
  59. status=http_code,
  60. )
  61. def get_validation_error_response(
  62. self,
  63. error: ProcessValidationError,
  64. http_code: HTTPStatus=HTTPStatus.BAD_REQUEST,
  65. ) -> typing.Any:
  66. error_content = self.default_error_builder.build_from_validation_error(
  67. error,
  68. )
  69. # Check error
  70. dumped = self.default_error_builder.dump(error).data
  71. unmarshall = self.default_error_builder.load(dumped)
  72. if unmarshall.errors:
  73. raise OutputValidationException(
  74. 'Validation error during dump of error response: {}'.format(
  75. str(unmarshall.errors)
  76. )
  77. )
  78. return bottle.HTTPResponse(
  79. body=json.dumps(error_content),
  80. headers=[
  81. ('Content-Type', 'application/json'),
  82. ],
  83. status=int(http_code),
  84. )
  85. def find_route(
  86. self,
  87. decorated_controller: DecoratedController,
  88. ) -> RouteRepresentation:
  89. if not self.app.routes:
  90. raise NoRoutesException('There is no routes in your bottle app')
  91. reference = decorated_controller.reference
  92. for route in self.app.routes:
  93. route_token = getattr(
  94. route.callback,
  95. DECORATION_ATTRIBUTE_NAME,
  96. None,
  97. )
  98. match_with_wrapper = route.callback == reference.wrapper
  99. match_with_wrapped = route.callback == reference.wrapped
  100. match_with_token = route_token == reference.token
  101. if match_with_wrapper or match_with_wrapped or match_with_token:
  102. return RouteRepresentation(
  103. rule=self.get_swagger_path(route.rule),
  104. method=route.method.lower(),
  105. original_route_object=route,
  106. )
  107. # TODO BS 20171010: Raise exception or print error ? see #10
  108. raise RouteNotFound(
  109. 'Decorated route "{}" was not found in bottle routes'.format(
  110. decorated_controller.name,
  111. )
  112. )
  113. def get_swagger_path(self, contextualised_rule: str) -> str:
  114. return BOTTLE_RE_PATH_URL.sub(r'{\1}', contextualised_rule)
  115. def by_pass_output_wrapping(self, response: typing.Any) -> bool:
  116. if isinstance(response, bottle.HTTPResponse):
  117. return True
  118. return False