hapic.py 9.6KB

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