hapic.py 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. # -*- coding: utf-8 -*-
  2. import typing
  3. import uuid
  4. try: # Python 3.5+
  5. from http import HTTPStatus
  6. except ImportError:
  7. from http import client as HTTPStatus
  8. import functools
  9. import marshmallow
  10. from hapic.buffer import DecorationBuffer
  11. from hapic.context import ContextInterface
  12. from hapic.decorator import DecoratedController
  13. from hapic.decorator import DECORATION_ATTRIBUTE_NAME
  14. from hapic.decorator import ControllerReference
  15. from hapic.decorator import ExceptionHandlerControllerWrapper
  16. from hapic.decorator import InputBodyControllerWrapper
  17. from hapic.decorator import InputHeadersControllerWrapper
  18. from hapic.decorator import InputPathControllerWrapper
  19. from hapic.decorator import InputQueryControllerWrapper
  20. from hapic.decorator import InputFilesControllerWrapper
  21. from hapic.decorator import OutputBodyControllerWrapper
  22. from hapic.decorator import OutputHeadersControllerWrapper
  23. from hapic.decorator import OutputFileControllerWrapper
  24. from hapic.description import InputBodyDescription
  25. from hapic.description import ErrorDescription
  26. from hapic.description import InputFormsDescription
  27. from hapic.description import InputHeadersDescription
  28. from hapic.description import InputPathDescription
  29. from hapic.description import InputQueryDescription
  30. from hapic.description import InputFilesDescription
  31. from hapic.description import OutputBodyDescription
  32. from hapic.description import OutputHeadersDescription
  33. from hapic.description import OutputFileDescription
  34. from hapic.doc import DocGenerator
  35. from hapic.processor import ProcessorInterface
  36. from hapic.processor import MarshmallowInputProcessor
  37. from hapic.processor import MarshmallowInputFilesProcessor
  38. from hapic.processor import MarshmallowOutputProcessor
  39. class ErrorResponseSchema(marshmallow.Schema):
  40. message = marshmallow.fields.String(required=True)
  41. details = marshmallow.fields.Dict(required=False, missing={})
  42. code = marshmallow.fields.Raw(missing=None)
  43. _default_global_error_schema = ErrorResponseSchema()
  44. # TODO: Gérer les cas ou c'est une liste la réponse (items, item_nb), see #12
  45. # TODO: Confusion nommage body/json/forms, see #13
  46. class Hapic(object):
  47. def __init__(self):
  48. self._buffer = DecorationBuffer()
  49. self._controllers = [] # type: typing.List[DecoratedController]
  50. self._context = None # type: ContextInterface
  51. self.doc_generator = DocGenerator()
  52. # This local function will be pass to different components
  53. # who will need context but declared (like with decorator)
  54. # before context declaration
  55. def context_getter():
  56. return self._context
  57. self._context_getter = context_getter
  58. # TODO: Permettre la surcharge des classes utilisés ci-dessous, see #14
  59. @property
  60. def controllers(self) -> typing.List[DecoratedController]:
  61. return self._controllers
  62. @property
  63. def context(self) -> ContextInterface:
  64. return self._context
  65. def set_context(self, context: ContextInterface) -> None:
  66. assert not self._context
  67. self._context = context
  68. def reset_context(self) -> None:
  69. self._context = None
  70. def with_api_doc(self, tags: typing.List['str']=None):
  71. """
  72. Permit to generate doc about a controller. Use as a decorator:
  73. ```
  74. @hapic.with_api_doc()
  75. def my_controller(self):
  76. # ...
  77. ```
  78. What it do: Register this controller with all previous given
  79. information like `@hapic.input_path(...)` etc.
  80. :param tags: list of string tags (OpenApi)
  81. :return: The decorator
  82. """
  83. # FIXME BS 20171228: Documenter sur ce que ça fait vraiment (tester:
  84. # on peut l'enlever si on veut pas generer la doc ?)
  85. tags = tags or [] # FDV
  86. def decorator(func):
  87. @functools.wraps(func)
  88. def wrapper(*args, **kwargs):
  89. return func(*args, **kwargs)
  90. token = uuid.uuid4().hex
  91. setattr(wrapper, DECORATION_ATTRIBUTE_NAME, token)
  92. setattr(func, DECORATION_ATTRIBUTE_NAME, token)
  93. description = self._buffer.get_description()
  94. description.tags = tags
  95. reference = ControllerReference(
  96. wrapper=wrapper,
  97. wrapped=func,
  98. token=token,
  99. )
  100. decorated_controller = DecoratedController(
  101. reference=reference,
  102. description=description,
  103. name=func.__name__,
  104. )
  105. self._buffer.clear()
  106. self._controllers.append(decorated_controller)
  107. return wrapper
  108. return decorator
  109. def output_body(
  110. self,
  111. schema: typing.Any,
  112. processor: ProcessorInterface = None,
  113. context: ContextInterface = None,
  114. error_http_code: HTTPStatus = HTTPStatus.INTERNAL_SERVER_ERROR,
  115. default_http_code: HTTPStatus = HTTPStatus.OK,
  116. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  117. processor = processor or MarshmallowOutputProcessor()
  118. processor.schema = schema
  119. context = context or self._context_getter
  120. decoration = OutputBodyControllerWrapper(
  121. context=context,
  122. processor=processor,
  123. error_http_code=error_http_code,
  124. default_http_code=default_http_code,
  125. )
  126. def decorator(func):
  127. self._buffer.output_body = OutputBodyDescription(decoration)
  128. return decoration.get_wrapper(func)
  129. return decorator
  130. def output_headers(
  131. self,
  132. schema: typing.Any,
  133. processor: ProcessorInterface = None,
  134. context: ContextInterface = None,
  135. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  136. default_http_code: HTTPStatus = HTTPStatus.OK,
  137. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  138. processor = processor or MarshmallowOutputProcessor()
  139. processor.schema = schema
  140. context = context or self._context_getter
  141. decoration = OutputHeadersControllerWrapper(
  142. context=context,
  143. processor=processor,
  144. error_http_code=error_http_code,
  145. default_http_code=default_http_code,
  146. )
  147. def decorator(func):
  148. self._buffer.output_headers = OutputHeadersDescription(decoration)
  149. return decoration.get_wrapper(func)
  150. return decorator
  151. # TODO BS 20171102: Think about possibilities to validate output ?
  152. # (with mime type, or validator)
  153. def output_file(
  154. self,
  155. output_types: typing.List[str],
  156. default_http_code: HTTPStatus = HTTPStatus.OK,
  157. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  158. decoration = OutputFileControllerWrapper(
  159. output_types=output_types,
  160. default_http_code=default_http_code,
  161. )
  162. def decorator(func):
  163. self._buffer.output_file = OutputFileDescription(decoration)
  164. return decoration.get_wrapper(func)
  165. return decorator
  166. def input_headers(
  167. self,
  168. schema: typing.Any,
  169. processor: ProcessorInterface = None,
  170. context: ContextInterface = None,
  171. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  172. default_http_code: HTTPStatus = HTTPStatus.OK,
  173. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  174. processor = processor or MarshmallowInputProcessor()
  175. processor.schema = schema
  176. context = context or self._context_getter
  177. decoration = InputHeadersControllerWrapper(
  178. context=context,
  179. processor=processor,
  180. error_http_code=error_http_code,
  181. default_http_code=default_http_code,
  182. )
  183. def decorator(func):
  184. self._buffer.input_headers = InputHeadersDescription(decoration)
  185. return decoration.get_wrapper(func)
  186. return decorator
  187. def input_path(
  188. self,
  189. schema: typing.Any,
  190. processor: ProcessorInterface = None,
  191. context: ContextInterface = None,
  192. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  193. default_http_code: HTTPStatus = HTTPStatus.OK,
  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 = InputPathControllerWrapper(
  199. context=context,
  200. processor=processor,
  201. error_http_code=error_http_code,
  202. default_http_code=default_http_code,
  203. )
  204. def decorator(func):
  205. self._buffer.input_path = InputPathDescription(decoration)
  206. return decoration.get_wrapper(func)
  207. return decorator
  208. def input_query(
  209. self,
  210. schema: typing.Any,
  211. processor: ProcessorInterface = None,
  212. context: ContextInterface = None,
  213. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  214. default_http_code: HTTPStatus = HTTPStatus.OK,
  215. as_list: typing.List[str]=None,
  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 = InputQueryControllerWrapper(
  221. context=context,
  222. processor=processor,
  223. error_http_code=error_http_code,
  224. default_http_code=default_http_code,
  225. as_list=as_list,
  226. )
  227. def decorator(func):
  228. self._buffer.input_query = InputQueryDescription(decoration)
  229. return decoration.get_wrapper(func)
  230. return decorator
  231. def input_body(
  232. self,
  233. schema: typing.Any,
  234. processor: ProcessorInterface = None,
  235. context: ContextInterface = None,
  236. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  237. default_http_code: HTTPStatus = HTTPStatus.OK,
  238. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  239. processor = processor or MarshmallowInputProcessor()
  240. processor.schema = schema
  241. context = context or self._context_getter
  242. decoration = InputBodyControllerWrapper(
  243. context=context,
  244. processor=processor,
  245. error_http_code=error_http_code,
  246. default_http_code=default_http_code,
  247. )
  248. def decorator(func):
  249. self._buffer.input_body = InputBodyDescription(decoration)
  250. return decoration.get_wrapper(func)
  251. return decorator
  252. def input_forms(
  253. self,
  254. schema: typing.Any,
  255. processor: ProcessorInterface=None,
  256. context: ContextInterface=None,
  257. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  258. default_http_code: HTTPStatus = HTTPStatus.OK,
  259. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  260. processor = processor or MarshmallowInputProcessor()
  261. processor.schema = schema
  262. context = context or self._context_getter
  263. decoration = InputBodyControllerWrapper(
  264. context=context,
  265. processor=processor,
  266. error_http_code=error_http_code,
  267. default_http_code=default_http_code,
  268. )
  269. def decorator(func):
  270. self._buffer.input_forms = InputFormsDescription(decoration)
  271. return decoration.get_wrapper(func)
  272. return decorator
  273. def input_files(
  274. self,
  275. schema: typing.Any,
  276. processor: ProcessorInterface=None,
  277. context: ContextInterface=None,
  278. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  279. default_http_code: HTTPStatus = HTTPStatus.OK,
  280. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  281. processor = processor or MarshmallowInputFilesProcessor()
  282. processor.schema = schema
  283. context = context or self._context_getter
  284. decoration = InputFilesControllerWrapper(
  285. context=context,
  286. processor=processor,
  287. error_http_code=error_http_code,
  288. default_http_code=default_http_code,
  289. )
  290. def decorator(func):
  291. self._buffer.input_files = InputFilesDescription(decoration)
  292. return decoration.get_wrapper(func)
  293. return decorator
  294. def handle_exception(
  295. self,
  296. handled_exception_class: typing.Type[Exception],
  297. http_code: HTTPStatus = HTTPStatus.INTERNAL_SERVER_ERROR,
  298. context: ContextInterface = None,
  299. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  300. context = context or self._context_getter
  301. decoration = ExceptionHandlerControllerWrapper(
  302. handled_exception_class,
  303. context,
  304. # TODO BS 20171013: Permit schema overriding, see #15
  305. schema=_default_global_error_schema,
  306. http_code=http_code,
  307. )
  308. def decorator(func):
  309. self._buffer.errors.append(ErrorDescription(decoration))
  310. return decoration.get_wrapper(func)
  311. return decorator
  312. def generate_doc(self, title: str='', description: str='') -> dict:
  313. """
  314. See hapic.doc.DocGenerator#get_doc docstring
  315. :param title: Title of generated doc
  316. :param description: Description of generated doc
  317. :return: dict containing apispec doc
  318. """
  319. return self.doc_generator.get_doc(
  320. self._controllers,
  321. self.context,
  322. title=title,
  323. description=description,
  324. )