hapic.py 18KB

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