hapic.py 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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 set_context(self, context: ContextInterface) -> None:
  62. assert not self._context
  63. self._context = context
  64. def reset_context(self) -> None:
  65. self._context = None
  66. def with_api_doc(self):
  67. def decorator(func):
  68. @functools.wraps(func)
  69. def wrapper(*args, **kwargs):
  70. return func(*args, **kwargs)
  71. token = uuid.uuid4().hex
  72. setattr(wrapper, DECORATION_ATTRIBUTE_NAME, token)
  73. setattr(func, DECORATION_ATTRIBUTE_NAME, token)
  74. description = self._buffer.get_description()
  75. reference = ControllerReference(
  76. wrapper=wrapper,
  77. wrapped=func,
  78. token=token,
  79. )
  80. decorated_controller = DecoratedController(
  81. reference=reference,
  82. description=description,
  83. name=func.__name__,
  84. )
  85. self._buffer.clear()
  86. self._controllers.append(decorated_controller)
  87. return wrapper
  88. return decorator
  89. def output_body(
  90. self,
  91. schema: typing.Any,
  92. processor: ProcessorInterface = None,
  93. context: ContextInterface = None,
  94. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  95. default_http_code: HTTPStatus = HTTPStatus.OK,
  96. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  97. processor = processor or MarshmallowOutputProcessor()
  98. processor.schema = schema
  99. context = context or self._context_getter
  100. decoration = OutputBodyControllerWrapper(
  101. context=context,
  102. processor=processor,
  103. error_http_code=error_http_code,
  104. default_http_code=default_http_code,
  105. )
  106. def decorator(func):
  107. self._buffer.output_body = OutputBodyDescription(decoration)
  108. return decoration.get_wrapper(func)
  109. return decorator
  110. def output_headers(
  111. self,
  112. schema: typing.Any,
  113. processor: ProcessorInterface = None,
  114. context: ContextInterface = None,
  115. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  116. default_http_code: HTTPStatus = HTTPStatus.OK,
  117. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  118. processor = processor or MarshmallowOutputProcessor()
  119. processor.schema = schema
  120. context = context or self._context_getter
  121. decoration = OutputHeadersControllerWrapper(
  122. context=context,
  123. processor=processor,
  124. error_http_code=error_http_code,
  125. default_http_code=default_http_code,
  126. )
  127. def decorator(func):
  128. self._buffer.output_headers = OutputHeadersDescription(decoration)
  129. return decoration.get_wrapper(func)
  130. return decorator
  131. # TODO BS 20171102: Think about possibilities to validate output ?
  132. # (with mime type, or validator)
  133. def output_file(
  134. self,
  135. output_types: typing.List[str],
  136. default_http_code: HTTPStatus = HTTPStatus.OK,
  137. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  138. decoration = OutputFileControllerWrapper(
  139. output_types=output_types,
  140. default_http_code=default_http_code,
  141. )
  142. def decorator(func):
  143. self._buffer.output_file = OutputFileDescription(decoration)
  144. return decoration.get_wrapper(func)
  145. return decorator
  146. def input_headers(
  147. self,
  148. schema: typing.Any,
  149. processor: ProcessorInterface = None,
  150. context: ContextInterface = None,
  151. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  152. default_http_code: HTTPStatus = HTTPStatus.OK,
  153. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  154. processor = processor or MarshmallowInputProcessor()
  155. processor.schema = schema
  156. context = context or self._context_getter
  157. decoration = InputHeadersControllerWrapper(
  158. context=context,
  159. processor=processor,
  160. error_http_code=error_http_code,
  161. default_http_code=default_http_code,
  162. )
  163. def decorator(func):
  164. self._buffer.input_headers = InputHeadersDescription(decoration)
  165. return decoration.get_wrapper(func)
  166. return decorator
  167. def input_path(
  168. self,
  169. schema: typing.Any,
  170. processor: ProcessorInterface = None,
  171. context: ContextInterface = None,
  172. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  173. default_http_code: HTTPStatus = HTTPStatus.OK,
  174. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  175. processor = processor or MarshmallowInputProcessor()
  176. processor.schema = schema
  177. context = context or self._context_getter
  178. decoration = InputPathControllerWrapper(
  179. context=context,
  180. processor=processor,
  181. error_http_code=error_http_code,
  182. default_http_code=default_http_code,
  183. )
  184. def decorator(func):
  185. self._buffer.input_path = InputPathDescription(decoration)
  186. return decoration.get_wrapper(func)
  187. return decorator
  188. def input_query(
  189. self,
  190. schema: typing.Any,
  191. processor: ProcessorInterface = None,
  192. context: ContextInterface = None,
  193. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  194. default_http_code: HTTPStatus = HTTPStatus.OK,
  195. as_list: typing.List[str]=None,
  196. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  197. processor = processor or MarshmallowInputProcessor()
  198. processor.schema = schema
  199. context = context or self._context_getter
  200. decoration = InputQueryControllerWrapper(
  201. context=context,
  202. processor=processor,
  203. error_http_code=error_http_code,
  204. default_http_code=default_http_code,
  205. as_list=as_list,
  206. )
  207. def decorator(func):
  208. self._buffer.input_query = InputQueryDescription(decoration)
  209. return decoration.get_wrapper(func)
  210. return decorator
  211. def input_body(
  212. self,
  213. schema: typing.Any,
  214. processor: ProcessorInterface = None,
  215. context: ContextInterface = None,
  216. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  217. default_http_code: HTTPStatus = HTTPStatus.OK,
  218. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  219. processor = processor or MarshmallowInputProcessor()
  220. processor.schema = schema
  221. context = context or self._context_getter
  222. decoration = InputBodyControllerWrapper(
  223. context=context,
  224. processor=processor,
  225. error_http_code=error_http_code,
  226. default_http_code=default_http_code,
  227. )
  228. def decorator(func):
  229. self._buffer.input_body = InputBodyDescription(decoration)
  230. return decoration.get_wrapper(func)
  231. return decorator
  232. def input_forms(
  233. self,
  234. schema: typing.Any,
  235. processor: ProcessorInterface=None,
  236. context: ContextInterface=None,
  237. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  238. default_http_code: HTTPStatus = HTTPStatus.OK,
  239. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  240. processor = processor or MarshmallowInputProcessor()
  241. processor.schema = schema
  242. context = context or self._context_getter
  243. decoration = InputBodyControllerWrapper(
  244. context=context,
  245. processor=processor,
  246. error_http_code=error_http_code,
  247. default_http_code=default_http_code,
  248. )
  249. def decorator(func):
  250. self._buffer.input_forms = InputFormsDescription(decoration)
  251. return decoration.get_wrapper(func)
  252. return decorator
  253. def input_files(
  254. self,
  255. schema: typing.Any,
  256. processor: ProcessorInterface=None,
  257. context: ContextInterface=None,
  258. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  259. default_http_code: HTTPStatus = HTTPStatus.OK,
  260. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  261. processor = processor or MarshmallowInputFilesProcessor()
  262. processor.schema = schema
  263. context = context or self._context_getter
  264. decoration = InputFilesControllerWrapper(
  265. context=context,
  266. processor=processor,
  267. error_http_code=error_http_code,
  268. default_http_code=default_http_code,
  269. )
  270. def decorator(func):
  271. self._buffer.input_files = InputFilesDescription(decoration)
  272. return decoration.get_wrapper(func)
  273. return decorator
  274. def handle_exception(
  275. self,
  276. handled_exception_class: typing.Type[Exception],
  277. http_code: HTTPStatus = HTTPStatus.INTERNAL_SERVER_ERROR,
  278. context: ContextInterface = None,
  279. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  280. context = context or self._context_getter
  281. decoration = ExceptionHandlerControllerWrapper(
  282. handled_exception_class,
  283. context,
  284. # TODO BS 20171013: Permit schema overriding, see #15
  285. schema=_default_global_error_schema,
  286. http_code=http_code,
  287. )
  288. def decorator(func):
  289. self._buffer.errors.append(ErrorDescription(decoration))
  290. return decoration.get_wrapper(func)
  291. return decorator
  292. def generate_doc(self, app, title: str='', description: str=''):
  293. # FIXME: j'ai du tricher avec app, see #11
  294. # FIXME @Damien bottle specific code ! see #11
  295. # rendre ca generique
  296. app = app or self._context.get_app()
  297. doc_generator = DocGenerator()
  298. return doc_generator.get_doc(
  299. self._controllers,
  300. app,
  301. title=title,
  302. description=description,
  303. )