decorator.py 9.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. # -*- coding: utf-8 -*-
  2. import functools
  3. import typing
  4. from http import HTTPStatus
  5. from hapic.data import HapicData
  6. from hapic.description import ControllerDescription
  7. from hapic.exception import ProcessException
  8. from hapic.context import ContextInterface
  9. from hapic.processor import ProcessorInterface
  10. from hapic.processor import RequestParameters
  11. # TODO: Ensure usage of DECORATION_ATTRIBUTE_NAME is documented and
  12. # var names correctly choose.
  13. DECORATION_ATTRIBUTE_NAME = '_hapic_decoration_token'
  14. class ControllerWrapper(object):
  15. def before_wrapped_func(
  16. self,
  17. func_args: typing.Tuple[typing.Any, ...],
  18. func_kwargs: typing.Dict[str, typing.Any],
  19. ) -> typing.Union[None, typing.Any]:
  20. pass
  21. def after_wrapped_function(self, response: typing.Any) -> typing.Any:
  22. return response
  23. def get_wrapper(
  24. self,
  25. func: 'typing.Callable[..., typing.Any]',
  26. ) -> 'typing.Callable[..., typing.Any]':
  27. def wrapper(*args, **kwargs) -> typing.Any:
  28. # Note: Design of before_wrapped_func can be to update kwargs
  29. # by reference here
  30. replacement_response = self.before_wrapped_func(args, kwargs)
  31. if replacement_response:
  32. return replacement_response
  33. response = self._execute_wrapped_function(func, args, kwargs)
  34. new_response = self.after_wrapped_function(response)
  35. return new_response
  36. return functools.update_wrapper(wrapper, func)
  37. def _execute_wrapped_function(
  38. self,
  39. func,
  40. func_args,
  41. func_kwargs,
  42. ) -> typing.Any:
  43. return func(*func_args, **func_kwargs)
  44. class InputOutputControllerWrapper(ControllerWrapper):
  45. def __init__(
  46. self,
  47. context: ContextInterface,
  48. processor: ProcessorInterface,
  49. error_http_code: HTTPStatus=HTTPStatus.BAD_REQUEST,
  50. default_http_code: HTTPStatus=HTTPStatus.OK,
  51. ) -> None:
  52. self.context = context
  53. self.processor = processor
  54. self.error_http_code = error_http_code
  55. self.default_http_code = default_http_code
  56. class InputControllerWrapper(InputOutputControllerWrapper):
  57. def before_wrapped_func(
  58. self,
  59. func_args: typing.Tuple[typing.Any, ...],
  60. func_kwargs: typing.Dict[str, typing.Any],
  61. ) -> typing.Any:
  62. # Retrieve hapic_data instance or create new one
  63. # hapic_data is given though decorators
  64. # Important note here: func_kwargs is update by reference !
  65. hapic_data = self.ensure_hapic_data(func_kwargs)
  66. request_parameters = self.get_request_parameters(
  67. func_args,
  68. func_kwargs,
  69. )
  70. try:
  71. processed_data = self.get_processed_data(request_parameters)
  72. self.update_hapic_data(hapic_data, processed_data)
  73. except ProcessException:
  74. error_response = self.get_error_response(request_parameters)
  75. return error_response
  76. @classmethod
  77. def ensure_hapic_data(
  78. cls,
  79. func_kwargs: typing.Dict[str, typing.Any],
  80. ) -> HapicData:
  81. # TODO: Permit other name than "hapic_data" ?
  82. try:
  83. return func_kwargs['hapic_data']
  84. except KeyError:
  85. hapic_data = HapicData()
  86. func_kwargs['hapic_data'] = hapic_data
  87. return hapic_data
  88. def get_request_parameters(
  89. self,
  90. func_args: typing.Tuple[typing.Any, ...],
  91. func_kwargs: typing.Dict[str, typing.Any],
  92. ) -> RequestParameters:
  93. return self.context.get_request_parameters(
  94. *func_args,
  95. **func_kwargs
  96. )
  97. def get_processed_data(
  98. self,
  99. request_parameters: RequestParameters,
  100. ) -> typing.Any:
  101. raise NotImplementedError()
  102. def update_hapic_data(
  103. self,
  104. hapic_data: HapicData,
  105. processed_data: typing.Dict[str, typing.Any],
  106. ) -> None:
  107. raise NotImplementedError()
  108. def get_error_response(
  109. self,
  110. request_parameters: RequestParameters,
  111. ) -> typing.Any:
  112. error = self.processor.get_validation_error(
  113. request_parameters.body_parameters,
  114. )
  115. error_response = self.context.get_validation_error_response(
  116. error,
  117. http_code=self.error_http_code,
  118. )
  119. return error_response
  120. class OutputControllerWrapper(InputOutputControllerWrapper):
  121. def __init__(
  122. self,
  123. context: ContextInterface,
  124. processor: ProcessorInterface,
  125. error_http_code: HTTPStatus=HTTPStatus.INTERNAL_SERVER_ERROR,
  126. default_http_code: HTTPStatus=HTTPStatus.OK,
  127. ) -> None:
  128. super().__init__(
  129. context,
  130. processor,
  131. error_http_code,
  132. default_http_code,
  133. )
  134. def get_error_response(
  135. self,
  136. response: typing.Any,
  137. ) -> typing.Any:
  138. error = self.processor.get_validation_error(response)
  139. error_response = self.context.get_validation_error_response(
  140. error,
  141. http_code=self.error_http_code,
  142. )
  143. return error_response
  144. def after_wrapped_function(self, response: typing.Any) -> typing.Any:
  145. try:
  146. processed_response = self.processor.process(response)
  147. prepared_response = self.context.get_response(
  148. processed_response,
  149. self.default_http_code,
  150. )
  151. return prepared_response
  152. except ProcessException:
  153. # TODO: ici ou ailleurs: il faut pas forcement donner le detail
  154. # de l'erreur (mode debug par exemple)
  155. error_response = self.get_error_response(response)
  156. return error_response
  157. class DecoratedController(object):
  158. def __init__(
  159. self,
  160. token: str,
  161. description: ControllerDescription,
  162. ) -> None:
  163. self._token = token
  164. self._description = description
  165. @property
  166. def token(self) -> str:
  167. return self._token
  168. @property
  169. def description(self) -> ControllerDescription:
  170. return self._description
  171. class OutputBodyControllerWrapper(OutputControllerWrapper):
  172. pass
  173. class OutputHeadersControllerWrapper(OutputControllerWrapper):
  174. # TODO: write me
  175. pass
  176. class InputPathControllerWrapper(InputControllerWrapper):
  177. def update_hapic_data(
  178. self, hapic_data: HapicData,
  179. processed_data: typing.Any,
  180. ) -> None:
  181. hapic_data.path = processed_data
  182. def get_processed_data(
  183. self,
  184. request_parameters: RequestParameters,
  185. ) -> typing.Any:
  186. processed_data = self.processor.process(
  187. request_parameters.path_parameters,
  188. )
  189. return processed_data
  190. class InputQueryControllerWrapper(InputControllerWrapper):
  191. def update_hapic_data(
  192. self, hapic_data: HapicData,
  193. processed_data: typing.Any,
  194. ) -> None:
  195. hapic_data.query = processed_data
  196. def get_processed_data(
  197. self,
  198. request_parameters: RequestParameters,
  199. ) -> typing.Any:
  200. processed_data = self.processor.process(
  201. request_parameters.query_parameters,
  202. )
  203. return processed_data
  204. class InputBodyControllerWrapper(InputControllerWrapper):
  205. def update_hapic_data(
  206. self, hapic_data: HapicData,
  207. processed_data: typing.Any,
  208. ) -> None:
  209. hapic_data.body = processed_data
  210. def get_processed_data(
  211. self,
  212. request_parameters: RequestParameters,
  213. ) -> typing.Any:
  214. processed_data = self.processor.process(
  215. request_parameters.body_parameters,
  216. )
  217. return processed_data
  218. class InputHeadersControllerWrapper(InputControllerWrapper):
  219. def update_hapic_data(
  220. self, hapic_data: HapicData,
  221. processed_data: typing.Any,
  222. ) -> None:
  223. hapic_data.headers = processed_data
  224. def get_processed_data(
  225. self,
  226. request_parameters: RequestParameters,
  227. ) -> typing.Any:
  228. processed_data = self.processor.process(
  229. request_parameters.header_parameters,
  230. )
  231. return processed_data
  232. class InputFormsControllerWrapper(InputControllerWrapper):
  233. def update_hapic_data(
  234. self, hapic_data: HapicData,
  235. processed_data: typing.Any,
  236. ) -> None:
  237. hapic_data.forms = processed_data
  238. def get_processed_data(
  239. self,
  240. request_parameters: RequestParameters,
  241. ) -> typing.Any:
  242. processed_data = self.processor.process(
  243. request_parameters.form_parameters,
  244. )
  245. return processed_data
  246. class ExceptionHandlerControllerWrapper(ControllerWrapper):
  247. def __init__(
  248. self,
  249. handled_exception_class: typing.Type[Exception],
  250. context: ContextInterface,
  251. http_code: HTTPStatus=HTTPStatus.INTERNAL_SERVER_ERROR,
  252. ) -> None:
  253. self.handled_exception_class = handled_exception_class
  254. self.context = context
  255. self.http_code = http_code
  256. def _execute_wrapped_function(
  257. self,
  258. func,
  259. func_args,
  260. func_kwargs,
  261. ) -> typing.Any:
  262. try:
  263. return super()._execute_wrapped_function(
  264. func,
  265. func_args,
  266. func_kwargs,
  267. )
  268. except self.handled_exception_class as exc:
  269. # TODO: error_dict configurable name
  270. # TODO: Who assume error structure ? We have to rethink it
  271. error_dict = {
  272. 'error_message': str(exc),
  273. }
  274. if hasattr(exc, 'error_dict'):
  275. error_dict.update(exc.error_dict)
  276. error_response = self.context.get_response(
  277. error_dict,
  278. self.http_code,
  279. )
  280. return error_response