hapic.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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 InputFilesControllerWrapper
  18. from hapic.decorator import OutputBodyControllerWrapper
  19. from hapic.decorator import OutputHeadersControllerWrapper
  20. from hapic.decorator import OutputFileControllerWrapper
  21. from hapic.description import InputBodyDescription
  22. from hapic.description import ErrorDescription
  23. from hapic.description import InputFormsDescription
  24. from hapic.description import InputHeadersDescription
  25. from hapic.description import InputPathDescription
  26. from hapic.description import InputQueryDescription
  27. from hapic.description import InputFilesDescription
  28. from hapic.description import OutputBodyDescription
  29. from hapic.description import OutputHeadersDescription
  30. from hapic.description import OutputFileDescription
  31. from hapic.doc import DocGenerator
  32. from hapic.processor import ProcessorInterface
  33. from hapic.processor import MarshmallowInputProcessor
  34. from hapic.processor import MarshmallowInputFilesProcessor
  35. from hapic.processor import MarshmallowOutputProcessor
  36. class ErrorResponseSchema(marshmallow.Schema):
  37. message = marshmallow.fields.String(required=True)
  38. details = marshmallow.fields.Dict(required=False, missing={})
  39. code = marshmallow.fields.Raw(missing=None)
  40. _default_global_error_schema = ErrorResponseSchema()
  41. # TODO: Gérer les cas ou c'est une liste la réponse (items, item_nb), see #12
  42. # TODO: Confusion nommage body/json/forms, see #13
  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, see #14
  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. @functools.wraps(func)
  64. def wrapper(*args, **kwargs):
  65. return func(*args, **kwargs)
  66. token = uuid.uuid4().hex
  67. setattr(wrapper, DECORATION_ATTRIBUTE_NAME, token)
  68. setattr(func, DECORATION_ATTRIBUTE_NAME, token)
  69. description = self._buffer.get_description()
  70. reference = ControllerReference(
  71. wrapper=wrapper,
  72. wrapped=func,
  73. token=token,
  74. )
  75. decorated_controller = DecoratedController(
  76. reference=reference,
  77. description=description,
  78. name=func.__name__,
  79. )
  80. self._buffer.clear()
  81. self._controllers.append(decorated_controller)
  82. return wrapper
  83. return decorator
  84. def set_context(self, context: ContextInterface) -> None:
  85. assert not self._context
  86. self._context = context
  87. def output_body(
  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 MarshmallowOutputProcessor()
  96. processor.schema = schema
  97. context = context or self._context_getter
  98. decoration = OutputBodyControllerWrapper(
  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_body = OutputBodyDescription(decoration)
  106. return decoration.get_wrapper(func)
  107. return decorator
  108. def output_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 MarshmallowOutputProcessor()
  117. processor.schema = schema
  118. context = context or self._context_getter
  119. decoration = OutputHeadersControllerWrapper(
  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.output_headers = OutputHeadersDescription(decoration)
  127. return decoration.get_wrapper(func)
  128. return decorator
  129. # TODO BS 20171102: Think about possibilities to validate output ? (with mime type, or validator)
  130. def output_file(
  131. self,
  132. output_type: str,
  133. default_http_code: HTTPStatus = HTTPStatus.OK,
  134. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  135. decoration = OutputFileControllerWrapper(
  136. output_type=output_type,
  137. default_http_code=default_http_code,
  138. )
  139. def decorator(func):
  140. self._buffer.output_file = OutputFileDescription(decoration)
  141. return decoration.get_wrapper(func)
  142. return decorator
  143. def input_headers(
  144. self,
  145. schema: typing.Any,
  146. processor: ProcessorInterface = None,
  147. context: ContextInterface = None,
  148. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  149. default_http_code: HTTPStatus = HTTPStatus.OK,
  150. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  151. processor = processor or MarshmallowInputProcessor()
  152. processor.schema = schema
  153. context = context or self._context_getter
  154. decoration = InputHeadersControllerWrapper(
  155. context=context,
  156. processor=processor,
  157. error_http_code=error_http_code,
  158. default_http_code=default_http_code,
  159. )
  160. def decorator(func):
  161. self._buffer.input_headers = InputHeadersDescription(decoration)
  162. return decoration.get_wrapper(func)
  163. return decorator
  164. def input_path(
  165. self,
  166. schema: typing.Any,
  167. processor: ProcessorInterface = None,
  168. context: ContextInterface = None,
  169. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  170. default_http_code: HTTPStatus = HTTPStatus.OK,
  171. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  172. processor = processor or MarshmallowInputProcessor()
  173. processor.schema = schema
  174. context = context or self._context_getter
  175. decoration = InputPathControllerWrapper(
  176. context=context,
  177. processor=processor,
  178. error_http_code=error_http_code,
  179. default_http_code=default_http_code,
  180. )
  181. def decorator(func):
  182. self._buffer.input_path = InputPathDescription(decoration)
  183. return decoration.get_wrapper(func)
  184. return decorator
  185. def input_query(
  186. self,
  187. schema: typing.Any,
  188. processor: ProcessorInterface = None,
  189. context: ContextInterface = None,
  190. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  191. default_http_code: HTTPStatus = HTTPStatus.OK,
  192. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  193. processor = processor or MarshmallowInputProcessor()
  194. processor.schema = schema
  195. context = context or self._context_getter
  196. decoration = InputQueryControllerWrapper(
  197. context=context,
  198. processor=processor,
  199. error_http_code=error_http_code,
  200. default_http_code=default_http_code,
  201. )
  202. def decorator(func):
  203. self._buffer.input_query = InputQueryDescription(decoration)
  204. return decoration.get_wrapper(func)
  205. return decorator
  206. def input_body(
  207. self,
  208. schema: typing.Any,
  209. processor: ProcessorInterface = None,
  210. context: ContextInterface = None,
  211. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  212. default_http_code: HTTPStatus = HTTPStatus.OK,
  213. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  214. processor = processor or MarshmallowInputProcessor()
  215. processor.schema = schema
  216. context = context or self._context_getter
  217. decoration = InputBodyControllerWrapper(
  218. context=context,
  219. processor=processor,
  220. error_http_code=error_http_code,
  221. default_http_code=default_http_code,
  222. )
  223. def decorator(func):
  224. self._buffer.input_body = InputBodyDescription(decoration)
  225. return decoration.get_wrapper(func)
  226. return decorator
  227. def input_forms(
  228. self,
  229. schema: typing.Any,
  230. processor: ProcessorInterface=None,
  231. context: ContextInterface=None,
  232. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  233. default_http_code: HTTPStatus = HTTPStatus.OK,
  234. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  235. processor = processor or MarshmallowInputProcessor()
  236. processor.schema = schema
  237. context = context or self._context_getter
  238. decoration = InputBodyControllerWrapper(
  239. context=context,
  240. processor=processor,
  241. error_http_code=error_http_code,
  242. default_http_code=default_http_code,
  243. )
  244. def decorator(func):
  245. self._buffer.input_forms = InputFormsDescription(decoration)
  246. return decoration.get_wrapper(func)
  247. return decorator
  248. def input_files(
  249. self,
  250. schema: typing.Any,
  251. processor: ProcessorInterface=None,
  252. context: ContextInterface=None,
  253. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  254. default_http_code: HTTPStatus = HTTPStatus.OK,
  255. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  256. processor = processor or MarshmallowInputFilesProcessor()
  257. processor.schema = schema
  258. context = context or self._context_getter
  259. decoration = InputFilesControllerWrapper(
  260. context=context,
  261. processor=processor,
  262. error_http_code=error_http_code,
  263. default_http_code=default_http_code,
  264. )
  265. def decorator(func):
  266. self._buffer.input_files = InputFilesDescription(decoration)
  267. return decoration.get_wrapper(func)
  268. return decorator
  269. def handle_exception(
  270. self,
  271. handled_exception_class: typing.Type[Exception],
  272. http_code: HTTPStatus = HTTPStatus.INTERNAL_SERVER_ERROR,
  273. context: ContextInterface = None,
  274. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  275. context = context or self._context_getter
  276. decoration = ExceptionHandlerControllerWrapper(
  277. handled_exception_class,
  278. context,
  279. # TODO BS 20171013: Permit schema overriding, see #15
  280. schema=_default_global_error_schema,
  281. http_code=http_code,
  282. )
  283. def decorator(func):
  284. self._buffer.errors.append(ErrorDescription(decoration))
  285. return decoration.get_wrapper(func)
  286. return decorator
  287. def generate_doc(self, app):
  288. # FIXME: j'ai du tricher avec app, see #11
  289. # FIXME @Damien bottle specific code ! see #11
  290. # rendre ca generique
  291. app = app or self._context.get_app()
  292. doc_generator = DocGenerator()
  293. return doc_generator.get_doc(self._controllers, app)