def create_app(config: 'dict') -> 'Application': """Create server application and all necessary services. :param config: server settings """ logger_configure( level=config['LOG_LEVEL'], root_level=config['LOG_ROOT_LEVEL']) app = Application(debug=config['DEBUG']) app['config'] = config if config['DEBUG'] and not config['TESTING']: log.warning('Run in DEBUG mode!') aiohttp_autoreload.start() api_app = Application() app['api'] = api_app register_routes(api_app, routes['/api']) app.add_subapp('/api', api_app) register_routes(app, routes['/']) return app
async def create_app( *, config: Optional[Configuration] = None, slack: Optional[WebClient] = None, ) -> Application: """Create and configure the Checkerboard application. On startup, Checkerboard will rebuild its mapping of Slack users to GitHub users and will not start responding to routes (including health checks) until that is done. This will take 10-15 minutes, so set health check timeouts accordingly. Parameters ---------- config : `Configuration`, optional The configuration to use. If not provided, the default Configuration will be used. This is a parameter primarily to allow for dependency injection by the test suite. slack : `WebClient`, optional The Slack WebClient to use. If not provided, one will be created based on the application configuration. This is a parameter primarily to allow for dependency injection by the test suite. """ if not config: config = Configuration() configure_logging( profile=config.profile, log_level=config.log_level, name=config.logger_name, ) # Create the Slack to GitHub mapper and retrieve the initial mapping # before creating the application. This ensures that it will not respond # to health checks until the mapping is ready. if not slack: slack = WebClient(config.slack_token, run_async=True) mapper = await create_mapper(config, slack) root_app = Application() root_app["safir/config"] = config root_app["checkerboard/mapper"] = mapper setup_metadata(package_name="checkerboard", app=root_app) setup_middleware(root_app) root_app.add_routes(init_internal_routes()) root_app.cleanup_ctx.append(create_mapper_refresh_task) sub_app = Application() setup_middleware(sub_app) sub_app.add_routes(init_external_routes()) root_app.add_subapp(f"/{config.name}", sub_app) # The basic auth middleware requires the full URL, so attach it to the # root app, even though all the protected URLs are in the sub app. root_app.middlewares.append( basic_auth_middleware( (f"/{config.name}/slack", f"/{config.name}/github"), {config.username: config.password}, )) return root_app
def get_serve_app(self) -> Application: """Create the application which runs the server""" app = self.web(server=True) if self.base_path: base = Application() base.add_subapp(self.base_path, app) base["cli"] = self app = base return app
def register_nested_apps(app: web.Application) -> None: """ Joining nested apps for using like Flask's blueprints :param app: The app web.Application from aiohttp """ app.router.add_get('/', default_entry_point) app.add_subapp('/check', checker) app.add_subapp('/history', history) return None
def setup_async_metrics( app: web.Application, subapp_name: str = "async_metrics", ): monitoring = web.Application(middlewares=[restrict_access]) monitoring.add_routes([ web.get("/summary", _main_handler, name="async_metrics_summary"), web.get("/all", _metrics_handler, name="async_metrics_all"), web.get( "/asyncio", _asyncio_metrics_handler, name="async_metrics_asyncio", ), web.get( "/system", _system_metrics_handler, name="async_metrics_system", ), web.get( "/system/dependencies", _dependencies_metrics_handler, name="async_metrics_dependencies", ), web.get( "/system/python", _python_metrics_handler, name="async_metrics_python", ), web.get( "/system/process", _process_metrics_handler, name="async_metrics_process", ), web.get( "/system/partitions", _partitions_metrics_handler, name="async_metrics_partitions", ), web.get( "/routes", _routes_handler, name="async_metrics_routes", ), web.get("/about", _about_handler, name="async_metrics_about"), ]) app.add_subapp(f"/{subapp_name}", monitoring) app["async_metrics"] = monitoring
def _init_subapp(pkg_name: str, root_app: web.Application, subapp: web.Application, global_middlewares: Iterable[WebMiddleware]) -> None: subapp.on_response_prepare.append(on_prepare) async def _copy_public_interface_objs(subapp: web.Application): # Allow subapp's access to the root app properties. # These are the public APIs exposed to plugins as well. for key, obj in public_interface_objs.items(): subapp[key] = obj # We must copy the public interface prior to all user-defined startup signal handlers. subapp.on_startup.insert(0, _copy_public_interface_objs) prefix = subapp.get('prefix', pkg_name.split('.')[-1].replace('_', '-')) aiojobs.aiohttp.setup(subapp, **root_app['scheduler_opts']) root_app.add_subapp('/' + prefix, subapp) root_app.middlewares.extend(global_middlewares)
def init_app_authenticate(*, app: web.Application, living_time: int, private_key: bytes) -> None: """ Init and returns sub app for accounts :param app: main web.Application object :param living_time: living token time :param private_key: private key for signature JWT :return: """ app_authenticate = web.Application() app_authenticate['living_time'] = living_time app_authenticate['private_key'] = private_key init_routes(app_authenticate) app.add_subapp('/authenticate/', app_authenticate) app['authenticate'] = app_authenticate
def setup( app: web.Application, apps_to_expose: Iterable[web.Application] = (), url_prefix: str = "/oas", enable: bool = True, version_spec: Optional[str] = None, title_spec: Optional[str] = None, ): if enable: oas_app = web.Application() oas_app["apps to expose"] = tuple(apps_to_expose) or (app, ) oas_app["index template"] = jinja2.Template( resources.read_text("aiohttp_pydantic.oas", "index.j2")) oas_app["version_spec"] = version_spec oas_app["title_spec"] = title_spec oas_app.router.add_get("/spec", get_oas, name="spec") oas_app.router.add_static("/static", swagger_ui_path, name="static") oas_app.router.add_get("", oas_ui, name="index") app.add_subapp(url_prefix, oas_app)
def app_startup(app_list: list, app: web.Application, context: dict, **kwargs: dict): # Configure the main App # app.router.add_route("GET", "/ping", ping) # index app.router.add_get("/", home) for app_name in app_list: obj = None try: name = app_name.split(".")[1] app_class = importlib.import_module(app_name, package="apps") obj = getattr(app_class, name) instance = obj(context, **kwargs) domain = getattr(instance, 'domain', None) if domain: app.add_domain(domain, instance.App) else: app.add_subapp("/{}/".format(name), instance.App) # TODO: build automatic documentation except ImportError as err: print(err) continue
def setup_routes(app: web.Application, engine): app.router.add_view("/", Root, name="root") auth_api.router.add_view("/", Index, name="index") auth_api.router.add_view("/signup", Signup, name="signup") auth_api.router.add_view("/login", Login, name="login") auth_api.router.add_view("/logout", Logout, name="logout") game_api.router.add_view("/", AddGame, name="add_game") game_api.router.add_view("/list", GameList, name="game_list") game_api.router.add_view("/{game_name}/add", AddPlayerToGame, name="add_player_to_game") game_api.router.add_view("/{game_name}/move", MakeMove, name="make_move") game_api.router.add_view("/{game_name}/board", ShowGameBoard, name="show_game_board") app.add_subapp("/auth/", auth_api) app.add_subapp("/game/", game_api) auth_api["db"] = engine game_api["db"] = engine
async def add_subapp(event, main_app: web.Application) -> None: main_app.add_subapp(URL_BASE, self.frontend_app)
content_type='text/html', text=path.read_text(), ) @routes.post('/timesync') async def timesync(request): body = await request.json() id = body['id'] now = time() * 1000.0 return json_response({ 'jsonrpc': '2.0', 'id': id, 'result': now, }) routes.static('/js', str(Path(__file__).with_name('html') / 'js')) routes.static('/img', str(Path(__file__).with_name('html') / 'img')) routes.static('/d', str(Path(__file__).with_name('html') / 'd')) routes.static('/m', str(Path(__file__).with_name('html') / 'm')) routes.static('/obj', str(Path(__file__).with_name('html') / 'obj')) alpaca = Application( middlewares=[cors_factory], client_max_size=10 * 1024 * 1024, ) alpaca.router.add_routes(routes) alpaca.add_subapp('/store', http_store)
def main(host, port): app = Application(debug=True) app.add_subapp('/store', http_store) app.router.add_get('/', index) run_app(app, host=host, port=port)
async def add_subapp(self, event, app: web.Application) -> None: """Adds the auth subapp to the api""" app.add_subapp("/auth", self.auth_app)
"""Sanic web application main.""" from aiohttp.web import Application, AppRunner, Request, Response, RouteTableDef, TCPSite from .auth import auth_app from .client_dev import dev_routes from .game import game_app app = Application() app.add_subapp('/auth/', auth_app) app.add_subapp('/game/', game_app) app.add_routes(dev_routes) routes = RouteTableDef() @routes.get('/status') async def get_status(request: Request) -> Response: return Response(text="OK") app.add_routes(routes) async def run_app(host: str, port: int) -> None: runner = AppRunner(app) await runner.setup() site = TCPSite(runner, host, port) await site.start()