| 1 | import copy |
| 2 | import os |
| 3 | from pathlib import Path |
| 4 | from typing import Awaitable, Callable |
| 5 | |
| 6 | from aiohttp import web |
| 7 | from aiohttp.hdrs import METH_ALL, METH_ANY |
| 8 | from apispec import APISpec |
| 9 | from apispec.core import VALID_METHODS_OPENAPI_V2 |
| 10 | from apispec.ext.marshmallow import MarshmallowPlugin, common |
| 11 | from jinja2 import Template |
| 12 | from webargs.aiohttpparser import parser |
| 13 | |
| 14 | from .utils import get_path, get_path_keys, issubclass_py37fix |
| 15 | |
| 16 | _AiohttpView = Callable[[web.Request], Awaitable[web.StreamResponse]] |
| 17 | |
| 18 | VALID_RESPONSE_FIELDS = {"description", "headers", "examples"} |
| 19 | |
| 20 | DEFAULT_RESPONSE_LOCATION = "json" |
| 21 | |
| 22 | NAME_SWAGGER_SPEC = "swagger.spec" |
| 23 | NAME_SWAGGER_DOCS = "swagger.docs" |
| 24 | NAME_SWAGGER_STATIC = "swagger.static" |
| 25 | |
| 26 | INDEX_PAGE = "index.html" |
| 27 | |
| 28 | |
| 29 | def resolver(schema): |
| 30 | schema_instance = common.resolve_schema_instance(schema) |
| 31 | prefix = "Partial-" if schema_instance.partial else "" |
| 32 | schema_cls = common.resolve_schema_cls(schema) |
| 33 | name = prefix + schema_cls.__name__ |
| 34 | if name.endswith("Schema"): |
| 35 | return name[:-6] or name |
| 36 | return name |
| 37 | |
| 38 | |
| 39 | class AiohttpApiSpec: |
| 40 | def __init__( |
| 41 | self, |
| 42 | url="/api/docs/swagger.json", |
| 43 | app=None, |
| 44 | request_data_name="data", |
| 45 | swagger_path=None, |
| 46 | static_path='/static/swagger', |
| 47 | error_callback=None, |
| 48 | in_place=False, |
| 49 | prefix='', |
| 50 | schema_name_resolver=resolver, |
| 51 | **kwargs, |
| 52 | ): |
| 53 | |
| 54 | self.plugin = MarshmallowPlugin(schema_name_resolver=schema_name_resolver) |
| 55 | self.spec = APISpec(plugins=(self.plugin,), openapi_version="2.0", **kwargs) |
| 56 | |
| 57 | self.url = url |
| 58 | self.swagger_path = swagger_path |
| 59 | self.static_path = static_path |
| 60 | self._registered = False |
| 61 | self._request_data_name = request_data_name |
| 62 | self.error_callback = error_callback |
| 63 | self.prefix = prefix |
| 64 | self._index_page = None |
| 65 | if app is not None: |
| 66 | self.register(app, in_place) |
| 67 | |
| 68 | def swagger_dict(self): |
| 69 | """Returns swagger spec representation in JSON format""" |
| 70 | return self.spec.to_dict() |
| 71 | |
| 72 | def register(self, app: web.Application, in_place: bool = False): |
| 73 | """Creates spec based on registered app routes and registers needed view""" |
| 74 | if self._registered is True: |
| 75 | return None |
| 76 | |
| 77 | app["_apispec_request_data_name"] = self._request_data_name |
| 78 | |
| 79 | if self.error_callback: |
| 80 | parser.error_callback = self.error_callback |
| 81 | app["_apispec_parser"] = parser |
| 82 | |
| 83 | if in_place: |
| 84 | self._register(app) |
| 85 | else: |
| 86 | |
| 87 | async def doc_routes(app_): |
| 88 | self._register(app_) |
| 89 | |
| 90 | app.on_startup.append(doc_routes) |
| 91 | |
| 92 | self._registered = True |
| 93 | |
| 94 | if self.url is not None: |
| 95 | |
| 96 | async def swagger_handler(request): |
| 97 | return web.json_response(request.app["swagger_dict"]) |
| 98 | |
| 99 | route_url = self.url |
| 100 | if not self.url.startswith("/"): |
| 101 | route_url = "/{}".format(self.url) |
| 102 | app.router.add_route( |
| 103 | "GET", route_url, swagger_handler, name=NAME_SWAGGER_SPEC |
| 104 | ) |
| 105 | |
| 106 | if self.swagger_path is not None: |
| 107 | self._add_swagger_web_page(app, self.static_path, self.swagger_path) |
| 108 | |
| 109 | def _get_index_page(self, app, static_files, static_path): |
| 110 | if self._index_page is not None: |
| 111 | return self._index_page |
| 112 | |
| 113 | with open(str(static_files / INDEX_PAGE)) as swg_tmp: |
| 114 | url = self.url if app is None else app.router[NAME_SWAGGER_SPEC].url_for() |
| 115 | |
| 116 | if app is not None: |
| 117 | static_path = app.router[NAME_SWAGGER_STATIC].url_for( |
| 118 | filename=INDEX_PAGE |
| 119 | ) |
| 120 | static_path = os.path.dirname(str(static_path)) |
| 121 | |
| 122 | self._index_page = Template(swg_tmp.read()).render( |
| 123 | path=url, static=static_path |
| 124 | ) |
| 125 | |
| 126 | return self._index_page |
| 127 | |
| 128 | def _add_swagger_web_page( |
| 129 | self, app: web.Application, static_path: str, view_path: str |
| 130 | ): |
| 131 | static_files = Path(__file__).parent / "static" |
| 132 | app.router.add_static(static_path, static_files, name=NAME_SWAGGER_STATIC) |
| 133 | |
| 134 | async def swagger_view(_): |
| 135 | index_page = self._get_index_page(app, static_files, static_path) |
| 136 | return web.Response(text=index_page, content_type="text/html") |
| 137 | |
| 138 | app.router.add_route("GET", view_path, swagger_view, name=NAME_SWAGGER_DOCS) |
| 139 | |
| 140 | def _register(self, app: web.Application): |
| 141 | for route in app.router.routes(): |
| 142 | if issubclass_py37fix(route.handler, web.View) and route.method == METH_ANY: |
| 143 | for attr in dir(route.handler): |
| 144 | if attr.upper() in METH_ALL: |
| 145 | view = getattr(route.handler, attr) |
| 146 | method = attr |
| 147 | self._register_route(route, method, view) |
| 148 | else: |
| 149 | method = route.method.lower() |
| 150 | view = route.handler |
| 151 | self._register_route(route, method, view) |
| 152 | app["swagger_dict"] = self.swagger_dict() |
| 153 | |
| 154 | def _register_route( |
| 155 | self, route: web.AbstractRoute, method: str, view: _AiohttpView |
| 156 | ): |
| 157 | |
| 158 | if not hasattr(view, "__apispec__"): |
| 159 | return None |
| 160 | |
| 161 | url_path = get_path(route) |
| 162 | if not url_path: |
| 163 | return None |
| 164 | |
| 165 | self._update_paths(view.__apispec__, method, self.prefix + url_path) |
| 166 | |
| 167 | def _update_paths(self, data: dict, method: str, url_path: str): |
| 168 | if method not in VALID_METHODS_OPENAPI_V2: |
| 169 | return None |
| 170 | for schema in data.pop("schemas", []): |
| 171 | parameters = self.plugin.converter.schema2parameters( |
| 172 | schema["schema"], location=schema["location"], **schema["options"] |
| 173 | ) |
| 174 | self._add_examples(schema["schema"], parameters, schema["example"]) |
| 175 | data["parameters"].extend(parameters) |
| 176 | |
| 177 | existing = [p["name"] for p in data["parameters"] if p["in"] == "path"] |
| 178 | data["parameters"].extend( |
| 179 | {"in": "path", "name": path_key, "required": True, "type": "string"} |
| 180 | for path_key in get_path_keys(url_path) |
| 181 | if path_key not in existing |
| 182 | ) |
| 183 | |
| 184 | if "responses" in data: |
| 185 | responses = {} |
| 186 | for code, actual_params in data["responses"].items(): |
| 187 | if "schema" in actual_params: |
| 188 | raw_parameters = self.plugin.converter.schema2parameters( |
| 189 | actual_params["schema"], |
| 190 | location=DEFAULT_RESPONSE_LOCATION, |
| 191 | required=actual_params.get("required", False), |
| 192 | )[0] |
| 193 | updated_params = { |
| 194 | k: v |
| 195 | for k, v in raw_parameters.items() |
| 196 | if k in VALID_RESPONSE_FIELDS |
| 197 | } |
| 198 | updated_params['schema'] = actual_params["schema"] |
| 199 | for extra_info in ("description", "headers", "examples"): |
| 200 | if extra_info in actual_params: |
| 201 | updated_params[extra_info] = actual_params[extra_info] |
| 202 | responses[code] = updated_params |
| 203 | else: |
| 204 | responses[code] = actual_params |
| 205 | data["responses"] = responses |
| 206 | |
| 207 | operations = copy.deepcopy(data) |
| 208 | self.spec.path(path=url_path, operations={method: operations}) |
| 209 | |
| 210 | def _add_examples(self, ref_schema, endpoint_schema, example): |
| 211 | def add_to_endpoint_or_ref(): |
| 212 | if add_to_refs: |
| 213 | self.spec.components.schemas[name]["example"] = example |
| 214 | else: |
| 215 | endpoint_schema[0]['schema']['allOf'] = [ |
| 216 | endpoint_schema[0]['schema'].pop('$ref') |
| 217 | ] |
| 218 | endpoint_schema[0]['schema']["example"] = example |
| 219 | |
| 220 | if not example: |
| 221 | return |
| 222 | schema_instance = common.resolve_schema_instance(ref_schema) |
| 223 | name = self.plugin.converter.schema_name_resolver(schema_instance) |
| 224 | add_to_refs = example.pop('add_to_refs') |
| 225 | if self.spec.components.openapi_version.major < 3: |
| 226 | if name and name in self.spec.components.schemas: |
| 227 | add_to_endpoint_or_ref() |
| 228 | else: |
| 229 | add_to_endpoint_or_ref() |
| 230 | |
| 231 | |
| 232 | def setup_aiohttp_apispec( |
| 233 | app: web.Application, |
| 234 | *, |
| 235 | title: str = "API documentation", |
| 236 | version: str = "0.0.1", |
| 237 | url: str = "/api/docs/swagger.json", |
| 238 | request_data_name: str = "data", |
| 239 | swagger_path: str = None, |
| 240 | static_path: str = '/static/swagger', |
| 241 | error_callback=None, |
| 242 | in_place: bool = False, |
| 243 | prefix: str = '', |
| 244 | schema_name_resolver: Callable = resolver, |
| 245 | **kwargs, |
| 246 | ) -> None: |
| 247 | """ |
| 248 | aiohttp-apispec extension. |
| 249 | |
| 250 | Usage: |
| 251 | |
| 252 | .. code-block:: python |
| 253 | |
| 254 | from aiohttp_apispec import docs, request_schema, setup_aiohttp_apispec |
| 255 | from aiohttp import web |
| 256 | from marshmallow import Schema, fields |
| 257 | |
| 258 | |
| 259 | class RequestSchema(Schema): |
| 260 | id = fields.Int() |
| 261 | name = fields.Str(description='name') |
| 262 | bool_field = fields.Bool() |
| 263 | |
| 264 | |
| 265 | @docs(tags=['mytag'], |
| 266 | summary='Test method summary', |
| 267 | description='Test method description') |
| 268 | @request_schema(RequestSchema) |
| 269 | async def index(request): |
| 270 | return web.json_response({'msg': 'done', 'data': {}}) |
| 271 | |
| 272 | |
| 273 | app = web.Application() |
| 274 | app.router.add_post('/v1/test', index) |
| 275 | |
| 276 | # init docs with all parameters, usual for ApiSpec |
| 277 | setup_aiohttp_apispec(app=app, |
| 278 | title='My Documentation', |
| 279 | version='v1', |
| 280 | url='/api/docs/api-docs') |
| 281 | |
| 282 | # now we can find it on 'http://localhost:8080/api/docs/api-docs' |
| 283 | web.run_app(app) |
| 284 | |
| 285 | :param Application app: aiohttp web app |
| 286 | :param str title: API title |
| 287 | :param str version: API version |
| 288 | :param str url: url for swagger spec in JSON format |
| 289 | :param str request_data_name: name of the key in Request object |
| 290 | where validated data will be placed by |
| 291 | validation_middleware (``'data'`` by default) |
| 292 | :param str swagger_path: experimental SwaggerUI support (starting from v1.1.0). |
| 293 | By default it is None (disabled) |
| 294 | :param str static_path: path for static files used by SwaggerUI |
| 295 | (if it is enabled with ``swagger_path``) |
| 296 | :param error_callback: custom error handler |
| 297 | :param in_place: register all routes at the moment of calling this function |
| 298 | instead of the moment of the on_startup signal. |
| 299 | If True, be sure all routes are added to router |
| 300 | :param prefix: prefix to add to all registered routes |
| 301 | :param schema_name_resolver: custom schema_name_resolver for MarshmallowPlugin. |
| 302 | :param kwargs: any apispec.APISpec kwargs |
| 303 | :return: return instance of AiohttpApiSpec class |
| 304 | :rtype: AiohttpApiSpec |
| 305 | """ |
| 306 | return AiohttpApiSpec( |
| 307 | url, |
| 308 | app, |
| 309 | request_data_name, |
| 310 | title=title, |
| 311 | version=version, |
| 312 | swagger_path=swagger_path, |
| 313 | static_path=static_path, |
| 314 | error_callback=error_callback, |
| 315 | in_place=in_place, |
| 316 | prefix=prefix, |
| 317 | schema_name_resolver=schema_name_resolver, |
| 318 | **kwargs, |
| 319 | ) |