hapic.py 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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 ?
  130. # (with mime type, or validator)
  131. def output_file(
  132. self,
  133. output_types: typing.List[str],
  134. default_http_code: HTTPStatus = HTTPStatus.OK,
  135. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  136. decoration = OutputFileControllerWrapper(
  137. output_types=output_types,
  138. default_http_code=default_http_code,
  139. )
  140. def decorator(func):
  141. self._buffer.output_file = OutputFileDescription(decoration)
  142. return decoration.get_wrapper(func)
  143. return decorator
  144. def input_headers(
  145. self,
  146. schema: typing.Any,
  147. processor: ProcessorInterface = None,
  148. context: ContextInterface = None,
  149. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  150. default_http_code: HTTPStatus = HTTPStatus.OK,
  151. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  152. processor = processor or MarshmallowInputProcessor()
  153. processor.schema = schema
  154. context = context or self._context_getter
  155. decoration = InputHeadersControllerWrapper(
  156. context=context,
  157. processor=processor,
  158. error_http_code=error_http_code,
  159. default_http_code=default_http_code,
  160. )
  161. def decorator(func):
  162. self._buffer.input_headers = InputHeadersDescription(decoration)
  163. return decoration.get_wrapper(func)
  164. return decorator
  165. def input_path(
  166. self,
  167. schema: typing.Any,
  168. processor: ProcessorInterface = None,
  169. context: ContextInterface = None,
  170. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  171. default_http_code: HTTPStatus = HTTPStatus.OK,
  172. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  173. processor = processor or MarshmallowInputProcessor()
  174. processor.schema = schema
  175. context = context or self._context_getter
  176. decoration = InputPathControllerWrapper(
  177. context=context,
  178. processor=processor,
  179. error_http_code=error_http_code,
  180. default_http_code=default_http_code,
  181. )
  182. def decorator(func):
  183. self._buffer.input_path = InputPathDescription(decoration)
  184. return decoration.get_wrapper(func)
  185. return decorator
  186. def input_query(
  187. self,
  188. schema: typing.Any,
  189. processor: ProcessorInterface = None,
  190. context: ContextInterface = None,
  191. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  192. default_http_code: HTTPStatus = HTTPStatus.OK,
  193. as_list: typing.List[str]=None,
  194. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  195. processor = processor or MarshmallowInputProcessor()
  196. processor.schema = schema
  197. context = context or self._context_getter
  198. decoration = InputQueryControllerWrapper(
  199. context=context,
  200. processor=processor,
  201. error_http_code=error_http_code,
  202. default_http_code=default_http_code,
  203. as_list=as_list,
  204. )
  205. def decorator(func):
  206. self._buffer.input_query = InputQueryDescription(decoration)
  207. return decoration.get_wrapper(func)
  208. return decorator
  209. def input_body(
  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_body = InputBodyDescription(decoration)
  228. return decoration.get_wrapper(func)
  229. return decorator
  230. def input_forms(
  231. self,
  232. schema: typing.Any,
  233. processor: ProcessorInterface=None,
  234. context: ContextInterface=None,
  235. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  236. default_http_code: HTTPStatus = HTTPStatus.OK,
  237. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  238. processor = processor or MarshmallowInputProcessor()
  239. processor.schema = schema
  240. context = context or self._context_getter
  241. decoration = InputBodyControllerWrapper(
  242. context=context,
  243. processor=processor,
  244. error_http_code=error_http_code,
  245. default_http_code=default_http_code,
  246. )
  247. def decorator(func):
  248. self._buffer.input_forms = InputFormsDescription(decoration)
  249. return decoration.get_wrapper(func)
  250. return decorator
  251. def input_files(
  252. self,
  253. schema: typing.Any,
  254. processor: ProcessorInterface=None,
  255. context: ContextInterface=None,
  256. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  257. default_http_code: HTTPStatus = HTTPStatus.OK,
  258. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  259. processor = processor or MarshmallowInputFilesProcessor()
  260. processor.schema = schema
  261. context = context or self._context_getter
  262. decoration = InputFilesControllerWrapper(
  263. context=context,
  264. processor=processor,
  265. error_http_code=error_http_code,
  266. default_http_code=default_http_code,
  267. )
  268. def decorator(func):
  269. self._buffer.input_files = InputFilesDescription(decoration)
  270. return decoration.get_wrapper(func)
  271. return decorator
  272. def handle_exception(
  273. self,
  274. handled_exception_class: typing.Type[Exception],
  275. http_code: HTTPStatus = HTTPStatus.INTERNAL_SERVER_ERROR,
  276. context: ContextInterface = None,
  277. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  278. context = context or self._context_getter
  279. decoration = ExceptionHandlerControllerWrapper(
  280. handled_exception_class,
  281. context,
  282. # TODO BS 20171013: Permit schema overriding, see #15
  283. schema=_default_global_error_schema,
  284. http_code=http_code,
  285. )
  286. def decorator(func):
  287. self._buffer.errors.append(ErrorDescription(decoration))
  288. return decoration.get_wrapper(func)
  289. return decorator
  290. def generate_doc(self, app, title: str='', description: str=''):
  291. # FIXME: j'ai du tricher avec app, see #11
  292. # FIXME @Damien bottle specific code ! see #11
  293. # rendre ca generique
  294. app = app or self._context.get_app()
  295. doc_generator = DocGenerator()
  296. return doc_generator.get_doc(
  297. self._controllers,
  298. app,
  299. title=title,
  300. description=description,
  301. )