hapic.py 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. # -*- coding: utf-8 -*-
  2. import os
  3. import typing
  4. import uuid
  5. import functools
  6. try: # Python 3.5+
  7. from http import HTTPStatus
  8. except ImportError:
  9. from http import client as HTTPStatus
  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 AsyncInputBodyControllerWrapper
  18. from hapic.decorator import InputHeadersControllerWrapper
  19. from hapic.decorator import InputPathControllerWrapper
  20. from hapic.decorator import InputQueryControllerWrapper
  21. from hapic.decorator import InputFilesControllerWrapper
  22. from hapic.decorator import OutputBodyControllerWrapper
  23. from hapic.decorator import AsyncOutputBodyControllerWrapper
  24. from hapic.decorator import AsyncOutputStreamControllerWrapper
  25. from hapic.decorator import OutputHeadersControllerWrapper
  26. from hapic.decorator import OutputFileControllerWrapper
  27. from hapic.description import InputBodyDescription
  28. from hapic.description import ErrorDescription
  29. from hapic.description import InputFormsDescription
  30. from hapic.description import InputHeadersDescription
  31. from hapic.description import InputPathDescription
  32. from hapic.description import InputQueryDescription
  33. from hapic.description import InputFilesDescription
  34. from hapic.description import OutputBodyDescription
  35. from hapic.description import OutputStreamDescription
  36. from hapic.description import OutputHeadersDescription
  37. from hapic.description import OutputFileDescription
  38. from hapic.doc import DocGenerator
  39. from hapic.processor import ProcessorInterface
  40. from hapic.processor import MarshmallowInputProcessor
  41. from hapic.processor import MarshmallowInputFilesProcessor
  42. from hapic.processor import MarshmallowOutputProcessor
  43. from hapic.error import ErrorBuilderInterface
  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__(
  48. self,
  49. async_: bool = False,
  50. ):
  51. self._buffer = DecorationBuffer()
  52. self._controllers = [] # type: typing.List[DecoratedController]
  53. self._context = None # type: ContextInterface
  54. self._error_builder = None # type: ErrorBuilderInterface
  55. self._async = async_
  56. self.doc_generator = DocGenerator()
  57. # This local function will be pass to different components
  58. # who will need context but declared (like with decorator)
  59. # before context declaration
  60. def context_getter():
  61. return self._context
  62. # This local function will be pass to different components
  63. # who will need error_builder but declared (like with decorator)
  64. # before error_builder declaration
  65. def error_builder_getter():
  66. return self._context.get_default_error_builder()
  67. self._context_getter = context_getter
  68. self._error_builder_getter = error_builder_getter
  69. # TODO: Permettre la surcharge des classes utilisés ci-dessous, see #14
  70. @property
  71. def controllers(self) -> typing.List[DecoratedController]:
  72. return self._controllers
  73. @property
  74. def context(self) -> ContextInterface:
  75. return self._context
  76. def set_context(self, context: ContextInterface) -> None:
  77. assert not self._context
  78. self._context = context
  79. def reset_context(self) -> None:
  80. self._context = None
  81. def with_api_doc(self, tags: typing.List['str']=None):
  82. """
  83. Permit to generate doc about a controller. Use as a decorator:
  84. ```
  85. @hapic.with_api_doc()
  86. def my_controller(self):
  87. # ...
  88. ```
  89. What it do: Register this controller with all previous given
  90. information like `@hapic.input_path(...)` etc.
  91. :param tags: list of string tags (OpenApi)
  92. :return: The decorator
  93. """
  94. # FIXME BS 20171228: Documenter sur ce que ça fait vraiment (tester:
  95. # on peut l'enlever si on veut pas generer la doc ?)
  96. tags = tags or [] # FDV
  97. def decorator(func):
  98. @functools.wraps(func)
  99. def wrapper(*args, **kwargs):
  100. return func(*args, **kwargs)
  101. token = uuid.uuid4().hex
  102. setattr(wrapper, DECORATION_ATTRIBUTE_NAME, token)
  103. setattr(func, DECORATION_ATTRIBUTE_NAME, token)
  104. description = self._buffer.get_description()
  105. description.tags = tags
  106. reference = ControllerReference(
  107. wrapper=wrapper,
  108. wrapped=func,
  109. token=token,
  110. )
  111. decorated_controller = DecoratedController(
  112. reference=reference,
  113. description=description,
  114. name=func.__name__,
  115. )
  116. self._buffer.clear()
  117. self._controllers.append(decorated_controller)
  118. return wrapper
  119. return decorator
  120. def output_body(
  121. self,
  122. schema: typing.Any,
  123. processor: ProcessorInterface = None,
  124. context: ContextInterface = None,
  125. error_http_code: HTTPStatus = HTTPStatus.INTERNAL_SERVER_ERROR,
  126. default_http_code: HTTPStatus = HTTPStatus.OK,
  127. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  128. processor = processor or MarshmallowOutputProcessor()
  129. processor.schema = schema
  130. context = context or self._context_getter
  131. if self._async:
  132. decoration = AsyncOutputBodyControllerWrapper(
  133. context=context,
  134. processor=processor,
  135. error_http_code=error_http_code,
  136. default_http_code=default_http_code,
  137. )
  138. else:
  139. decoration = OutputBodyControllerWrapper(
  140. context=context,
  141. processor=processor,
  142. error_http_code=error_http_code,
  143. default_http_code=default_http_code,
  144. )
  145. def decorator(func):
  146. self._buffer.output_body = OutputBodyDescription(decoration)
  147. return decoration.get_wrapper(func)
  148. return decorator
  149. def output_stream(
  150. self,
  151. item_schema: typing.Any,
  152. processor: ProcessorInterface = None,
  153. context: ContextInterface = None,
  154. error_http_code: HTTPStatus = HTTPStatus.INTERNAL_SERVER_ERROR,
  155. default_http_code: HTTPStatus = HTTPStatus.OK,
  156. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  157. """
  158. Decorate with a wrapper who check and serialize each items in output
  159. stream.
  160. :param item_schema: Schema of output stream items
  161. :param processor: ProcessorInterface object to process with given
  162. schema
  163. :param context: Context to use here
  164. :param error_http_code: http code in case of error
  165. :param default_http_code: http code in case of success
  166. :return: decorator
  167. """
  168. processor = processor or MarshmallowOutputProcessor()
  169. processor.schema = item_schema
  170. context = context or self._context_getter
  171. if self._async:
  172. decoration = AsyncOutputStreamControllerWrapper(
  173. context=context,
  174. processor=processor,
  175. error_http_code=error_http_code,
  176. default_http_code=default_http_code,
  177. )
  178. else:
  179. # TODO BS 2018-07-25: To do
  180. raise NotImplementedError('todo')
  181. def decorator(func):
  182. self._buffer.output_stream = OutputStreamDescription(decoration)
  183. return decoration.get_wrapper(func)
  184. return decorator
  185. def output_headers(
  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 MarshmallowOutputProcessor()
  194. processor.schema = schema
  195. context = context or self._context_getter
  196. decoration = OutputHeadersControllerWrapper(
  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.output_headers = OutputHeadersDescription(decoration)
  204. return decoration.get_wrapper(func)
  205. return decorator
  206. # TODO BS 20171102: Think about possibilities to validate output ?
  207. # (with mime type, or validator)
  208. def output_file(
  209. self,
  210. output_types: typing.List[str],
  211. default_http_code: HTTPStatus = HTTPStatus.OK,
  212. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  213. decoration = OutputFileControllerWrapper(
  214. output_types=output_types,
  215. default_http_code=default_http_code,
  216. )
  217. def decorator(func):
  218. self._buffer.output_file = OutputFileDescription(decoration)
  219. return decoration.get_wrapper(func)
  220. return decorator
  221. def input_headers(
  222. self,
  223. schema: typing.Any,
  224. processor: ProcessorInterface = None,
  225. context: ContextInterface = None,
  226. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  227. default_http_code: HTTPStatus = HTTPStatus.OK,
  228. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  229. processor = processor or MarshmallowInputProcessor()
  230. processor.schema = schema
  231. context = context or self._context_getter
  232. decoration = InputHeadersControllerWrapper(
  233. context=context,
  234. processor=processor,
  235. error_http_code=error_http_code,
  236. default_http_code=default_http_code,
  237. )
  238. def decorator(func):
  239. self._buffer.input_headers = InputHeadersDescription(decoration)
  240. return decoration.get_wrapper(func)
  241. return decorator
  242. def input_path(
  243. self,
  244. schema: typing.Any,
  245. processor: ProcessorInterface = None,
  246. context: ContextInterface = None,
  247. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  248. default_http_code: HTTPStatus = HTTPStatus.OK,
  249. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  250. processor = processor or MarshmallowInputProcessor()
  251. processor.schema = schema
  252. context = context or self._context_getter
  253. decoration = InputPathControllerWrapper(
  254. context=context,
  255. processor=processor,
  256. error_http_code=error_http_code,
  257. default_http_code=default_http_code,
  258. )
  259. def decorator(func):
  260. self._buffer.input_path = InputPathDescription(decoration)
  261. return decoration.get_wrapper(func)
  262. return decorator
  263. def input_query(
  264. self,
  265. schema: typing.Any,
  266. processor: ProcessorInterface = None,
  267. context: ContextInterface = None,
  268. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  269. default_http_code: HTTPStatus = HTTPStatus.OK,
  270. as_list: typing.List[str]=None,
  271. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  272. processor = processor or MarshmallowInputProcessor()
  273. processor.schema = schema
  274. context = context or self._context_getter
  275. decoration = InputQueryControllerWrapper(
  276. context=context,
  277. processor=processor,
  278. error_http_code=error_http_code,
  279. default_http_code=default_http_code,
  280. as_list=as_list,
  281. )
  282. def decorator(func):
  283. self._buffer.input_query = InputQueryDescription(decoration)
  284. return decoration.get_wrapper(func)
  285. return decorator
  286. def input_body(
  287. self,
  288. schema: typing.Any,
  289. processor: ProcessorInterface = None,
  290. context: ContextInterface = None,
  291. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  292. default_http_code: HTTPStatus = HTTPStatus.OK,
  293. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  294. processor = processor or MarshmallowInputProcessor()
  295. processor.schema = schema
  296. context = context or self._context_getter
  297. if self._async:
  298. decoration = AsyncInputBodyControllerWrapper(
  299. context=context,
  300. processor=processor,
  301. error_http_code=error_http_code,
  302. default_http_code=default_http_code,
  303. )
  304. else:
  305. decoration = InputBodyControllerWrapper(
  306. context=context,
  307. processor=processor,
  308. error_http_code=error_http_code,
  309. default_http_code=default_http_code,
  310. )
  311. def decorator(func):
  312. self._buffer.input_body = InputBodyDescription(decoration)
  313. return decoration.get_wrapper(func)
  314. return decorator
  315. def input_forms(
  316. self,
  317. schema: typing.Any,
  318. processor: ProcessorInterface=None,
  319. context: ContextInterface=None,
  320. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  321. default_http_code: HTTPStatus = HTTPStatus.OK,
  322. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  323. processor = processor or MarshmallowInputProcessor()
  324. processor.schema = schema
  325. context = context or self._context_getter
  326. decoration = InputBodyControllerWrapper(
  327. context=context,
  328. processor=processor,
  329. error_http_code=error_http_code,
  330. default_http_code=default_http_code,
  331. )
  332. def decorator(func):
  333. self._buffer.input_forms = InputFormsDescription(decoration)
  334. return decoration.get_wrapper(func)
  335. return decorator
  336. def input_files(
  337. self,
  338. schema: typing.Any,
  339. processor: ProcessorInterface=None,
  340. context: ContextInterface=None,
  341. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  342. default_http_code: HTTPStatus = HTTPStatus.OK,
  343. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  344. processor = processor or MarshmallowInputFilesProcessor()
  345. processor.schema = schema
  346. context = context or self._context_getter
  347. decoration = InputFilesControllerWrapper(
  348. context=context,
  349. processor=processor,
  350. error_http_code=error_http_code,
  351. default_http_code=default_http_code,
  352. )
  353. def decorator(func):
  354. self._buffer.input_files = InputFilesDescription(decoration)
  355. return decoration.get_wrapper(func)
  356. return decorator
  357. def handle_exception(
  358. self,
  359. handled_exception_class: typing.Type[Exception]=Exception,
  360. http_code: HTTPStatus = HTTPStatus.INTERNAL_SERVER_ERROR,
  361. error_builder: ErrorBuilderInterface=None,
  362. context: ContextInterface = None,
  363. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  364. context = context or self._context_getter
  365. error_builder = error_builder or self._error_builder_getter
  366. decoration = ExceptionHandlerControllerWrapper(
  367. handled_exception_class,
  368. context,
  369. error_builder=error_builder,
  370. http_code=http_code,
  371. )
  372. def decorator(func):
  373. self._buffer.errors.append(ErrorDescription(decoration))
  374. return decoration.get_wrapper(func)
  375. return decorator
  376. def generate_doc(self, title: str='', description: str='') -> dict:
  377. """
  378. See hapic.doc.DocGenerator#get_doc docstring
  379. :param title: Title of generated doc
  380. :param description: Description of generated doc
  381. :return: dict containing apispec doc
  382. """
  383. return self.doc_generator.get_doc(
  384. self._controllers,
  385. self.context,
  386. title=title,
  387. description=description,
  388. )
  389. def save_doc_in_file(
  390. self,
  391. file_path: str,
  392. title: str='',
  393. description: str='',
  394. ) -> None:
  395. """
  396. See hapic.doc.DocGenerator#get_doc docstring
  397. :param file_path: The file path to write doc in YAML format
  398. :param title: Title of generated doc
  399. :param description: Description of generated doc
  400. """
  401. self.doc_generator.save_in_file(
  402. file_path,
  403. controllers=self._controllers,
  404. context=self.context,
  405. title=title,
  406. description=description,
  407. )
  408. def add_documentation_view(
  409. self,
  410. route: str,
  411. title: str='',
  412. description: str='',
  413. ) -> None:
  414. # Ensure "/" at end of route, else web browser will not consider it as
  415. # a path
  416. if not route.endswith('/'):
  417. route = '{}/'.format(route)
  418. swaggerui_path = os.path.join(
  419. os.path.dirname(os.path.abspath(__file__)),
  420. 'static',
  421. 'swaggerui',
  422. )
  423. # Documentation file view
  424. doc_yaml = self.doc_generator.get_doc_yaml(
  425. controllers=self._controllers,
  426. context=self.context,
  427. title=title,
  428. description=description,
  429. )
  430. def spec_yaml_view(*args, **kwargs):
  431. """
  432. Method to return swagger generated yaml spec file.
  433. This method will be call as a framework view, like those,
  434. it need to handle the default arguments of a framework view.
  435. As frameworks have different arguments patterns, we should
  436. allow any arguments patterns (args, kwargs).
  437. """
  438. return self.context.get_response(
  439. doc_yaml,
  440. mimetype='text/x-yaml',
  441. http_code=HTTPStatus.OK,
  442. )
  443. # Prepare views html content
  444. doc_index_path = os.path.join(swaggerui_path, 'index.html')
  445. with open(doc_index_path, 'r') as doc_page:
  446. doc_page_content = doc_page.read()
  447. doc_page_content = doc_page_content.replace(
  448. '{{ spec_uri }}',
  449. 'spec.yml',
  450. )
  451. # Declare the swaggerui view
  452. def api_doc_view(*args, **kwargs):
  453. """
  454. Method to return html index view of swagger ui.
  455. This method will be call as a framework view, like those,
  456. it need to handle the default arguments of a framework view.
  457. As frameworks have different arguments patterns, we should
  458. allow any arguments patterns (args, kwargs).
  459. """
  460. return self.context.get_response(
  461. doc_page_content,
  462. http_code=HTTPStatus.OK,
  463. mimetype='text/html',
  464. )
  465. # Add a view to generate the html index page of swagger-ui
  466. self.context.add_view(
  467. route=route,
  468. http_method='GET',
  469. view_func=api_doc_view,
  470. )
  471. # Add a doc yaml view
  472. self.context.add_view(
  473. route=os.path.join(route, 'spec.yml'),
  474. http_method='GET',
  475. view_func=spec_yaml_view,
  476. )
  477. # Add swagger directory as served static dir
  478. self.context.serve_directory(
  479. route,
  480. swaggerui_path,
  481. )