doc.py 6.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. # -*- coding: utf-8 -*-
  2. import re
  3. import typing
  4. import bottle
  5. from apispec import APISpec
  6. from apispec import Path
  7. from apispec.ext.marshmallow.swagger import schema2jsonschema
  8. from hapic.decorator import DecoratedController
  9. from hapic.decorator import DECORATION_ATTRIBUTE_NAME
  10. # Bottle regular expression to locate url parameters
  11. from hapic.description import ControllerDescription
  12. BOTTLE_RE_PATH_URL = re.compile(r'<(?:[^:<>]+:)?([^<>]+)>')
  13. def find_bottle_route(
  14. decorated_controller: DecoratedController,
  15. app: bottle.Bottle,
  16. ):
  17. if not app.routes:
  18. # TODO BS 20171010: specialize exception
  19. raise Exception('There is no routes in yout bottle app')
  20. reference = decorated_controller.reference
  21. for route in app.routes:
  22. route_token = getattr(
  23. route.callback,
  24. DECORATION_ATTRIBUTE_NAME,
  25. None,
  26. )
  27. match_with_wrapper = route.callback == reference.wrapper
  28. match_with_wrapped = route.callback == reference.wrapped
  29. match_with_token = route_token == reference.token
  30. if match_with_wrapper or match_with_wrapped or match_with_token:
  31. return route
  32. # TODO BS 20171010: specialize exception
  33. # TODO BS 20171010: Raise exception or print error ?
  34. raise Exception(
  35. 'Decorated route "{}" was not found in bottle routes'.format(
  36. decorated_controller.name,
  37. )
  38. )
  39. def bottle_generate_operations(
  40. spec,
  41. bottle_route: bottle.Route,
  42. description: ControllerDescription,
  43. ):
  44. method_operations = dict()
  45. # schema based
  46. if description.input_body:
  47. schema_class = type(description.input_body.wrapper.processor.schema)
  48. method_operations.setdefault('parameters', []).append({
  49. 'in': 'body',
  50. 'name': 'body',
  51. 'schema': {
  52. '$ref': '#/definitions/{}'.format(schema_class.__name__)
  53. }
  54. })
  55. if description.output_body:
  56. schema_class = type(description.output_body.wrapper.processor.schema)
  57. method_operations.setdefault('responses', {})\
  58. [int(description.output_body.wrapper.default_http_code)] = {
  59. 'description': str(description.output_body.wrapper.default_http_code), # nopep8
  60. 'schema': {
  61. '$ref': '#/definitions/{}'.format(schema_class.__name__)
  62. }
  63. }
  64. if description.errors:
  65. for error in description.errors:
  66. method_operations.setdefault('responses', {})\
  67. [int(error.wrapper.http_code)] = {
  68. 'description': str(error.wrapper.http_code),
  69. }
  70. # jsonschema based
  71. if description.input_path:
  72. schema_class = type(description.input_path.wrapper.processor.schema)
  73. # TODO: look schema2parameters ?
  74. jsonschema = schema2jsonschema(schema_class, spec=spec)
  75. for name, schema in jsonschema.get('properties', {}).items():
  76. method_operations.setdefault('parameters', []).append({
  77. 'in': 'path',
  78. 'name': name,
  79. 'required': name in jsonschema.get('required', []),
  80. 'type': schema['type']
  81. })
  82. if description.input_query:
  83. schema_class = type(description.input_query.wrapper.processor.schema)
  84. jsonschema = schema2jsonschema(schema_class, spec=spec)
  85. for name, schema in jsonschema.get('properties', {}).items():
  86. method_operations.setdefault('parameters', []).append({
  87. 'in': 'query',
  88. 'name': name,
  89. 'required': name in jsonschema.get('required', []),
  90. 'type': schema['type']
  91. })
  92. operations = {
  93. bottle_route.method.lower(): method_operations,
  94. }
  95. return operations
  96. class DocGenerator(object):
  97. def get_doc(
  98. self,
  99. controllers: typing.List[DecoratedController],
  100. app,
  101. ) -> dict:
  102. # TODO: Découper
  103. # TODO: bottle specific code !
  104. if not app:
  105. app = bottle.default_app()
  106. else:
  107. bottle.default_app.push(app)
  108. flatten = lambda l: [item for sublist in l for item in sublist]
  109. spec = APISpec(
  110. title='Swagger Petstore',
  111. version='1.0.0',
  112. plugins=[
  113. 'apispec.ext.bottle',
  114. 'apispec.ext.marshmallow',
  115. ],
  116. )
  117. schemas = []
  118. # parse schemas
  119. for controller in controllers:
  120. description = controller.description
  121. if description.input_body:
  122. schemas.append(type(
  123. description.input_body.wrapper.processor.schema
  124. ))
  125. if description.input_forms:
  126. schemas.append(type(
  127. description.input_forms.wrapper.processor.schema
  128. ))
  129. if description.output_body:
  130. schemas.append(type(
  131. description.output_body.wrapper.processor.schema
  132. ))
  133. for schema in set(schemas):
  134. spec.definition(schema.__name__, schema=schema)
  135. # add views
  136. # with app.test_request_context():
  137. paths = {}
  138. for controller in controllers:
  139. bottle_route = find_bottle_route(controller, app)
  140. swagger_path = BOTTLE_RE_PATH_URL.sub(r'{\1}', bottle_route.rule)
  141. operations = bottle_generate_operations(
  142. spec,
  143. bottle_route,
  144. controller.description,
  145. )
  146. path = Path(path=swagger_path, operations=operations)
  147. if swagger_path in paths:
  148. paths[swagger_path].update(path)
  149. else:
  150. paths[swagger_path] = path
  151. spec.add_path(path)
  152. return spec.to_dict()
  153. # route_by_callbacks = []
  154. # routes = flatten(app.router.dyna_routes.values())
  155. # for path, path_regex, route, func_ in routes:
  156. # route_by_callbacks.append(route.callback)
  157. #
  158. # for description in self._controllers:
  159. # for path, path_regex, route, func_ in routes:
  160. # if route.callback == description.reference:
  161. # # TODO: use description to feed apispec
  162. # print(route.method, path, description)
  163. # continue