hapic.py 10KB

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