decorator.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. # -*- coding: utf-8 -*-
  2. import functools
  3. import typing
  4. from http import HTTPStatus
  5. # TODO BS 20171010: bottle specific ! # see #5
  6. import marshmallow
  7. from bottle import HTTPResponse
  8. from hapic.data import HapicData
  9. from hapic.description import ControllerDescription
  10. from hapic.exception import ProcessException
  11. from hapic.context import ContextInterface
  12. from hapic.processor import ProcessorInterface
  13. from hapic.processor import RequestParameters
  14. # TODO: Ensure usage of DECORATION_ATTRIBUTE_NAME is documented and
  15. # var names correctly choose. see #6
  16. DECORATION_ATTRIBUTE_NAME = '_hapic_decoration_token'
  17. class ControllerReference(object):
  18. def __init__(
  19. self,
  20. wrapper: typing.Callable[..., typing.Any],
  21. wrapped: typing.Callable[..., typing.Any],
  22. token: str,
  23. ) -> None:
  24. """
  25. This class is a centralization of different ways to match
  26. final controller with decorated function:
  27. - wrapper will match if final controller is the hapic returned
  28. wrapper
  29. - wrapped will match if final controller is the controller itself
  30. - token will match if only apposed token still exist: This case
  31. happen when hapic decoration is make on class function and final
  32. controller is the same function but as instance function.
  33. :param wrapper: Wrapper returned by decorator
  34. :param wrapped: Function wrapped by decorator
  35. :param token: String token set on these both functions
  36. """
  37. self.wrapper = wrapper
  38. self.wrapped = wrapped
  39. self.token = token
  40. class ControllerWrapper(object):
  41. def before_wrapped_func(
  42. self,
  43. func_args: typing.Tuple[typing.Any, ...],
  44. func_kwargs: typing.Dict[str, typing.Any],
  45. ) -> typing.Union[None, typing.Any]:
  46. pass
  47. def after_wrapped_function(self, response: typing.Any) -> typing.Any:
  48. return response
  49. def get_wrapper(
  50. self,
  51. func: 'typing.Callable[..., typing.Any]',
  52. ) -> 'typing.Callable[..., typing.Any]':
  53. def wrapper(*args, **kwargs) -> typing.Any:
  54. # Note: Design of before_wrapped_func can be to update kwargs
  55. # by reference here
  56. replacement_response = self.before_wrapped_func(args, kwargs)
  57. if replacement_response:
  58. return replacement_response
  59. response = self._execute_wrapped_function(func, args, kwargs)
  60. new_response = self.after_wrapped_function(response)
  61. return new_response
  62. return functools.update_wrapper(wrapper, func)
  63. def _execute_wrapped_function(
  64. self,
  65. func,
  66. func_args,
  67. func_kwargs,
  68. ) -> typing.Any:
  69. return func(*func_args, **func_kwargs)
  70. class InputOutputControllerWrapper(ControllerWrapper):
  71. def __init__(
  72. self,
  73. context: typing.Union[ContextInterface, typing.Callable[[], ContextInterface]], # nopep8
  74. processor: ProcessorInterface,
  75. error_http_code: HTTPStatus=HTTPStatus.BAD_REQUEST,
  76. default_http_code: HTTPStatus=HTTPStatus.OK,
  77. ) -> None:
  78. self._context = context
  79. self.processor = processor
  80. self.error_http_code = error_http_code
  81. self.default_http_code = default_http_code
  82. @property
  83. def context(self) -> ContextInterface:
  84. if callable(self._context):
  85. return self._context()
  86. return self._context
  87. class InputControllerWrapper(InputOutputControllerWrapper):
  88. def before_wrapped_func(
  89. self,
  90. func_args: typing.Tuple[typing.Any, ...],
  91. func_kwargs: typing.Dict[str, typing.Any],
  92. ) -> typing.Any:
  93. # Retrieve hapic_data instance or create new one
  94. # hapic_data is given though decorators
  95. # Important note here: func_kwargs is update by reference !
  96. hapic_data = self.ensure_hapic_data(func_kwargs)
  97. request_parameters = self.get_request_parameters(
  98. func_args,
  99. func_kwargs,
  100. )
  101. try:
  102. processed_data = self.get_processed_data(request_parameters)
  103. self.update_hapic_data(hapic_data, processed_data)
  104. except ProcessException:
  105. error_response = self.get_error_response(request_parameters)
  106. return error_response
  107. @classmethod
  108. def ensure_hapic_data(
  109. cls,
  110. func_kwargs: typing.Dict[str, typing.Any],
  111. ) -> HapicData:
  112. # TODO: Permit other name than "hapic_data" ? see #7
  113. try:
  114. return func_kwargs['hapic_data']
  115. except KeyError:
  116. hapic_data = HapicData()
  117. func_kwargs['hapic_data'] = hapic_data
  118. return hapic_data
  119. def get_request_parameters(
  120. self,
  121. func_args: typing.Tuple[typing.Any, ...],
  122. func_kwargs: typing.Dict[str, typing.Any],
  123. ) -> RequestParameters:
  124. return self.context.get_request_parameters(
  125. *func_args,
  126. **func_kwargs
  127. )
  128. def get_processed_data(
  129. self,
  130. request_parameters: RequestParameters,
  131. ) -> typing.Any:
  132. parameters_data = self.get_parameters_data(request_parameters)
  133. processed_data = self.processor.process(parameters_data)
  134. return processed_data
  135. def get_parameters_data(self, request_parameters: RequestParameters) -> dict:
  136. raise NotImplementedError()
  137. def update_hapic_data(
  138. self,
  139. hapic_data: HapicData,
  140. processed_data: typing.Dict[str, typing.Any],
  141. ) -> None:
  142. raise NotImplementedError()
  143. def get_error_response(
  144. self,
  145. request_parameters: RequestParameters,
  146. ) -> typing.Any:
  147. parameters_data = self.get_parameters_data(request_parameters)
  148. error = self.processor.get_validation_error(parameters_data)
  149. error_response = self.context.get_validation_error_response(
  150. error,
  151. http_code=self.error_http_code,
  152. )
  153. return error_response
  154. class OutputControllerWrapper(InputOutputControllerWrapper):
  155. def __init__(
  156. self,
  157. context: typing.Union[ContextInterface, typing.Callable[[], ContextInterface]], # nopep8
  158. processor: ProcessorInterface,
  159. error_http_code: HTTPStatus=HTTPStatus.INTERNAL_SERVER_ERROR,
  160. default_http_code: HTTPStatus=HTTPStatus.OK,
  161. ) -> None:
  162. super().__init__(
  163. context,
  164. processor,
  165. error_http_code,
  166. default_http_code,
  167. )
  168. def get_error_response(
  169. self,
  170. response: typing.Any,
  171. ) -> typing.Any:
  172. error = self.processor.get_validation_error(response)
  173. error_response = self.context.get_validation_error_response(
  174. error,
  175. http_code=self.error_http_code,
  176. )
  177. return error_response
  178. def after_wrapped_function(self, response: typing.Any) -> typing.Any:
  179. try:
  180. if isinstance(response, HTTPResponse):
  181. return response
  182. processed_response = self.processor.process(response)
  183. prepared_response = self.context.get_response(
  184. processed_response,
  185. self.default_http_code,
  186. )
  187. return prepared_response
  188. except ProcessException:
  189. # TODO: ici ou ailleurs: il faut pas forcement donner le detail
  190. # de l'erreur (mode debug par exemple) see #8
  191. error_response = self.get_error_response(response)
  192. return error_response
  193. class DecoratedController(object):
  194. def __init__(
  195. self,
  196. reference: ControllerReference,
  197. description: ControllerDescription,
  198. name: str='',
  199. ) -> None:
  200. self._reference = reference
  201. self._description = description
  202. self._name = name
  203. @property
  204. def reference(self) -> ControllerReference:
  205. return self._reference
  206. @property
  207. def description(self) -> ControllerDescription:
  208. return self._description
  209. @property
  210. def name(self) -> str:
  211. return self._name
  212. class OutputBodyControllerWrapper(OutputControllerWrapper):
  213. pass
  214. class OutputHeadersControllerWrapper(OutputControllerWrapper):
  215. pass
  216. class OutputFileControllerWrapper(ControllerWrapper):
  217. def __init__(
  218. self,
  219. output_type: str,
  220. default_http_code: HTTPStatus=HTTPStatus.OK,
  221. ) -> None:
  222. self.output_type = output_type
  223. self.default_http_code = default_http_code
  224. class InputPathControllerWrapper(InputControllerWrapper):
  225. def update_hapic_data(
  226. self, hapic_data: HapicData,
  227. processed_data: typing.Any,
  228. ) -> None:
  229. hapic_data.path = processed_data
  230. def get_parameters_data(self, request_parameters: RequestParameters) -> dict:
  231. return request_parameters.path_parameters
  232. class InputQueryControllerWrapper(InputControllerWrapper):
  233. def update_hapic_data(
  234. self, hapic_data: HapicData,
  235. processed_data: typing.Any,
  236. ) -> None:
  237. hapic_data.query = processed_data
  238. def get_parameters_data(self, request_parameters: RequestParameters) -> dict:
  239. return request_parameters.query_parameters
  240. class InputBodyControllerWrapper(InputControllerWrapper):
  241. def update_hapic_data(
  242. self, hapic_data: HapicData,
  243. processed_data: typing.Any,
  244. ) -> None:
  245. hapic_data.body = processed_data
  246. def get_parameters_data(self, request_parameters: RequestParameters) -> dict:
  247. return request_parameters.body_parameters
  248. class InputHeadersControllerWrapper(InputControllerWrapper):
  249. def update_hapic_data(
  250. self, hapic_data: HapicData,
  251. processed_data: typing.Any,
  252. ) -> None:
  253. hapic_data.headers = processed_data
  254. def get_parameters_data(self, request_parameters: RequestParameters) -> dict:
  255. return request_parameters.header_parameters
  256. class InputFormsControllerWrapper(InputControllerWrapper):
  257. def update_hapic_data(
  258. self, hapic_data: HapicData,
  259. processed_data: typing.Any,
  260. ) -> None:
  261. hapic_data.forms = processed_data
  262. def get_parameters_data(self, request_parameters: RequestParameters) -> dict:
  263. return request_parameters.form_parameters
  264. class InputFilesControllerWrapper(InputControllerWrapper):
  265. def update_hapic_data(
  266. self, hapic_data: HapicData,
  267. processed_data: typing.Any,
  268. ) -> None:
  269. hapic_data.files = processed_data
  270. def get_parameters_data(self, request_parameters: RequestParameters) -> dict:
  271. return request_parameters.files_parameters
  272. class ExceptionHandlerControllerWrapper(ControllerWrapper):
  273. def __init__(
  274. self,
  275. handled_exception_class: typing.Type[Exception],
  276. context: typing.Union[ContextInterface, typing.Callable[[], ContextInterface]], # nopep8
  277. schema: marshmallow.Schema,
  278. http_code: HTTPStatus=HTTPStatus.INTERNAL_SERVER_ERROR,
  279. ) -> None:
  280. self.handled_exception_class = handled_exception_class
  281. self._context = context
  282. self.http_code = http_code
  283. self.schema = schema
  284. @property
  285. def context(self) -> ContextInterface:
  286. if callable(self._context):
  287. return self._context()
  288. return self._context
  289. def _execute_wrapped_function(
  290. self,
  291. func,
  292. func_args,
  293. func_kwargs,
  294. ) -> typing.Any:
  295. try:
  296. return super()._execute_wrapped_function(
  297. func,
  298. func_args,
  299. func_kwargs,
  300. )
  301. except self.handled_exception_class as exc:
  302. # TODO: "error_detail" attribute name should be configurable
  303. # TODO BS 20171013: use overrideable mechanism, error object given
  304. # to schema ? see #15
  305. raw_response = {
  306. 'message': str(exc),
  307. 'code': None,
  308. 'detail': getattr(exc, 'error_detail', {}),
  309. }
  310. error_response = self.context.get_response(
  311. raw_response,
  312. self.http_code,
  313. )
  314. return error_response