decorator.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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. raise NotImplementedError()
  133. def update_hapic_data(
  134. self,
  135. hapic_data: HapicData,
  136. processed_data: typing.Dict[str, typing.Any],
  137. ) -> None:
  138. raise NotImplementedError()
  139. def get_error_response(
  140. self,
  141. request_parameters: RequestParameters,
  142. ) -> typing.Any:
  143. error = self.processor.get_validation_error(
  144. request_parameters.body_parameters,
  145. )
  146. error_response = self.context.get_validation_error_response(
  147. error,
  148. http_code=self.error_http_code,
  149. )
  150. return error_response
  151. class OutputControllerWrapper(InputOutputControllerWrapper):
  152. def __init__(
  153. self,
  154. context: typing.Union[ContextInterface, typing.Callable[[], ContextInterface]], # nopep8
  155. processor: ProcessorInterface,
  156. error_http_code: HTTPStatus=HTTPStatus.INTERNAL_SERVER_ERROR,
  157. default_http_code: HTTPStatus=HTTPStatus.OK,
  158. ) -> None:
  159. super().__init__(
  160. context,
  161. processor,
  162. error_http_code,
  163. default_http_code,
  164. )
  165. def get_error_response(
  166. self,
  167. response: typing.Any,
  168. ) -> typing.Any:
  169. error = self.processor.get_validation_error(response)
  170. error_response = self.context.get_validation_error_response(
  171. error,
  172. http_code=self.error_http_code,
  173. )
  174. return error_response
  175. def after_wrapped_function(self, response: typing.Any) -> typing.Any:
  176. try:
  177. if isinstance(response, HTTPResponse):
  178. return response
  179. processed_response = self.processor.process(response)
  180. prepared_response = self.context.get_response(
  181. processed_response,
  182. self.default_http_code,
  183. )
  184. return prepared_response
  185. except ProcessException:
  186. # TODO: ici ou ailleurs: il faut pas forcement donner le detail
  187. # de l'erreur (mode debug par exemple) see #8
  188. error_response = self.get_error_response(response)
  189. return error_response
  190. class DecoratedController(object):
  191. def __init__(
  192. self,
  193. reference: ControllerReference,
  194. description: ControllerDescription,
  195. name: str='',
  196. ) -> None:
  197. self._reference = reference
  198. self._description = description
  199. self._name = name
  200. @property
  201. def reference(self) -> ControllerReference:
  202. return self._reference
  203. @property
  204. def description(self) -> ControllerDescription:
  205. return self._description
  206. @property
  207. def name(self) -> str:
  208. return self._name
  209. class OutputBodyControllerWrapper(OutputControllerWrapper):
  210. pass
  211. class OutputHeadersControllerWrapper(OutputControllerWrapper):
  212. pass
  213. class InputPathControllerWrapper(InputControllerWrapper):
  214. def update_hapic_data(
  215. self, hapic_data: HapicData,
  216. processed_data: typing.Any,
  217. ) -> None:
  218. hapic_data.path = processed_data
  219. def get_processed_data(
  220. self,
  221. request_parameters: RequestParameters,
  222. ) -> typing.Any:
  223. processed_data = self.processor.process(
  224. request_parameters.path_parameters,
  225. )
  226. return processed_data
  227. class InputQueryControllerWrapper(InputControllerWrapper):
  228. def update_hapic_data(
  229. self, hapic_data: HapicData,
  230. processed_data: typing.Any,
  231. ) -> None:
  232. hapic_data.query = processed_data
  233. def get_processed_data(
  234. self,
  235. request_parameters: RequestParameters,
  236. ) -> typing.Any:
  237. processed_data = self.processor.process(
  238. request_parameters.query_parameters,
  239. )
  240. return processed_data
  241. class InputBodyControllerWrapper(InputControllerWrapper):
  242. def update_hapic_data(
  243. self, hapic_data: HapicData,
  244. processed_data: typing.Any,
  245. ) -> None:
  246. hapic_data.body = processed_data
  247. def get_processed_data(
  248. self,
  249. request_parameters: RequestParameters,
  250. ) -> typing.Any:
  251. processed_data = self.processor.process(
  252. request_parameters.body_parameters,
  253. )
  254. return processed_data
  255. class InputHeadersControllerWrapper(InputControllerWrapper):
  256. def update_hapic_data(
  257. self, hapic_data: HapicData,
  258. processed_data: typing.Any,
  259. ) -> None:
  260. hapic_data.headers = processed_data
  261. def get_processed_data(
  262. self,
  263. request_parameters: RequestParameters,
  264. ) -> typing.Any:
  265. processed_data = self.processor.process(
  266. request_parameters.header_parameters,
  267. )
  268. return processed_data
  269. class InputFormsControllerWrapper(InputControllerWrapper):
  270. def update_hapic_data(
  271. self, hapic_data: HapicData,
  272. processed_data: typing.Any,
  273. ) -> None:
  274. hapic_data.forms = processed_data
  275. def get_processed_data(
  276. self,
  277. request_parameters: RequestParameters,
  278. ) -> typing.Any:
  279. processed_data = self.processor.process(
  280. request_parameters.form_parameters,
  281. )
  282. return processed_data
  283. class ExceptionHandlerControllerWrapper(ControllerWrapper):
  284. def __init__(
  285. self,
  286. handled_exception_class: typing.Type[Exception],
  287. context: typing.Union[ContextInterface, typing.Callable[[], ContextInterface]], # nopep8
  288. schema: marshmallow.Schema,
  289. http_code: HTTPStatus=HTTPStatus.INTERNAL_SERVER_ERROR,
  290. ) -> None:
  291. self.handled_exception_class = handled_exception_class
  292. self._context = context
  293. self.http_code = http_code
  294. self.schema = schema
  295. @property
  296. def context(self) -> ContextInterface:
  297. if callable(self._context):
  298. return self._context()
  299. return self._context
  300. def _execute_wrapped_function(
  301. self,
  302. func,
  303. func_args,
  304. func_kwargs,
  305. ) -> typing.Any:
  306. try:
  307. return super()._execute_wrapped_function(
  308. func,
  309. func_args,
  310. func_kwargs,
  311. )
  312. except self.handled_exception_class as exc:
  313. # TODO: "error_detail" attribute name should be configurable
  314. # TODO BS 20171013: use overrideable mechanism, error object given
  315. # to schema ? see #15
  316. raw_response = {
  317. 'message': str(exc),
  318. 'code': None,
  319. 'detail': getattr(exc, 'error_detail', {}),
  320. }
  321. error_response = self.context.get_response(
  322. raw_response,
  323. self.http_code,
  324. )
  325. return error_response