hapic.py 19KB

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