hapic.py 10KB

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