Ejemplo n.º 1
0
def main(arguments):
    """
    Run with argparse configuration.
    """
    app = web.Application(middlewares=(cors_middleware(allow_all=True),
                                       error_middleware()))
    app.add_routes([
        web.get('/info', route_info),
        web.get('/available_tests', route_available),
        web.get('/spec/{testname}', route_spec),
        web.post('/run', route_run),
        web.get('/jobs', route_jobs),
        web.get('/jobs/{status}', route_jobs_with_status),
        web.get('/jobs/range/{min}/{max}', route_jobs_in_range),
        web.get('/submissions', route_submissions),
        web.get('/submissions/{status}', route_submissions_with_status),
        web.get('/submissions/range/{min}/{max}', route_submissions_in_range),
        web.get('/job/{job_id}', route_one_job),
        web.get('/job/{job_id}/log/{logfile}', route_one_job_log),
        web.get('/job/{job_id}/lograw/{logfile}', route_one_job_lograw),
        web.get('/submission/{sub_id}', route_one_submission),
        web.get('/submission_jobs/{sub_id}', route_one_submission_jobs),
        web.post('/cancel_job/{job_id}', route_cancel_job),
        web.post('/cancel_submission/{sub_id}', route_cancel_submission)
    ])
    app.on_startup.append(do_before)
    app.on_cleanup.append(do_after)
    web.run_app(app,
                port=arguments.port,
                reuse_port=True,
                host=arguments.host,
                reuse_address=True,
                print=None)
async def test_default_handler(aiohttp_client):
    app = web.Application(middlewares=[error_middleware()])
    client = await aiohttp_client(app)

    response = await client.get("/does-not-exist.exe")
    assert response.content_type == "application/json"
    assert response.status == 404
    assert await response.json() == {"detail": "Not Found"}
Ejemplo n.º 3
0
def create_app(argv: List[str] = None) -> web.Application:
    """Create aiohttp applicaiton for OpenAPI 3 Schema.

    The ``petstore-expanded.yaml`` schema taken from OpenAPI 3 Specification
    examples directory and used inside the app without modifications besides
    changing default server URL to use.

    As pets storage is a simple list, it will be cleared on each application
    shutdown.

    This aiohttp application is ready to be run as:

    .. code-block:: bash

        python -m aiohttp.web petstore.app:create_app

    After application is running, feel free to use Swagger UI to check the
    results. The OpenAPI schema will be available at:
    http://localhost:8080/api/openapi.yaml

    To ensure that Swagger UI been able to make requests to the PetStore
    example app CORS headers allowed for all requests. **Please, avoid
    enabling CORS headers for all requests at production.**
    """
    # Setup logging
    setup_logging(
        default_logging_dict("aiohttp", "aiohttp_middlewares", "petstore",
                             "rororo"),
        remove_root_handlers=True,
    )

    # Create new aiohttp application with CORS & error middlewares
    app = web.Application(middlewares=(
        # CORS middleware should be the first one as it ensures that every
        # aiohttp response use proper CORS headers
        cors_middleware(allow_all=True),
        # It's good practice to enable error middleware right after the
        # CORS one to catch as many errors as possible
        error_middleware(default_handler=views.error),
    ))

    # Create the "storage" for the pets
    app["pets"] = []

    # Setup OpenAPI schema support for aiohttp application
    setup_openapi(
        # Where first param is an application instance
        app,
        # Second is path to OpenAPI 3 Schema
        Path(__file__).parent / "petstore-expanded.yaml",
        # And after list of operations
        views.operations,
        # Need to add route prefix if server URL in OpenAPI schema ended with
        # a path, like "http://localhost:8080/api"
        route_prefix="/api",
    )

    return app
async def test_ignore_exceptions(aiohttp_client, ignore_exceptions):
    app = web.Application(
        middlewares=[error_middleware(ignore_exceptions=ignore_exceptions)])
    client = await aiohttp_client(app)

    response = await client.get("/does-not-exist.exe")
    assert response.content_type == "text/plain"
    assert response.status == 404
    assert await response.text() == "404: Not Found"
async def test_single_handler(aiohttp_client):
    app = web.Application(
        middlewares=[error_middleware(default_handler=error)])
    client = await aiohttp_client(app)

    response = await client.get("/does-not-exist.exe")
    assert response.content_type == "text/plain"
    assert response.status == 404
    assert await response.text() == "Not Found"
Ejemplo n.º 6
0
def run(wsgi=True):
    app = web.Application(middlewares=(
        cors_middleware(origins=("http://localhost:%s" % CLIENT_PORT,
                                 "http://localhost:%s" % PORT),
                        allow_credentials=True),
        error_middleware(),
    ))

    setup_routes(app, web)

    if wsgi:
        return app

    web.run_app(app, host=HOST, port=PORT)
Ejemplo n.º 7
0
async def create_app() -> web.Application:
    """Create a web application."""
    app = web.Application(middlewares=[
        cors_middleware(allow_all=True),
        error_middleware(),  # default error handler for whole application
    ])
    app.add_routes([
        web.view("/ping", Ping),
        web.view("/ready", Ready),
        web.view("/validator", Validator),
        web.view("/shapes", ShapesCollection),
        web.view("/shapes/{id}", Shapes),
        web.view("/ontologies", Ontologies),
        web.view("/ontologies/{id}", Ontology),
    ])

    # logging configurataion:
    logging.basicConfig(
        format=
        "%(asctime)s,%(msecs)d %(levelname)s - %(module)s:%(lineno)d: %(message)s",
        datefmt="%H:%M:%S",
        level=LOGGING_LEVEL,
    )
    logging.getLogger("chardet.charsetprober").setLevel(logging.INFO)

    async def redis_context(app: Any) -> Any:
        # Enable cache in all other cases than test:
        if CONFIG in {"test", "dev"}:
            cache = None
        else:  # pragma: no cover
            cache = RedisBackend(
                "aiohttp-cache",
                address=f"redis://{REDIS_HOST}",
                password=REDIS_PASSWORD,
                expire_after=timedelta(days=1),
            )
        app["cache"] = cache

        yield

        if cache:  # pragma: no cover
            await cache.close()

    app.cleanup_ctx.append(redis_context)

    return app
Ejemplo n.º 8
0
def create_app(argv: List[str] = None) -> web.Application:
    app = web.Application(
        middlewares=(
            cors_middleware(allow_all=True),
            error_middleware(default_handler=views.error),
        )
    )

    setup_openapi(
        app,
        Path(__file__).parent / "openapi.yaml",
        views.operations,
        route_prefix="/api",
        is_validate_response=True,
    )

    return app
async def test_multiple_handlers(aiohttp_client, path, expected_status,
                                 expected_content_type, expected_text):
    app = web.Application(middlewares=[
        error_middleware(
            default_handler=error,
            config={
                "/no-error-context/": no_error_context,
                re.compile(r"^/api"): api_error,
            },
        )
    ])
    app.router.add_get("/legal/", legal)
    app.router.add_get("/api/legal/", legal)

    client = await aiohttp_client(app)
    response = await client.get(path)
    assert response.status == expected_status
    assert response.content_type == expected_content_type
    assert await response.text() == expected_text
Ejemplo n.º 10
0
async def create_app():
    app = web.Application(middlewares=(
        cors_middleware(allow_all=True),
        error_middleware(),
    ))

    fernet_key = fernet.Fernet.generate_key()
    secret_key = base64.urlsafe_b64decode(fernet_key)
    setup(app, EncryptedCookieStorage(secret_key))

    provider = MacAulayProvider(TARGET_SPECIES)
    app["quiz_controller"] = QuizController(provider)

    api = await create_api()
    app.add_subapp("/api", api)

    logger.debug("App creation completed")

    return app