hapic.py 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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. ignore_on_error: bool = True,
  157. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  158. """
  159. Decorate with a wrapper who check and serialize each items in output
  160. stream.
  161. :param item_schema: Schema of output stream items
  162. :param processor: ProcessorInterface object to process with given
  163. schema
  164. :param context: Context to use here
  165. :param error_http_code: http code in case of error
  166. :param default_http_code: http code in case of success
  167. :param ignore_on_error: if set, an error of serialization will be
  168. ignored: stream will not send this failed object
  169. :return: decorator
  170. """
  171. processor = processor or MarshmallowOutputProcessor()
  172. processor.schema = item_schema
  173. context = context or self._context_getter
  174. if self._async:
  175. decoration = AsyncOutputStreamControllerWrapper(
  176. context=context,
  177. processor=processor,
  178. error_http_code=error_http_code,
  179. default_http_code=default_http_code,
  180. ignore_on_error=ignore_on_error,
  181. )
  182. else:
  183. # TODO BS 2018-07-25: To do
  184. raise NotImplementedError('todo')
  185. def decorator(func):
  186. self._buffer.output_stream = OutputStreamDescription(decoration)
  187. return decoration.get_wrapper(func)
  188. return decorator
  189. def output_headers(
  190. self,
  191. schema: typing.Any,
  192. processor: ProcessorInterface = None,
  193. context: ContextInterface = None,
  194. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  195. default_http_code: HTTPStatus = HTTPStatus.OK,
  196. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  197. processor = processor or MarshmallowOutputProcessor()
  198. processor.schema = schema
  199. context = context or self._context_getter
  200. decoration = OutputHeadersControllerWrapper(
  201. context=context,
  202. processor=processor,
  203. error_http_code=error_http_code,
  204. default_http_code=default_http_code,
  205. )
  206. def decorator(func):
  207. self._buffer.output_headers = OutputHeadersDescription(decoration)
  208. return decoration.get_wrapper(func)
  209. return decorator
  210. # TODO BS 20171102: Think about possibilities to validate output ?
  211. # (with mime type, or validator)
  212. def output_file(
  213. self,
  214. output_types: typing.List[str],
  215. default_http_code: HTTPStatus = HTTPStatus.OK,
  216. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  217. decoration = OutputFileControllerWrapper(
  218. output_types=output_types,
  219. default_http_code=default_http_code,
  220. )
  221. def decorator(func):
  222. self._buffer.output_file = OutputFileDescription(decoration)
  223. return decoration.get_wrapper(func)
  224. return decorator
  225. def input_headers(
  226. self,
  227. schema: typing.Any,
  228. processor: ProcessorInterface = None,
  229. context: ContextInterface = None,
  230. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  231. default_http_code: HTTPStatus = HTTPStatus.OK,
  232. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  233. processor = processor or MarshmallowInputProcessor()
  234. processor.schema = schema
  235. context = context or self._context_getter
  236. decoration = InputHeadersControllerWrapper(
  237. context=context,
  238. processor=processor,
  239. error_http_code=error_http_code,
  240. default_http_code=default_http_code,
  241. )
  242. def decorator(func):
  243. self._buffer.input_headers = InputHeadersDescription(decoration)
  244. return decoration.get_wrapper(func)
  245. return decorator
  246. def input_path(
  247. self,
  248. schema: typing.Any,
  249. processor: ProcessorInterface = None,
  250. context: ContextInterface = None,
  251. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  252. default_http_code: HTTPStatus = HTTPStatus.OK,
  253. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  254. processor = processor or MarshmallowInputProcessor()
  255. processor.schema = schema
  256. context = context or self._context_getter
  257. decoration = InputPathControllerWrapper(
  258. context=context,
  259. processor=processor,
  260. error_http_code=error_http_code,
  261. default_http_code=default_http_code,
  262. )
  263. def decorator(func):
  264. self._buffer.input_path = InputPathDescription(decoration)
  265. return decoration.get_wrapper(func)
  266. return decorator
  267. def input_query(
  268. self,
  269. schema: typing.Any,
  270. processor: ProcessorInterface = None,
  271. context: ContextInterface = None,
  272. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  273. default_http_code: HTTPStatus = HTTPStatus.OK,
  274. as_list: typing.List[str]=None,
  275. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  276. processor = processor or MarshmallowInputProcessor()
  277. processor.schema = schema
  278. context = context or self._context_getter
  279. decoration = InputQueryControllerWrapper(
  280. context=context,
  281. processor=processor,
  282. error_http_code=error_http_code,
  283. default_http_code=default_http_code,
  284. as_list=as_list,
  285. )
  286. def decorator(func):
  287. self._buffer.input_query = InputQueryDescription(decoration)
  288. return decoration.get_wrapper(func)
  289. return decorator
  290. def input_body(
  291. self,
  292. schema: typing.Any,
  293. processor: ProcessorInterface = None,
  294. context: ContextInterface = None,
  295. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  296. default_http_code: HTTPStatus = HTTPStatus.OK,
  297. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  298. processor = processor or MarshmallowInputProcessor()
  299. processor.schema = schema
  300. context = context or self._context_getter
  301. if self._async:
  302. decoration = AsyncInputBodyControllerWrapper(
  303. context=context,
  304. processor=processor,
  305. error_http_code=error_http_code,
  306. default_http_code=default_http_code,
  307. )
  308. else:
  309. decoration = InputBodyControllerWrapper(
  310. context=context,
  311. processor=processor,
  312. error_http_code=error_http_code,
  313. default_http_code=default_http_code,
  314. )
  315. def decorator(func):
  316. self._buffer.input_body = InputBodyDescription(decoration)
  317. return decoration.get_wrapper(func)
  318. return decorator
  319. def input_forms(
  320. self,
  321. schema: typing.Any,
  322. processor: ProcessorInterface=None,
  323. context: ContextInterface=None,
  324. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  325. default_http_code: HTTPStatus = HTTPStatus.OK,
  326. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  327. processor = processor or MarshmallowInputProcessor()
  328. processor.schema = schema
  329. context = context or self._context_getter
  330. decoration = InputBodyControllerWrapper(
  331. context=context,
  332. processor=processor,
  333. error_http_code=error_http_code,
  334. default_http_code=default_http_code,
  335. )
  336. def decorator(func):
  337. self._buffer.input_forms = InputFormsDescription(decoration)
  338. return decoration.get_wrapper(func)
  339. return decorator
  340. def input_files(
  341. self,
  342. schema: typing.Any,
  343. processor: ProcessorInterface=None,
  344. context: ContextInterface=None,
  345. error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
  346. default_http_code: HTTPStatus = HTTPStatus.OK,
  347. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  348. processor = processor or MarshmallowInputFilesProcessor()
  349. processor.schema = schema
  350. context = context or self._context_getter
  351. decoration = InputFilesControllerWrapper(
  352. context=context,
  353. processor=processor,
  354. error_http_code=error_http_code,
  355. default_http_code=default_http_code,
  356. )
  357. def decorator(func):
  358. self._buffer.input_files = InputFilesDescription(decoration)
  359. return decoration.get_wrapper(func)
  360. return decorator
  361. def handle_exception(
  362. self,
  363. handled_exception_class: typing.Type[Exception]=Exception,
  364. http_code: HTTPStatus = HTTPStatus.INTERNAL_SERVER_ERROR,
  365. error_builder: ErrorBuilderInterface=None,
  366. context: ContextInterface = None,
  367. ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
  368. context = context or self._context_getter
  369. error_builder = error_builder or self._error_builder_getter
  370. decoration = ExceptionHandlerControllerWrapper(
  371. handled_exception_class,
  372. context,
  373. error_builder=error_builder,
  374. http_code=http_code,
  375. )
  376. def decorator(func):
  377. self._buffer.errors.append(ErrorDescription(decoration))
  378. return decoration.get_wrapper(func)
  379. return decorator
  380. def generate_doc(self, title: str='', description: str='') -> dict:
  381. """
  382. See hapic.doc.DocGenerator#get_doc docstring
  383. :param title: Title of generated doc
  384. :param description: Description of generated doc
  385. :return: dict containing apispec doc
  386. """
  387. return self.doc_generator.get_doc(
  388. self._controllers,
  389. self.context,
  390. title=title,
  391. description=description,
  392. )
  393. def save_doc_in_file(
  394. self,
  395. file_path: str,
  396. title: str='',
  397. description: str='',
  398. ) -> None:
  399. """
  400. See hapic.doc.DocGenerator#get_doc docstring
  401. :param file_path: The file path to write doc in YAML format
  402. :param title: Title of generated doc
  403. :param description: Description of generated doc
  404. """
  405. self.doc_generator.save_in_file(
  406. file_path,
  407. controllers=self._controllers,
  408. context=self.context,
  409. title=title,
  410. description=description,
  411. )
  412. def add_documentation_view(
  413. self,
  414. route: str,
  415. title: str='',
  416. description: str='',
  417. ) -> None:
  418. # Ensure "/" at end of route, else web browser will not consider it as
  419. # a path
  420. if not route.endswith('/'):
  421. route = '{}/'.format(route)
  422. swaggerui_path = os.path.join(
  423. os.path.dirname(os.path.abspath(__file__)),
  424. 'static',
  425. 'swaggerui',
  426. )
  427. # Documentation file view
  428. doc_yaml = self.doc_generator.get_doc_yaml(
  429. controllers=self._controllers,
  430. context=self.context,
  431. title=title,
  432. description=description,
  433. )
  434. def spec_yaml_view(*args, **kwargs):
  435. """
  436. Method to return swagger generated yaml spec file.
  437. This method will be call as a framework view, like those,
  438. it need to handle the default arguments of a framework view.
  439. As frameworks have different arguments patterns, we should
  440. allow any arguments patterns (args, kwargs).
  441. """
  442. return self.context.get_response(
  443. doc_yaml,
  444. mimetype='text/x-yaml',
  445. http_code=HTTPStatus.OK,
  446. )
  447. # Prepare views html content
  448. doc_index_path = os.path.join(swaggerui_path, 'index.html')
  449. with open(doc_index_path, 'r') as doc_page:
  450. doc_page_content = doc_page.read()
  451. doc_page_content = doc_page_content.replace(
  452. '{{ spec_uri }}',
  453. 'spec.yml',
  454. )
  455. # Declare the swaggerui view
  456. def api_doc_view(*args, **kwargs):
  457. """
  458. Method to return html index view of swagger ui.
  459. This method will be call as a framework view, like those,
  460. it need to handle the default arguments of a framework view.
  461. As frameworks have different arguments patterns, we should
  462. allow any arguments patterns (args, kwargs).
  463. """
  464. return self.context.get_response(
  465. doc_page_content,
  466. http_code=HTTPStatus.OK,
  467. mimetype='text/html',
  468. )
  469. # Add a view to generate the html index page of swagger-ui
  470. self.context.add_view(
  471. route=route,
  472. http_method='GET',
  473. view_func=api_doc_view,
  474. )
  475. # Add a doc yaml view
  476. self.context.add_view(
  477. route=os.path.join(route, 'spec.yml'),
  478. http_method='GET',
  479. view_func=spec_yaml_view,
  480. )
  481. # Add swagger directory as served static dir
  482. self.context.serve_directory(
  483. route,
  484. swaggerui_path,
  485. )