context.py 5.0KB

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