decorator.py 13KB

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