hapic.py 19KB

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