hapic.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. # -*- coding: utf-8 -*-
  2. import typing
  3. import uuid
  4. from http import HTTPStatus
  5. import functools
  6. import marshmallow
  7. from hapic.buffer import DecorationBuffer
  8. from hapic.context import ContextInterface
  9. from hapic.decorator import DecoratedController
  10. from hapic.decorator import DECORATION_ATTRIBUTE_NAME
  11. from hapic.decorator import ControllerReference
  12. from hapic.decorator import ExceptionHandlerControllerWrapper
  13. from hapic.decorator import InputBodyControllerWrapper
  14. from hapic.decorator import InputHeadersControllerWrapper
  15. from hapic.decorator import InputPathControllerWrapper
  16. from hapic.decorator import InputQueryControllerWrapper
  17. from hapic.decorator import OutputBodyControllerWrapper
  18. from hapic.decorator import OutputHeadersControllerWrapper
  19. from hapic.description import InputBodyDescription
  20. from hapic.description import ErrorDescription
  21. from hapic.description import InputFormsDescription
  22. from hapic.description import InputHeadersDescription
  23. from hapic.description import InputPathDescription
  24. from hapic.description import InputQueryDescription
  25. from hapic.description import OutputBodyDescription
  26. from hapic.description import OutputHeadersDescription
  27. from hapic.doc import DocGenerator
  28. from hapic.processor import ProcessorInterface
  29. from hapic.processor import MarshmallowInputProcessor
  30. from hapic.processor import MarshmallowOutputProcessor
  31. # TODO: Gérer les erreurs avec schema
  32. # TODO: Gérer les erreurs avec schema: pouvoir le spécialiser
  33. # TODO: Gérer les cas ou c'est une liste la réponse (items, item_nb)
  34. # TODO: Confusion nommage body/json/forms
  35. # _waiting = {}
  36. # _endpoints = {}
  37. # FIXME: Voir
  38. class ErrorResponseSchema(marshmallow.Schema):
  39. error_message = marshmallow.fields.String(required=True)
  40. error_details = marshmallow.fields.Dict(required=True)
  41. # FIXME: C'est un gros gros fake !
  42. _default_global_error_schema = ErrorResponseSchema()
  43. class Hapic(object):
  44. def __init__(self):
  45. self._buffer = DecorationBuffer()
  46. self._controllers = [] # type: typing.List[DecoratedController]
  47. self._context = None # type: ContextInterface
  48. # This local function will be pass to different components
  49. # who will need context but declared (like with decorator)
  50. # before context declaration
  51. def context_getter():
  52. return self._context
  53. self._context_getter = context_getter
  54. # TODO: Permettre la surcharge des classes utilisés ci-dessous
  55. @property
  56. def controllers(self) -> typing.List[DecoratedController]:
  57. return self._controllers
  58. @property
  59. def context(self) -> ContextInterface:
  60. return self._context
  61. def with_api_doc(self):
  62. def decorator(func):
  63. # FIXME: casse ou casse pas le bis ?
  64. @functools.wraps(func)
  65. def wrapper(*args, **kwargs):
  66. return func(*args, **kwargs)
  67. token = uuid.uuid4().hex
  68. setattr(wrapper, DECORATION_ATTRIBUTE_NAME, token)
  69. setattr(func, DECORATION_ATTRIBUTE_NAME, token)
  70. description = self._buffer.get_description()
  71. reference = ControllerReference(
  72. wrapper=wrapper,
  73. wrapped=func,
  74. token=token,
  75. )
  76. decorated_controller = DecoratedController(
  77. reference=reference,
  78. description=description,
  79. name=func.__name__,
  80. )
  81. self._buffer.clear()
  82. self._controllers.append(decorated_controller)
  83. return wrapper
  84. return decorator
  85. def set_context(self, context: ContextInterface) -> None:
  86. assert not self._context
  87. self._context = context
  88. def output_body(
  89. self,
  90. schema: typing.Any,
  91. processor: ProcessorInterface = None,
  92. context: ContextInterface = None,
  93. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  94. default_http_code: HTTPStatus = HTTPStatus.OK,
  95. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  96. processor = processor or MarshmallowOutputProcessor()
  97. processor.schema = schema
  98. context = context or self._context_getter
  99. decoration = OutputBodyControllerWrapper(
  100. context=context,
  101. processor=processor,
  102. error_http_code=error_http_code,
  103. default_http_code=default_http_code,
  104. )
  105. def decorator(func):
  106. self._buffer.output_body = OutputBodyDescription(decoration)
  107. return decoration.get_wrapper(func)
  108. return decorator
  109. def output_headers(
  110. self,
  111. schema: typing.Any,
  112. processor: ProcessorInterface = None,
  113. context: ContextInterface = None,
  114. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  115. default_http_code: HTTPStatus = HTTPStatus.OK,
  116. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  117. processor = processor or MarshmallowOutputProcessor()
  118. processor.schema = schema
  119. context = context or self._context_getter
  120. decoration = OutputHeadersControllerWrapper(
  121. context=context,
  122. processor=processor,
  123. error_http_code=error_http_code,
  124. default_http_code=default_http_code,
  125. )
  126. def decorator(func):
  127. self._buffer.output_headers = OutputHeadersDescription(decoration)
  128. return decoration.get_wrapper(func)
  129. return decorator
  130. def input_headers(
  131. self,
  132. schema: typing.Any,
  133. processor: ProcessorInterface = None,
  134. context: ContextInterface = None,
  135. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  136. default_http_code: HTTPStatus = HTTPStatus.OK,
  137. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  138. processor = processor or MarshmallowInputProcessor()
  139. processor.schema = schema
  140. context = context or self._context_getter
  141. decoration = InputHeadersControllerWrapper(
  142. context=context,
  143. processor=processor,
  144. error_http_code=error_http_code,
  145. default_http_code=default_http_code,
  146. )
  147. def decorator(func):
  148. self._buffer.input_headers = InputHeadersDescription(decoration)
  149. return decoration.get_wrapper(func)
  150. return decorator
  151. def input_path(
  152. self,
  153. schema: typing.Any,
  154. processor: ProcessorInterface = None,
  155. context: ContextInterface = None,
  156. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  157. default_http_code: HTTPStatus = HTTPStatus.OK,
  158. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  159. processor = processor or MarshmallowInputProcessor()
  160. processor.schema = schema
  161. context = context or self._context_getter
  162. decoration = InputPathControllerWrapper(
  163. context=context,
  164. processor=processor,
  165. error_http_code=error_http_code,
  166. default_http_code=default_http_code,
  167. )
  168. def decorator(func):
  169. self._buffer.input_path = InputPathDescription(decoration)
  170. return decoration.get_wrapper(func)
  171. return decorator
  172. def input_query(
  173. self,
  174. schema: typing.Any,
  175. processor: ProcessorInterface = None,
  176. context: ContextInterface = None,
  177. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  178. default_http_code: HTTPStatus = HTTPStatus.OK,
  179. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  180. processor = processor or MarshmallowInputProcessor()
  181. processor.schema = schema
  182. context = context or self._context_getter
  183. decoration = InputQueryControllerWrapper(
  184. context=context,
  185. processor=processor,
  186. error_http_code=error_http_code,
  187. default_http_code=default_http_code,
  188. )
  189. def decorator(func):
  190. self._buffer.input_query = InputQueryDescription(decoration)
  191. return decoration.get_wrapper(func)
  192. return decorator
  193. def input_body(
  194. self,
  195. schema: typing.Any,
  196. processor: ProcessorInterface = None,
  197. context: ContextInterface = None,
  198. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  199. default_http_code: HTTPStatus = HTTPStatus.OK,
  200. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  201. processor = processor or MarshmallowInputProcessor()
  202. processor.schema = schema
  203. context = context or self._context_getter
  204. decoration = InputBodyControllerWrapper(
  205. context=context,
  206. processor=processor,
  207. error_http_code=error_http_code,
  208. default_http_code=default_http_code,
  209. )
  210. def decorator(func):
  211. self._buffer.input_body = InputBodyDescription(decoration)
  212. return decoration.get_wrapper(func)
  213. return decorator
  214. def input_forms(
  215. self,
  216. schema: typing.Any,
  217. processor: ProcessorInterface=None,
  218. context: ContextInterface=None,
  219. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  220. default_http_code: HTTPStatus = HTTPStatus.OK,
  221. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  222. processor = processor or MarshmallowInputProcessor()
  223. processor.schema = schema
  224. context = context or self._context_getter
  225. decoration = InputBodyControllerWrapper(
  226. context=context,
  227. processor=processor,
  228. error_http_code=error_http_code,
  229. default_http_code=default_http_code,
  230. )
  231. def decorator(func):
  232. self._buffer.input_forms = InputFormsDescription(decoration)
  233. return decoration.get_wrapper(func)
  234. return decorator
  235. def handle_exception(
  236. self,
  237. handled_exception_class: typing.Type[Exception],
  238. http_code: HTTPStatus = HTTPStatus.INTERNAL_SERVER_ERROR,
  239. context: ContextInterface = None,
  240. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  241. context = context or self._context_getter
  242. decoration = ExceptionHandlerControllerWrapper(
  243. handled_exception_class,
  244. context,
  245. http_code,
  246. )
  247. def decorator(func):
  248. self._buffer.errors.append(ErrorDescription(decoration))
  249. return decoration.get_wrapper(func)
  250. return decorator
  251. def generate_doc(self, app): # FIXME: j'ai du tricher avec app
  252. # FIXME @Damien bottle specific code !
  253. # rendre ca generique
  254. app = app or self._context.get_app()
  255. doc_generator = DocGenerator()
  256. return doc_generator.get_doc(self._controllers, app)