hapic.py 18KB

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