async def test_spec(loop, test_client, middlewares): router = SwaggerRouter( search_dirs=['tests'], default_validate=True, swagger_ui='apidoc', ) app = web.Application(router=router, loop=loop, middlewares=middlewares) router.include('data/root.yaml') cli = await test_client(app) spec_url = router['swagger:spec'].url_for() ui_url = router['swagger:ui'].url_for() resp = await cli.get(ui_url) assert resp.status == 200, (await resp.text()) resp = await cli.get(ui_url.with_query(spec='/api/1')) assert resp.status == 200, (await resp.text()) resp = await cli.get(spec_url) assert resp.status == 200, (await resp.text()) resp = await cli.get(spec_url.with_query(spec='/api/1')) assert resp.status == 200, (await resp.text())
def test_spec(loop, test_client, middlewares): router = SwaggerRouter( search_dirs=['tests'], default_validate=True, swagger_ui='apidoc', ) app = web.Application( router=router, loop=loop, middlewares=middlewares) router.include('data/root.yaml') cli = yield from test_client(app) spec_url = router['swagger:spec'].url_for() ui_url = router['swagger:ui'].url_for() resp = yield from cli.get(ui_url) assert resp.status == 200, resp resp = yield from cli.get(ui_url.with_query(spec='/api/1')) assert resp.status == 200, resp resp = yield from cli.get(spec_url) assert resp.status == 200, resp resp = yield from cli.get(spec_url.with_query(spec='/api/1')) assert resp.status == 200, resp
def swagger_router(): router = SwaggerRouter( search_dirs=['tests'], swagger_ui=False, ) router.include('data/root.yaml') return router
async def test_bool(test_client): def handler(b): return web.json_response(b) r = SwaggerRouter() r.add_get('/', handler=handler, swagger_data={ 'parameters': [{ 'name': 'b', 'in': 'query', 'type': 'boolean', 'default': False, }] }) app = web.Application(router=r) client = await test_client(app) r = await client.get('/?b=True') assert r.status == 200, (await r.text()) assert (await r.json()) is True r = await client.get('/?b=') assert r.status == 200, (await r.text()) assert (await r.json()) is True r = await client.get('/?b') assert r.status == 200, (await r.text()) assert (await r.json()) is True r = await client.get('/') assert r.status == 200, (await r.text()) assert (await r.json()) is False
def test_Path(): base = Path(__file__).parent router = SwaggerRouter( search_dirs=[base], swagger_ui=False, ) spec = base / 'data/root.yaml' router.include(spec) assert router._swagger_data
async def test_validation_errors_constructor(test_client): def handler(request): raise ValidationError('', r=[''], q='') r = SwaggerRouter() r.add_get('/', handler=handler) app = web.Application(router=r) client = await test_client(app) r = await client.get('/') assert r.status == 400, (await r.text())
def main(): router = SwaggerRouter(swagger_ui='/swagger/', ) router.add_post('/doc/{doc_id:\d+}', handler=set_document) app = web.Application( router=router, middlewares=[jsonify], ) # is now available in the swagger-ui to the address http://localhost:8080/swagger/ web.run_app(app)
def test_override_basePath(loop): router = SwaggerRouter(search_dirs=['tests']) web.Application(router=router, loop=loop) prefix = '/override' router.include('data/root.yaml', basePath=prefix) paths = [url for url in [ route.url_for().human_repr() for route in router.routes() ] if url.startswith(prefix)] assert prefix in router._swagger_data assert paths
def test_override_basePath(): router = SwaggerRouter(search_dirs=['tests']) prefix = '/override' router.include('data/root.yaml', basePath=prefix) paths = [ url for route, url in router._routes.values() if url.startswith(prefix) ] assert prefix in router._swagger_data assert paths
def __init__(self, *args, **kwargs): router = SwaggerRouter(search_dirs=['tutorial']) kwargs['router'] = router kwargs.setdefault('middlewares', []).append(jsonify) super().__init__(**kwargs) router.include('api.yaml') cls = type(self) self.on_startup.append(cls.startup_database) self.on_cleanup.append(cls.cleanup_database)
def get_app(options): """Get app.""" router = SwaggerRouter(swagger_ui='/swagger/') app = web.Application( router=router, middlewares=[ jsonify, SentryMiddleware(), log_middleware, ], ) app['logger'] = pygogo.Gogo( __name__, low_formatter=pygogo.formatters.structured_formatter, verbose=options.option('debug')) if options.option('debug'): logging.basicConfig(level=logging.DEBUG) app['sessions'] = {} app['logger'].get_logger().debug("starting") app['config'] = configparser.ConfigParser() app['config'].read(options.option('config') or '') setup(app) setup_routes(app) return app
def test_router_files(test_client): router = SwaggerRouter(search_dirs=['tests'], default_validate=True) router.include('data/root.yaml') def factory(loop, *args, **kwargs): app = web.Application(router=router, loop=loop, middlewares=[jsonify]) return app cli = yield from test_client(factory) url = router['file:simple:view'].url() assert isinstance( router['file:simple:view']._routes['POST'], SwaggerValidationRoute) resp = yield from cli.post(url + '?road_id=g') assert resp.status == 200, resp
async def test_json(test_client): router = SwaggerRouter( search_dirs=['tests'], default_validate=True, swagger_ui=False, ) router.include('data/root.yaml') def factory(loop, *args, **kwargs): app = web.Application(router=router, loop=loop, middlewares=[jsonify]) return app cli = await test_client(factory) url = router['file:simple:view'].url() resp = await cli.put(url) assert resp.status == 200, (await resp.text())
def test_json(test_client): router = SwaggerRouter( search_dirs=['tests'], default_validate=True, ) router.include('data/root.yaml') def factory(loop, *args, **kwargs): app = web.Application( router=router, loop=loop, middlewares=[jsonify]) return app cli = yield from test_client(factory) url = cli.app.router['file:simple:view'].url() resp = yield from cli.put(url) assert resp.status == 200, resp
def test_router(test_client): router = SwaggerRouter() router.add_route( 'POST', '/', handler, swagger_data={'parameters': parameters}, ).build_swagger_data({}) def factory(loop, *args, **kwargs): app = web.Application(router=router, loop=loop, middlewares=[jsonify]) return app cli = yield from test_client(factory) query = '/?road_id=1&road_id_csv=1&road_id_brackets[]=1' resp = yield from cli.post(query) assert resp.status == 200, resp txt = yield from resp.text() assert 'road_id' in txt, txt assert 'road_id_csv' in txt, txt assert 'road_id_brackets' in txt, txt
def main(): router = SwaggerRouter( encoding='utf-8', default_validate=True, swagger_ui=True, search_dirs=[BASE], ) app = web.Application( router=router, middlewares=[jsonify], ) # Include our specifications in a router, # is now available in the swagger-ui to the address /apidoc/ router.include( spec='swagger.yaml', operationId_mapping=opmap, ) web.run_app(app)
async def test_router(test_client): router = SwaggerRouter() router.add_route( 'POST', '/', handler, swagger_data={'parameters': parameters}, ) def factory(loop, *args, **kwargs): app = web.Application(router=router, loop=loop, middlewares=[jsonify]) return app cli = await test_client(factory) query = '/?road_id=1&road_id_csv=1&road_id_brackets[]=1' resp = await cli.post(query) assert resp.status == 200, (await resp.text()) txt = await resp.text() assert 'road_id' in txt, txt assert 'road_id_csv' in txt, txt assert 'road_id_brackets' in txt, txt
def test_spec(test_client, middlewares): router = SwaggerRouter( search_dirs=['tests'], default_validate=True, ) router.include('data/root.yaml') def factory(loop, *args, **kwargs): app = web.Application( router=router, loop=loop, middlewares=middlewares) return app cli = yield from test_client(factory) spec_url = list(router._swagger_yaml.keys())[0] ui_url = urljoin(spec_url, 'index.html') resp = yield from cli.get(ui_url) assert resp.status == 200, resp resp = yield from cli.get(spec_url) assert resp.status == 200, resp
def main(): async def on_startup(app: Application) -> None: app['session'] = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout()) app['replicant'] = Replicant(app['session']) await app['replicant'].start() async def on_cleanup(app: Application) -> None: await app['replicant'].stop() await app['session'].close() opmap = OperationIdMapping() opmap.add(general) router = SwaggerRouter(swagger_ui='/ui/', search_dirs=[spec_dir]) router.include(spec=spec_file, operationId_mapping=opmap) app = web.Application(router=router, middlewares=[jsonify]) app.on_startup.append(on_startup) app.on_cleanup.append(on_cleanup) logger.debug('Server is starting') web.run_app(app)
def create_router(oas3_path: Path = None): """ Creates a router provided openapi specification file version 3 (oas3) oas3_path: path to rest-api specifications. Mostly used for testing different apis """ if oas3_path is None: oas3_path = openapi_path() log.debug("OAS3 in %s", oas3_path) # generate a version 3 of the API documentation router = SwaggerRouter( swagger_ui='/apidoc/', version_ui=3, # forces the use of version 3 by default search_dirs=[str(oas3_path.parent)], default_validate=True, ) # TODO: check root_factory in SwaggerRouter?! # TODO: Deprecated since version 3.3: The custom routers support is deprecated, the parameter will be removed in 4.0. # See https://docs.aiohttp.org/en/stable/web_advanced.html#custom-routing-criteria return router
def create_web_app(base_folder, spec_file, additional_middlewares=None): # create the default mapping of the operationId to the implementation code in handlers opmap = __create_default_operation_mapping(Path(base_folder / spec_file)) # generate a version 3 of the API documentation router = SwaggerRouter( swagger_ui='/apidoc/', version_ui=3, # forces the use of version 3 by default search_dirs=[base_folder], default_validate=True, ) # add automatic jsonification of the models located in generated code jsonify.singleton = Jsonify(indent=3, ensure_ascii=False) jsonify.singleton.add_converter(Model, lambda o: o.to_dict(), score=0) middlewares = [jsonify, __handle_errors] if additional_middlewares: middlewares.extend(additional_middlewares) # create the web application using the API app = web.Application( router=router, middlewares=middlewares, ) router.set_cors(app, domains='*', headers=((hdrs.ACCESS_CONTROL_EXPOSE_HEADERS, hdrs.AUTHORIZATION), )) # Include our specifications in a router, # is now available in the swagger-ui to the address http://localhost:8080/swagger/?spec=v1 router.include( spec=Path(base_folder / spec_file), operationId_mapping=opmap, name='v0', # name to access in swagger-ui, basePath= "/v0" # BUG: in apiset with openapi 3.0.0 [Github bug entry](https://github.com/aamalev/aiohttp_apiset/issues/45) ) return app
def main(): router = SwaggerRouter( swagger_ui='/swagger/', search_dirs=[BASE], ) app = web.Application( router=router, middlewares=[jsonify], ) router.set_cors(app, domains='*', headers=((hdrs.ACCESS_CONTROL_EXPOSE_HEADERS, hdrs.AUTHORIZATION), )) # Include our specifications in a router, # is now available in the swagger-ui to the address http://localhost:8080/swagger/?spec=v1 router.include( spec='swagger.yaml', operationId_mapping=opmap, name='v1', # name to access in swagger-ui ) web.run_app(app)
request['last_visited'] = session['last_visited'] return await handler(request) loop = asyncio.get_event_loop() pg_pool = loop.run_until_complete(create_pool()) db = Database(pg_pool) redis = loop.run_until_complete(get_redis_pool()) storage = RedisStorage(redis) session_middleware = aiohttp_session.session_middleware(storage) dir_path = os.path.dirname(os.path.realpath(__file__)) router = SwaggerRouter(search_dirs=[dir_path], swagger_ui='/api/', default_validate=True) app = web.Application(router=router, middlewares=[ session_middleware, error_middleware, user_middleware, jsonify ]) add_routes(app) aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates')) app['database'] = db app['snmp'] = Snmp("192.168.63.10", 161, "public") # setup_swagger(app) app.on_cleanup.append(Database.close)
from pathlib import Path from aiohttp import web, hdrs from aiohttp_apiset import SwaggerRouter from aiohttp_apiset.middlewares import jsonify BASE = Path(__file__).parent router = SwaggerRouter( swagger_ui='/swagger/', search_dirs=[BASE], ) router.add_post('/api/v1/doc/{doc_id:\d+}', handler='handlers.set_document') app = web.Application( router=router, middlewares=[jsonify], ) router.set_cors(app, domains='*', headers=((hdrs.ACCESS_CONTROL_EXPOSE_HEADERS, hdrs.AUTHORIZATION), )) # Include our specifications in a router router.include(spec='swagger.yaml', basePath='/api/v1') if __name__ == '__main__': # now available swagger-ui to the address http://localhost:8080/swagger/ web.run_app(app)
def test_search_dirs(): d = Path(__file__).parent r = SwaggerRouter(d / 'data/include.yaml') r.add_search_dir(d)
def test_merge_spec(): d = Path(__file__).parent r = SwaggerRouter(d / 'data/include.yaml', search_dirs=[d]) r.include('data/file.yaml', basePath='/inc')
def test_merge_spec(): d = Path(__file__).parent r = SwaggerRouter(d / 'data/include.yaml') r.include('file.yaml', basePath='/inc')
def test_route_include(swagger_router: SwaggerRouter): paths = [route.url_for().human_repr() for route in swagger_router.routes()] assert '/api/1/include2/inc/image' in paths, paths
def test_routes(swagger_router: SwaggerRouter): paths = [route.url_for().human_repr() for route in swagger_router.routes()] assert '/api/1/file/image' in paths
def test_handler(swagger_router: SwaggerRouter): paths = [(route.method, route.url_for().human_repr()) for route in swagger_router.routes()] assert ('GET', '/api/1/include/image') in paths