hapic.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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):
  71. def decorator(func):
  72. @functools.wraps(func)
  73. def wrapper(*args, **kwargs):
  74. return func(*args, **kwargs)
  75. token = uuid.uuid4().hex
  76. setattr(wrapper, DECORATION_ATTRIBUTE_NAME, token)
  77. setattr(func, DECORATION_ATTRIBUTE_NAME, token)
  78. description = self._buffer.get_description()
  79. reference = ControllerReference(
  80. wrapper=wrapper,
  81. wrapped=func,
  82. token=token,
  83. )
  84. decorated_controller = DecoratedController(
  85. reference=reference,
  86. description=description,
  87. name=func.__name__,
  88. )
  89. self._buffer.clear()
  90. self._controllers.append(decorated_controller)
  91. return wrapper
  92. return decorator
  93. def output_body(
  94. self,
  95. schema: typing.Any,
  96. processor: ProcessorInterface = None,
  97. context: ContextInterface = None,
  98. error_http_code: HTTPStatus = HTTPStatus.INTERNAL_SERVER_ERROR,
  99. default_http_code: HTTPStatus = HTTPStatus.OK,
  100. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  101. processor = processor or MarshmallowOutputProcessor()
  102. processor.schema = schema
  103. context = context or self._context_getter
  104. decoration = OutputBodyControllerWrapper(
  105. context=context,
  106. processor=processor,
  107. error_http_code=error_http_code,
  108. default_http_code=default_http_code,
  109. )
  110. def decorator(func):
  111. self._buffer.output_body = OutputBodyDescription(decoration)
  112. return decoration.get_wrapper(func)
  113. return decorator
  114. def output_headers(
  115. self,
  116. schema: typing.Any,
  117. processor: ProcessorInterface = None,
  118. context: ContextInterface = None,
  119. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  120. default_http_code: HTTPStatus = HTTPStatus.OK,
  121. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  122. processor = processor or MarshmallowOutputProcessor()
  123. processor.schema = schema
  124. context = context or self._context_getter
  125. decoration = OutputHeadersControllerWrapper(
  126. context=context,
  127. processor=processor,
  128. error_http_code=error_http_code,
  129. default_http_code=default_http_code,
  130. )
  131. def decorator(func):
  132. self._buffer.output_headers = OutputHeadersDescription(decoration)
  133. return decoration.get_wrapper(func)
  134. return decorator
  135. # TODO BS 20171102: Think about possibilities to validate output ?
  136. # (with mime type, or validator)
  137. def output_file(
  138. self,
  139. output_types: typing.List[str],
  140. default_http_code: HTTPStatus = HTTPStatus.OK,
  141. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  142. decoration = OutputFileControllerWrapper(
  143. output_types=output_types,
  144. default_http_code=default_http_code,
  145. )
  146. def decorator(func):
  147. self._buffer.output_file = OutputFileDescription(decoration)
  148. return decoration.get_wrapper(func)
  149. return decorator
  150. def input_headers(
  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_getter
  161. decoration = InputHeadersControllerWrapper(
  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_headers = InputHeadersDescription(decoration)
  169. return decoration.get_wrapper(func)
  170. return decorator
  171. def input_path(
  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_getter
  182. decoration = InputPathControllerWrapper(
  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_path = InputPathDescription(decoration)
  190. return decoration.get_wrapper(func)
  191. return decorator
  192. def input_query(
  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. as_list: typing.List[str]=None,
  200. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  201. processor = processor or MarshmallowInputProcessor()
  202. processor.schema = schema
  203. context = context or self._context_getter
  204. decoration = InputQueryControllerWrapper(
  205. context=context,
  206. processor=processor,
  207. error_http_code=error_http_code,
  208. default_http_code=default_http_code,
  209. as_list=as_list,
  210. )
  211. def decorator(func):
  212. self._buffer.input_query = InputQueryDescription(decoration)
  213. return decoration.get_wrapper(func)
  214. return decorator
  215. def input_body(
  216. self,
  217. schema: typing.Any,
  218. processor: ProcessorInterface = None,
  219. context: ContextInterface = None,
  220. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  221. default_http_code: HTTPStatus = HTTPStatus.OK,
  222. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  223. processor = processor or MarshmallowInputProcessor()
  224. processor.schema = schema
  225. context = context or self._context_getter
  226. decoration = InputBodyControllerWrapper(
  227. context=context,
  228. processor=processor,
  229. error_http_code=error_http_code,
  230. default_http_code=default_http_code,
  231. )
  232. def decorator(func):
  233. self._buffer.input_body = InputBodyDescription(decoration)
  234. return decoration.get_wrapper(func)
  235. return decorator
  236. def input_forms(
  237. self,
  238. schema: typing.Any,
  239. processor: ProcessorInterface=None,
  240. context: ContextInterface=None,
  241. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  242. default_http_code: HTTPStatus = HTTPStatus.OK,
  243. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  244. processor = processor or MarshmallowInputProcessor()
  245. processor.schema = schema
  246. context = context or self._context_getter
  247. decoration = InputBodyControllerWrapper(
  248. context=context,
  249. processor=processor,
  250. error_http_code=error_http_code,
  251. default_http_code=default_http_code,
  252. )
  253. def decorator(func):
  254. self._buffer.input_forms = InputFormsDescription(decoration)
  255. return decoration.get_wrapper(func)
  256. return decorator
  257. def input_files(
  258. self,
  259. schema: typing.Any,
  260. processor: ProcessorInterface=None,
  261. context: ContextInterface=None,
  262. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  263. default_http_code: HTTPStatus = HTTPStatus.OK,
  264. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  265. processor = processor or MarshmallowInputFilesProcessor()
  266. processor.schema = schema
  267. context = context or self._context_getter
  268. decoration = InputFilesControllerWrapper(
  269. context=context,
  270. processor=processor,
  271. error_http_code=error_http_code,
  272. default_http_code=default_http_code,
  273. )
  274. def decorator(func):
  275. self._buffer.input_files = InputFilesDescription(decoration)
  276. return decoration.get_wrapper(func)
  277. return decorator
  278. def handle_exception(
  279. self,
  280. handled_exception_class: typing.Type[Exception],
  281. http_code: HTTPStatus = HTTPStatus.INTERNAL_SERVER_ERROR,
  282. context: ContextInterface = None,
  283. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  284. context = context or self._context_getter
  285. decoration = ExceptionHandlerControllerWrapper(
  286. handled_exception_class,
  287. context,
  288. # TODO BS 20171013: Permit schema overriding, see #15
  289. schema=_default_global_error_schema,
  290. http_code=http_code,
  291. )
  292. def decorator(func):
  293. self._buffer.errors.append(ErrorDescription(decoration))
  294. return decoration.get_wrapper(func)
  295. return decorator
  296. def generate_doc(self, title: str='', description: str=''):
  297. return self.doc_generator.get_doc(
  298. self._controllers,
  299. self.context,
  300. title=title,
  301. description=description)