from aiohttp import web from aiohttp_apispec import response_schema from server import config def dump_response_schema(schema, code=200, required=False, description=None, apply=(not config.DISABLE_DUMP_SCHEMA)): """Extended response schema which is possible to apply for response. Reflect endpoint description in swagger documentation (like response_schema), dumps the result of wrapped function if 'apply' is True and the result is not an instance of web.Response. """ if callable(schema): schema = schema() def wrapper(f): async def wrapped(*args, **kwargs): result = await f(*args, **kwargs) if isinstance(result, web.Response): return result return web.json_response(schema.dump(result) if apply else result, status=code) return response_schema(schema, code=code, required=required, description=description)(wrapped) return wrapper