context.py 5.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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. from hapic.context import BaseContext
  10. from hapic.context import RouteRepresentation
  11. from hapic.decorator import DecoratedController
  12. from hapic.decorator import DECORATION_ATTRIBUTE_NAME
  13. from hapic.exception import OutputValidationException
  14. from hapic.processor import RequestParameters
  15. from hapic.processor import ProcessValidationError
  16. from hapic.error import DefaultErrorBuilder
  17. from hapic.error import ErrorBuilderInterface
  18. from flask import Flask
  19. from flask import send_from_directory
  20. if typing.TYPE_CHECKING:
  21. from flask import Response
  22. # flask regular expression to locate url parameters
  23. FLASK_RE_PATH_URL = re.compile(r'<(?:[^:<>]+:)?([^<>]+)>')
  24. class FlaskContext(BaseContext):
  25. def __init__(
  26. self,
  27. app: Flask,
  28. default_error_builder: ErrorBuilderInterface=None,
  29. ):
  30. self._handled_exceptions = [] # type: typing.List[HandledException] # nopep8
  31. self.app = app
  32. self.default_error_builder = \
  33. default_error_builder or DefaultErrorBuilder() # FDV
  34. def get_request_parameters(self, *args, **kwargs) -> RequestParameters:
  35. from flask import request
  36. return RequestParameters(
  37. path_parameters=request.view_args,
  38. query_parameters=request.args, # TODO: Check
  39. body_parameters=request.get_json(), # TODO: Check
  40. form_parameters=request.form,
  41. header_parameters=request.headers,
  42. files_parameters=request.files,
  43. )
  44. def get_response(
  45. self,
  46. response: str,
  47. http_code: int,
  48. mimetype: str='application/json',
  49. ) -> 'Response':
  50. from flask import Response
  51. return Response(
  52. response=response,
  53. mimetype=mimetype,
  54. status=http_code,
  55. )
  56. def get_validation_error_response(
  57. self,
  58. error: ProcessValidationError,
  59. http_code: HTTPStatus=HTTPStatus.BAD_REQUEST,
  60. ) -> typing.Any:
  61. error_content = self.default_error_builder.build_from_validation_error(
  62. error,
  63. )
  64. # Check error
  65. dumped = self.default_error_builder.dump(error).data
  66. unmarshall = self.default_error_builder.load(dumped)
  67. if unmarshall.errors:
  68. raise OutputValidationException(
  69. 'Validation error during dump of error response: {}'.format(
  70. str(unmarshall.errors)
  71. )
  72. )
  73. from flask import Response
  74. return Response(
  75. response=json.dumps(error_content),
  76. mimetype='application/json',
  77. status=int(http_code),
  78. )
  79. def find_route(
  80. self,
  81. decorated_controller: 'DecoratedController',
  82. ):
  83. reference = decorated_controller.reference
  84. for route in self.app.url_map.iter_rules():
  85. if route.endpoint not in self.app.view_functions:
  86. continue
  87. route_callback = self.app.view_functions[route.endpoint]
  88. route_token = getattr(
  89. route_callback,
  90. DECORATION_ATTRIBUTE_NAME,
  91. None,
  92. )
  93. match_with_wrapper = route_callback == reference.wrapper
  94. match_with_wrapped = route_callback == reference.wrapped
  95. match_with_token = route_token == reference.token
  96. # FIXME - G.M - 2017-12-04 - return list instead of one method
  97. # This fix, return only 1 allowed method, change this when
  98. # RouteRepresentation is adapted to return multiples methods.
  99. method = [x for x in route.methods
  100. if x not in ['OPTIONS', 'HEAD']][0]
  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=method,
  105. original_route_object=route,
  106. )
  107. def get_swagger_path(self, contextualised_rule: str) -> str:
  108. # TODO - G.M - 2017-12-05 Check if all route path are handled correctly
  109. return FLASK_RE_PATH_URL.sub(r'{\1}', contextualised_rule)
  110. def by_pass_output_wrapping(self, response: typing.Any) -> bool:
  111. from flask import Response
  112. return isinstance(response, Response)
  113. def add_view(
  114. self,
  115. route: str,
  116. http_method: str,
  117. view_func: typing.Callable[..., typing.Any],
  118. ) -> None:
  119. self.app.add_url_rule(
  120. methods=[http_method],
  121. rule=route,
  122. view_func=view_func,
  123. )
  124. def serve_directory(
  125. self,
  126. route_prefix: str,
  127. directory_path: str,
  128. ) -> None:
  129. if not route_prefix.endswith('/'):
  130. route_prefix = '{}/'.format(route_prefix)
  131. @self.app.route(
  132. route_prefix,
  133. defaults={
  134. 'path': 'index.html',
  135. }
  136. )
  137. @self.app.route(
  138. '{}<path:path>'.format(route_prefix),
  139. )
  140. def api_doc(path):
  141. return send_from_directory(directory_path, path)
  142. def _add_exception_class_to_catch(
  143. self,
  144. exception_class: typing.Type[Exception],
  145. http_code: int,
  146. ) -> None:
  147. raise NotImplementedError('TODO')