コード例 #1
0
def create_app() -> Application:
    """
    Создает экземпляр приложения, готового к запуску
    """
    # TODO добавить middlewares для вадидации полей сообщений
    app = Application(client_max_size=MAX_REQUEST_SIZE,
                      # middlewares=[check_token_middleware]
                      )
    aiohttp_cors.setup(app,
                       defaults={
                           "*":
                           aiohttp_cors.ResourceOptions(
                               allow_credentials=True,
                               expose_headers="*",
                               allow_headers="*",
                           )
                       })
    app.cleanup_ctx.append(setup_pg)

    # Регистрация обработчика
    for handler in HANDLERS:
        log.debug('Registering handler %r as %r', handler, handler.URL_PATH)

        route = app.router.add_route('*', handler.URL_PATH, handler)

        app['aiohttp_cors'].add(route)

    setup_aiohttp_apispec(app=app, title="I SEE YOU API", swagger_path='/')

    # Автоматическая сериализация в json данных в HTTP ответах
    PAYLOAD_REGISTRY.register(AsyncGenJSONListPayload,
                              (AsyncGeneratorType, AsyncIterable))
    PAYLOAD_REGISTRY.register(JsonPayload, (Mapping, MappingProxyType))
    return app
コード例 #2
0
async def init(loop):
    # Setup app.
    app = web.Application()

    # Setup routes
    for route in api.routes.routes:
        app.router.add_route(*route)

    # Setup DB connection
    await init_db()
    db = Gino()
    db.init_app(
        app,
        config={
            "user": "******",
            "password": "",
            "database": "gino",
            "host": "postgres"})

    # Setup middlewares
    middlewares = [
        db, validation_middleware, auth_middleware]
    app.middlewares.extend(middlewares)

    # Setup api_spec
    setup_aiohttp_apispec(
        app=app,
        title="Joke's API documentation",
        version='v1',
        url="/api/v1/docs/swagger.json",
        swagger_path="/api/v1/docs/")
    host = "0.0.0.0"
    port = 80
    return app, host, port
コード例 #3
0
def create_app():
    #loop = asyncio.get_event_loop()
    #pool = loop.run_until_complete(init())
    app = web.Application()
    app['config'] = os.environ
    url = yarl.URL(app['config']["REDIS_CACHE"])
    # setup_cache(
    #     app,
    #     cache_type="redis",
    #     backend_config=RedisConfig(
    #         db=int(url.path[1:]), host=url.host, port=url.port
    #         ),
    # )

    app.on_startup.append(setup_logging)
    app.on_startup.append(init_pg)
    app.add_routes(routes)
    app.middlewares.append(validation_middleware)
    setup_aiohttp_apispec(app=app,
                          request_data_name='validated_data',
                          title='My Documentation',
                          version='v1',
                          url='/v1/api/docs/api-docs')
    app.on_startup.append(swagger)
    app.on_cleanup.append(close_pg)

    return app
コード例 #4
0
ファイル: app.py プロジェクト: kudddy/CheckFaceSys
def create_app() -> Application:
    """
    Создает экземпляр приложения, готового к запуску
    """
    # TODO добавить middlewares для вадидации полей сообщений
    app = Application(client_max_size=MAX_REQUEST_SIZE,
                      middlewares=[check_token_middleware])
    app.cleanup_ctx.append(setup_pg)

    app.on_startup.append(startup)
    app.on_shutdown.append(shutdown)

    # регестрируем менеджер кеша
    app['cache'] = CacheManager()
    app['encoders'] = EncoderManager()

    # Регистрация обработчика
    for handler in HANDLERS:
        log.debug('Registering handler %r as %r', handler, handler.URL_PATH)
        app.router.add_route('*', handler.URL_PATH, handler)

    setup_aiohttp_apispec(app=app, title="GROUP BY FACE API", swagger_path='/')

    # Автоматическая сериализация в json данных в HTTP ответах
    PAYLOAD_REGISTRY.register(AsyncGenJSONListPayload,
                              (AsyncGeneratorType, AsyncIterable))
    PAYLOAD_REGISTRY.register(JsonPayload, (Mapping, MappingProxyType))
    return app
コード例 #5
0
async def init_app():
    jwt_middleware = create_jwt_middleware()
    current_user_middleware = create_current_user_middleware()
    cors_middleware = create_cors_middleware()
    app = web.Application(
        middlewares=[cors_middleware, jwt_middleware, current_user_middleware])
    setup_routes(app)

    setup_aiohttp_apispec(app=app,
                          title="Family service",
                          version="v1",
                          swagger_path='/swagger-ui',
                          securityDefinitions={
                              "jwt": {
                                  "type": "apiKey",
                                  "schema": "bearer",
                                  "bearerFormat": "JWT",
                                  "name": "Authorization",
                                  "in": "header"
                              }
                          },
                          security=[{
                              "jwt": []
                          }])
    app['db'] = await create_db_connection()
    app.on_cleanup.append(close_pg)
    return app
コード例 #6
0
async def init_app(*argv):
    """
    Initialize app
    :return:
    """
    redis_pool = await aioredis.create_redis_pool('redis://localhost/0')

    middlewares = [
        core_middlewares.validation_error_middleware,
        auth_middlewares.auth_middleware,
        validation_middleware,
    ]

    app = web.Application(middlewares=middlewares)
    app['redis'] = redis_pool
    await db.set_bind(settings.DATABASE_URL)

    # Auto create tables
    await db.gino.create_all()

    app.router.add_routes(loaders.discover_urls())
    setup_aiohttp_apispec(app=app,
                          title='Refactored Adventure',
                          version='v1',
                          url='/api/docs/api-docs')
    app.on_startup.append(swagger)
    return app
コード例 #7
0
    async def start(self, port: int = None):
        """ Starts the HTTP control server. """

        # setup for automated swagger docs
        setup_aiohttp_apispec(
            self._app,
            title=f"TorScraper {self.container.service_type.value}",
            version=self.container.version,
            securityDefinitions={
                "jwt_token": {
                    "in": "header",
                    "type": "apiKey",
                    "name": "Authorization",
                    "description": "Format: `Bearer {JWT_TOKEN}`",
                }
            },
            **AppConfig.get("control_server.docs"),
        )

        import itertools
        self._tasks = list(
            itertools.chain(await asyncio.gather(*self._task_registrators)))

        await self._runner.setup()
        server_config = AppConfig.get("control_server.site")
        if port is not None:
            server_config["port"] = port

        log.debug("starting the control server, using config=%s",
                  server_config)
        self._site = web.TCPSite(self._runner, **server_config)
        await self._site.start()
        log.debug("started the control server")
コード例 #8
0
def create_app(args: Namespace) -> Application:
    """
    Создает экземпляр приложения, готового к запуску.
    """
    app = Application(
        client_max_size=MAX_REQUEST_SIZE,
        middlewares=[error_middleware, validation_middleware]
    )

    # Подключение на старте к postgres и отключение при остановке
    app.cleanup_ctx.append(partial(setup_pg, args=args))

    # Регистрация обработчиков
    for handler in HANDLERS:
        log.debug('Registering handler %r as %r', handler, handler.URL_PATH)
        app.router.add_route('*', handler.URL_PATH, handler)

    # Swagger документация
    setup_aiohttp_apispec(app=app, title='Citizens API', swagger_path='/',
                          error_callback=handle_validation_error)

    # Автоматическая сериализация в json данных в HTTP ответах
    PAYLOAD_REGISTRY.register(AsyncGenJSONListPayload,
                              (AsyncGeneratorType, AsyncIterable))
    PAYLOAD_REGISTRY.register(JsonPayload, (Mapping, MappingProxyType))
    return app
コード例 #9
0
    async def start(self, ip='0.0.0.0', port=8000):
        """
        Starts the HTTP API with the listen port as specified in the session configuration.
        """

        print("STARTING REST")

        root_endpoint = RootEndpoint(middlewares=[cors_middleware])
        root_endpoint.initialize(self.session)
        setup_aiohttp_apispec(
            app=root_endpoint.app,
            title="IPv8 REST API documentation",
            version="v1.9",
            url="/docs/swagger.json",
            swagger_path="/docs",
        )

        from apispec.core import VALID_METHODS_OPENAPI_V2
        if 'head' in VALID_METHODS_OPENAPI_V2:
            VALID_METHODS_OPENAPI_V2.remove('head')

        runner = web.AppRunner(root_endpoint.app, access_log=None)
        await runner.setup()
        # If localhost is used as hostname, it will randomly either use 127.0.0.1 or ::1
        self.site = web.TCPSite(runner, ip, port)
        await self.site.start()
コード例 #10
0
def setup_routes(app: Application) -> None:
    """Add routes to app."""
    app.router.add_post('/v1/user_register', user_register.user_register)
    app.router.add_post('/v1/user_info', user_info.user_info)
    app.router.add_post('/v1/wallet_top_up', wallet_top_up.wallet_top_up)
    app.router.add_post(
        '/v1/transaction_between_wallets',
        transaction_between_wallets.transaction_between_wallets,
    )

    app.router.add_post(
        '/v1/transactions_history',
        transactions_history.transactions_history,
    )

    app.router.add_get(
        r'/v1/transaction_logs/{transaction_id:\d+}',
        transaction_logs.transaction_logs,
        allow_head=False,
    )

    setup_aiohttp_apispec(
        app=app,
        title='My Documentation',
        version='v1',
        url='/api/docs/swagger.json',
        swagger_path='/api/docs',
    )
コード例 #11
0
    def __init__(self, config, store):
        self._config = config

        self._app = web.Application()

        self._log = log

        self._app.middlewares.append(request_id_middleware)
        self._app.middlewares.append(
            incoming_request_logger_middleware_factory(self))

        self._app["store"] = store

        self._app.middlewares.append(validation_middleware)

        self._app.router.add_routes(routes)

        self._runner = web.AppRunner(
            self._app, access_log_class=_access_logger_class_builder(self))

        setup_aiohttp_apispec(
            app=self._app,
            title="Heat Spreader HTTP API documentation",
            version="v1",
            url="/api/docs/swagger.json",
            swagger_path="/api/docs",
        )
コード例 #12
0
ファイル: app.py プロジェクト: ihorchikk/crawl-platform
def init_app(config: Optional[List[str]] = None) -> web.Application:
    """ Initializing web application with middlewares, config, routs and etc.

    :param config: Configuration
    :return: Web application
    """
    app = web.Application(
        middlewares=[normalize_path_middleware(), validation_middleware])

    init_config_app(app, config=config)
    init_routes(app)
    app.cleanup_ctx.extend([
        redis,
    ])

    app.on_startup.append(on_start)
    app.on_cleanup.append(gracefully_on_stop)

    setup_aiohttp_apispec(
        app=app,
        title="News project DD-flow",
        version="v1",
        url="/api/docs/swagger.json",
        swagger_path="/api/docs",
    )

    return app
コード例 #13
0
    async def get_application(self):
        """
        Override the get_app method to return your application.
        """
        app = Application()
        app.middlewares.append(error_middleware)
        app.middlewares.append(mock_auth_middleware)
        app.middlewares.append(validation_middleware)

        setup_aiohttp_apispec(
            app=app,
            title='API',
            version=API_VERSION,
            url=f'/{API_VERSION}/api/docs/swagger.json',
            swagger_path=f'/{API_VERSION}/api/docs/ui',
            securityDefinitions={
                'ApiKeyAuth': {
                    'type': 'apiKey',
                    'name': 'X-API-Key',
                    'in': 'header'
                }
            },
        )

        setup_routes(app)
        return app
コード例 #14
0
 def init_routes(self, app: web.Application):
     app.add_routes([
         web.view('/', IndexView),
         web.view('/api/v1/user', UserView),
         web.view('/api/v1/user/{user_id}', GetUserView),
         web.view('/api/v1/reports', ReporterView)
     ])
     setup_aiohttp_apispec(app=app, **self.config['swagger'])
コード例 #15
0
def setup_external_libraries(application: web.Application) -> None:
    setup_aiohttp_apispec(
        app=application,
        title="Своя игра бот. Документация",
        version="v1",
        url="/swagger.json",
        swagger_path="/",
    )
コード例 #16
0
ファイル: main.py プロジェクト: haze518/aiohttp-rest-example
def create_app() -> web.Application:
    app = web.Application()
    setup_routes(app)
    app.on_startup.append(startup)
    app.on_shutdown.append(shutdown)
    setup_aiohttp_apispec(app, swagger_path="/docs")
    app.middlewares.append(validation_middleware)
    return app
コード例 #17
0
def setup_external_libraries(app: web.Application) -> None:
    setup_aiohttp_apispec(
        app=app,
        title="Documentation",
        version="v1",
        url="/swagger.json",
        swagger_path="/swagger",
    )
コード例 #18
0
async def test_register_route_for_relative_url():
    app = web.Application()
    routes_count = len(app.router.routes())
    assert routes_count == 0
    setup_aiohttp_apispec(app=app, url="api/swagger")
    # new route should be registered according to AiohttpApispec.register() method?
    routes_count_after_setup_apispec = len(app.router.routes())
    # not sure why there was a comparison between the old rount_count vs new_route_count
    assert routes_count_after_setup_apispec == 1
コード例 #19
0
ファイル: app.py プロジェクト: Serufim/yandex_backend
async def init_app(argv=None):
    app = web.Application(router=UrlDispatcherEx())
    app['config'] = get_config(argv)
    setup_aiohttp_apispec(app=app, error_callback=my_error_handler)
    app.middlewares.append(validation_middleware)
    app.on_startup.append(init_pg)
    app.on_cleanup.append(close_pg)
    setup_routes(app)
    return app
コード例 #20
0
ファイル: msp.py プロジェクト: off-grid-block/admin
async def main(start_port: int, show_timing: bool = False):
    global agent
    genesis = await default_genesis_txns()
    if not genesis:
        print("Error retrieving ledger genesis transactions")
        sys.exit(1)

    try:
        log_status(
            "Provision an agent and wallet, get back configuration details")
        agent = MSPAgent(start_port,
                         start_port + 1,
                         genesis_data=genesis,
                         timing=show_timing)
        await agent.listen_webhooks(start_port + 2)
        # await agent.register_did()

        with log_timer("Startup duration:"):
            await agent.start_process()
        log_msg("Admin url is at:", agent.admin_url)
        log_msg("Endpoint url is at:", agent.endpoint)

        app = web.Application()
        app.add_routes([
            web.get('/create_invitation', handle_create_invitation),
            web.post('/verify_signature', handle_verify_signature),
            web.post('/verify_proof', handle_verify_proof),
        ])

        cors = aiohttp_cors.setup(
            app,
            defaults={
                "*":
                aiohttp_cors.ResourceOptions(
                    allow_credentials=True,
                    expose_headers="*",
                    allow_headers="*",
                    allow_methods="*",
                )
            },
        )
        for route in app.router.routes():
            cors.add(route)

        setup_aiohttp_apispec(app=app,
                              title="Aries Cloud Agent two",
                              version="v1",
                              swagger_path="/api/doc")
        app.on_startup.append(on_startup)

        return app

    except Exception:
        log_status(
            "Error while provision an agent and wallet, get back configuration details"
        )
コード例 #21
0
async def get_app(swagger=True,
                  doc="/ui",
                  prefix="",
                  static_path="/static/swagger",
                  base_path="",
                  enable_train=True,
                  enable_predict=True):
    """Get the main app."""
    global APP

    if APP:
        return APP

    APP = web.Application(debug=CONF.debug,
                          client_max_size=CONF.client_max_size)

    APP.middlewares.append(web.normalize_path_middleware())

    model.register_v2_models(APP)

    v2app = v2.get_app(enable_train=enable_train,
                       enable_predict=enable_predict)
    APP.add_subapp("/v2", v2app)
    versions.register_version("stable", v2.get_version)

    APP.add_routes(versions.routes)

    LOG.info("Serving loaded V2 models: %s", list(model.V2_MODELS.keys()))

    if CONF.warm:
        for _, m in model.V2_MODELS.items():
            LOG.debug("Warming models...")
            await m.warm()

    if swagger:
        # init docs with all parameters, usual for ApiSpec
        aiohttp_apispec.setup_aiohttp_apispec(
            app=APP,
            title="DEEP as a Service API endpoint",
            info={
                "description": API_DESCRIPTION,
            },
            externalDocs={
                "description": "API documentation",
                "url": "https://deepaas.readthedocs.org/",
            },
            basePath=base_path,
            version=deepaas.__version__,
            url="/swagger.json",
            swagger_path=doc if doc else None,
            prefix=prefix,
            static_path=static_path,
            in_place=True,
        )

    return APP
コード例 #22
0
def init_swagger_documentation(app):
    """Makes swagger documentation available at /api/docs for any endpoints
    marked for aiohttp_apispec documentation.
    """
    aiohttp_apispec.setup_aiohttp_apispec(app=app,
                                          title="CALDERA",
                                          version=version.get_version(),
                                          swagger_path="/api/docs",
                                          url="/api/docs/swagger.json",
                                          static_path="/static/swagger")
コード例 #23
0
def setup_external_libraries(application: web.Application) -> None:
    aiohttp_jinja2.setup(
        application, loader=jinja2.FileSystemLoader(f"{BASE_DIR}/templates"))
    setup_aiohttp_apispec(
        app=application,
        title="Forum documentation",
        version="v1",
        url="/swagger.json",
        swagger_path="/swagger",
    )
コード例 #24
0
async def create_app() -> web.Application:
    """
    Инизиализирует приложение
    :return:
    """
    app = web.Application(middlewares=MIDDLEWARES)
    app.cleanup_ctx.extend(INTEGRATIONS)
    setup_routes(app)
    setup_aiohttp_apispec(app, **settings.APISPEC_CONF)
    return app
コード例 #25
0
ファイル: app.py プロジェクト: avonar/api-gateway
def create_app() -> Application:
    
    app = web.Application()
    logging.basicConfig(level=logging.INFO)

    setup_aiohttp_apispec(app, swagger_path="/docs")
    setup_routes(app)
    app.middlewares.append(validation_middleware)

    return app
コード例 #26
0
    def install(self):
        self._app.add_routes(self._routes)

        setup_aiohttp_apispec(
            app=self._app,
            title="Documentation of gatherproxy_parser_web_service",
            version="v1",
            url="/api/docs/swagger.json",
            swagger_path="/api/docs",
        )
コード例 #27
0
def create_app():
    app = web.Application()
    setup_routes(app)
    # In-memory toy-database:
    app["users"] = []

    setup_aiohttp_apispec(app, swagger_path="/docs")
    app.middlewares.append(validation_middleware)

    return app
コード例 #28
0
def run_app():
    setup_config(app)
    setup_routes(app)
    setup_aiohttp_apispec(app,
                          title='CRM Application',
                          url='/docs/json',
                          swagger_path='/docs')
    setup_middlewares(app)
    setup_accessors(app)
    aiohttp_run_app(app)
コード例 #29
0
def init_app(
    loop: asyncio.AbstractEventLoop,
    redis_pool: Optional[aioredis.ConnectionsPool] = None,
) -> web.Application:
    app = web.Application(loop=loop)

    app['config'] = settings

    if not redis_pool:
        redis_pool = loop.run_until_complete(make_redis_pool())

    storage = RedisStorage(redis_pool, cookie_name='sesssionid')
    setup(app, storage)

    async def dispose_redis_pool(app: web.Application) -> None:
        if redis_pool is not None:
            redis_pool.close()
            await redis_pool.wait_closed()

    aiohttp_jinja2.setup(
        app,
        loader=jinja2.FileSystemLoader(str(BASE_DIR / 'its_on' /
                                           'templates'), ),
    )
    app['static_root_url'] = '/static'

    app.on_startup.append(init_pg)
    app.on_cleanup.append(close_pg)
    app.on_cleanup.append(dispose_redis_pool)

    setup_security(app, SessionIdentityPolicy(session_key='sessionkey'),
                   DBAuthorizationPolicy(app))

    cors_config = {
        origin:
        aiohttp_cors.ResourceOptions(allow_methods=['GET', 'OPTIONS'],
                                     allow_headers=settings.CORS_ALLOW_HEADERS)
        for origin in settings.CORS_ALLOW_ORIGIN
    }
    cors = aiohttp_cors.setup(app, defaults=cors_config)

    setup_routes(app, BASE_DIR, cors)

    setup_aiohttp_apispec(app=app,
                          title='Flags Bestdoctor',
                          version='v1',
                          url='/api/docs/swagger.json',
                          swagger_path='/api/docs',
                          static_path='/assets/swagger',
                          request_data_name='validated_data')
    setup_middlewares(app)
    setup_cache(app)

    return app
コード例 #30
0
def init_swagger_documentation(app):
    """Makes swagger documentation available at /api/docs for any endpoints
    marked for aiohttp_apispec documentation.
    """
    aiohttp_apispec.setup_aiohttp_apispec(app=app,
                                          title='CALDERA',
                                          version=version.get_version(),
                                          swagger_path='/api/docs',
                                          url='/api/docs/swagger.json',
                                          static_path='/static/swagger')
    app.middlewares.append(apispec_request_validation_middleware)
    app.middlewares.append(validation_middleware)