def test_register_graphql_handlers_raises():
    from tartiflette_aiohttp import register_graphql_handlers

    app = {}

    with pytest.raises(Exception):
        register_graphql_handlers(app)

    with pytest.raises(Exception):
        register_graphql_handlers(app, engine=Mock())
def main():
    loop = asyncio.get_event_loop()

    # Init aiohttp
    app = web.Application()

    # Suscribe on_shutdown to the SHUTDOWN event of the app
    app.on_shutdown.append(on_shutdown)

    register_graphql_handlers(app, engine_sdl="starwars/sdl/starwars.sdl")

    # Bind aiohttp to asyncio
    web.run_app(app, host="0.0.0.0", port="8089")
    return 0
Exemple #3
0
async def test_engine_composition(aiohttp_client, loop):
    @Resolver("Query.bob", schema_name="test_engine_composition")
    async def resolver_lol(*args, **kwargs):
        return {"name": "a", "surname": "b"}

    class myEngine:
        def __init__(self):
            self._engine = Engine()

        async def cook(self, *args, **kwargs):
            await self._engine.cook(*args, **kwargs)

        async def execute(self, *args, **kwargs):
            return await self._engine.execute(*args, **kwargs)

    app = register_graphql_handlers(
        app=web.Application(),
        engine=myEngine(),
        engine_sdl=
        """type Query { bob: Ninja } type Ninja { name: String surname: String }""",
        engine_schema_name="test_engine_composition",
    )

    client = await aiohttp_client(app)
    resp = await client.post(
        "/graphql",
        data=json.dumps({"query": "query lol { bob { name surname } }"}),
        headers={"content-type": "application/json"},
    )
    assert resp.status == 200
    result = await resp.json()
    assert result == {"data": {"bob": {"name": "a", "surname": "b"}}}
async def test_header_context_var(aiohttp_client, loop):
    @Resolver("Query.bob", schema_name="test_header_context_var")
    async def resolver_lol(*args, **kwargs):
        set_response_headers({"X-Test": "Lol", "Z-Test": "Ninja"})
        return {"name": "a", "surname": "b"}

    class myEngine(Engine):
        def __init__(self):
            super().__init__()

        async def cook(self, *args, **kwargs):
            await super().cook(*args, **kwargs)

    app = register_graphql_handlers(
        app=web.Application(),
        engine=myEngine(),
        engine_sdl="""type Query { bob: Ninja } type Ninja { name: String surname: String }""",
        engine_schema_name="test_header_context_var",
    )

    client = await aiohttp_client(app)
    resp = await client.post(
        "/graphql",
        data=json.dumps({"query": "query lol { bob { name surname } }"}),
        headers={"content-type": "application/json"},
    )
    assert resp.status == 200
    result = await resp.json()
    assert result == {"data": {"bob": {"name": "a", "surname": "b"}}}
    assert resp.headers["X-Test"] == "Lol"
    assert resp.headers["Z-Test"] == "Ninja"
Exemple #5
0
def main(args=None) -> None:
    """
    Entry point of the application.
    """
    parser = ArgumentParser(description="CONtrol system Interface over graphQL")
    parser.add_argument(
        "config_paths",
        metavar="PATH",
        type=Path,
        nargs="*",
        help="Paths to .coniql.yaml files describing Channels and Devices",
    )
    parsed_args = parser.parse_args(args)

    context = make_context(*parsed_args.config_paths)
    app = register_graphql_handlers(
        app=web.Application(),
        executor_context=context,
        executor_http_endpoint="/graphql",
        subscription_ws_endpoint="/ws",
        graphiql_enabled=True,
        engine=make_engine(),
    )
    cors = aiohttp_cors.setup(app)
    for route in app.router.routes():
        allow_all = {
            # Allow connections from cs-web-proto dev server
            "http://localhost:3000": aiohttp_cors.ResourceOptions(
                allow_headers=("*"), max_age=3600, allow_credentials=True
            )
        }
        cors.add(route, allow_all)

    web.run_app(app)
Exemple #6
0
def app_factory() -> web.Application:
    '''
    Config APP 
    '''
    app = web.Application()
    app['config'] = config
    app['logger'] = logging.getLogger()

    app.on_startup.append(init_db)
    app.on_cleanup.append(close_db)
    handler_config = {
        'app': app,
        'engine_sdl': 'sdl',
        'executor_http_endpoint': '/graphql',
        'executor_http_methods': ['GET', 'POST'],
        'engine_modules': [
            'apps.resolvers.query_resolvers',
            'apps.resolvers.mutation_resolvers',
            'apps.resolvers.subscription_resolvers',
            'apps.directives.rate_limiting',
            'apps.directives.auth'
        ],
        'graphiql_enabled': True
    }
    handler_app = register_graphql_handlers(**handler_config)
    
    return handler_app
Exemple #7
0
def build(db):
    app = web.Application(middlewares=[jwt_middleware])
    app.db = db
    context = Ctx(db=db, app=app, loop=None)
    app = register_graphql_handlers(
        app=app,
        engine=CustomEngine(),
        engine_sdl=f"{here}/sdl/",
        executor_context=context,
        executor_http_endpoint="/",
        executor_http_methods=["POST", "GET"],
        graphiql_enabled=True,
    )
    cors = aiohttp_cors.setup(
        app,
        defaults={
            "*":
            aiohttp_cors.ResourceOptions(allow_credentials=True,
                                         expose_headers="*",
                                         allow_headers="*")
        },
    )
    for route in list(app.router.routes()):
        cors.add(route)

    async def on_startup(app):
        context["loop"] = asyncio.get_event_loop()

    app.on_startup.append(on_startup)
    return app
Exemple #8
0
def run_app() -> None:
    """
    Entry point of the application.
    """

    generate_db(os.environ.get("DB"))

    app = web.Application()

    # Once the server starts connect with all
    # subscribed chats and log messages on the
    # Chat table
    app.on_startup.append(init_subscriptions)

    web.run_app(
        register_graphql_handlers(
            app=app,
            engine_sdl=os.path.dirname(os.path.abspath(__file__)) + "/sdl",
            engine_modules=[
                "project.api.resolvers.query",
                "project.api.resolvers.subscription",
                "project.api.resolvers.mutation",
            ],
            executor_http_endpoint="/graphql",
            executor_http_methods=["POST"],
            graphiql_enabled=True,
            subscription_ws_endpoint="/ws",
        ))
async def test_register_response_formatter(loop):
    @Resolver("Query.bob", schema_name="test_register_response_formatter")
    async def resolver_lol(*args, **kwargs):
        return {"name": "a", "surname": "b"}

    class myEngine(Engine):
        def __init__(self):
            super().__init__()

        async def cook(self, *args, **kwargs):
            await super().cook(*args, **kwargs)

    def response_formatter():
        pass

    app = register_graphql_handlers(
        app=web.Application(),
        engine=myEngine(),
        engine_sdl=
        """type Query { bob: Ninja } type Ninja { name: String surname: String }""",
        engine_schema_name="test_register_response_formatter",
        response_formatter=response_formatter,
    )

    assert app["response_formatter"] is response_formatter
Exemple #10
0
async def init(app):
    log.critical("Loading GraphQL SDL and install resolvers...")

    engine = app["engine"] = Engine(
        os.path.join(os.path.dirname(os.path.abspath(__file__)), "sdl"),
        modules=["gen3.peregrine.resolvers"],
    )
    register_graphql_handlers(
        app=app,
        engine=engine,
        subscription_ws_endpoint=f"{config.PEREGRINE_PREFIX}ws",
        executor_http_endpoint=f"{config.PEREGRINE_PREFIX}graphql",
        executor_http_methods=["POST"],
        graphiql_enabled=config.PEREGRINE_GRAPHIQL,
        graphiql_options=dict(endpoint=f"{config.PEREGRINE_PREFIX}graphiql"),
    )
    return engine
def run():
    app = web.Application()
    app = register_graphql_handlers(
        app=app,
        engine_sdl=f"{here}/sdl/",
        engine_modules=[ApolloFederationPlugin(engine_sdl=f"{here}/sdl/")],
        executor_http_endpoint="/graphql",
        executor_http_methods=["POST"],
        graphiql_enabled=True,
    )
    web.run_app(app, port=PORT)
Exemple #12
0
def run() -> None:
    web.run_app(
        register_graphql_handlers(
            app=web.Application(),
            engine_sdl=os.path.dirname(os.path.abspath(__file__)) + "/sdl",
            engine_modules=[
                "query_resolvers",
            ],
            executor_http_endpoint="/graphql",
            executor_http_methods=["POST"],
            graphiql_enabled=True,
        ))
Exemple #13
0
def run() -> None:
    """
    Entry point of the application.
    """
    web.run_app(
        register_graphql_handlers(
            app=web.Application(),
            engine_sdl=os.path.dirname(os.path.abspath(__file__)) + "/sdl",
            engine_modules=[
                "search_service.query_resolvers",
                "search_service.directives.auth",
            ],
            executor_http_endpoint="/graphql",
            executor_http_methods=["POST"],
            graphiql_enabled=True,
        ))
Exemple #14
0
def run() -> None:
    """Entry point of the application."""
    configure_logger(Path("."), "ceiba")
    args = read_cli_args()
    web.run_app(
        register_graphql_handlers(app=web.Application(),
                                  executor_context=create_context(args),
                                  engine_sdl=(PATH_LIB /
                                              "sdl").absolute().as_posix(),
                                  engine_modules=[
                                      "ceiba.query_resolvers",
                                      "ceiba.mutation_resolvers",
                                  ],
                                  executor_http_endpoint="/graphql",
                                  executor_http_methods=["POST"],
                                  graphiql_enabled=True))
Exemple #15
0
def build(db):
    app = web.Application(middlewares=[jwt_middleware])
    app.db = db
    context = {
        'db': db,
        'app': app,
        'loop': None,
    }
    app = register_graphql_handlers(
        app=app,
        engine=CustomEngine(),
        engine_sdl=sdl_files,
        executor_context=context,
        executor_http_endpoint='/',
        executor_http_methods=[
            'POST',
            'GET',
        ],
        engine_modules=[ApolloFederationPlugin(engine_sdl=sdl_files)],
        graphiql_enabled=os.getenv("DISABLE_GRAPHIQL", True),
        graphiql_options={
            "default_query": GRAPHIQL_QUERY,
            "default_variables": {},
            "default_headers": {
                "Authorization": "Bearer " +
                os.getenv("GRAPHIQL_DEFAULT_JWT", "")
            } if os.getenv("GRAPHIQL_DEFAULT_JWT") else {},
        },
    )
    cors = aiohttp_cors.setup(app,
                              defaults={
                                  "*":
                                  aiohttp_cors.ResourceOptions(
                                      allow_credentials=True,
                                      expose_headers="*",
                                      allow_headers="*",
                                  )
                              })
    for route in list(app.router.routes()):
        cors.add(route)

    async def on_startup(app):
        context.update({'loop': asyncio.get_event_loop()})

    app.on_startup.append(on_startup)
    return app
Exemple #16
0
def run():
    web.run_app(
        register_graphql_handlers(
            app=web.Application(),
            engine_sdl=os.path.dirname(os.path.abspath(__file__)) + '/sdl',
            engine_modules=[
                'recipes_manager.query_resolvers',
                'recipes_manager.mutation_resolvers',
                'recipes_manager.subscription_resolvers',
                'recipes_manager.directives.rate_limiting',
                "recipes_manager.directives.auth"
            ],
            executor_http_endpoint='/graphql',
            executor_http_methods=['POST', 'GET'],
            graphiql_enabled = True,
            subscription_ws_endpoint='/ws'
        )
    )
def test_register_graphql_handlers():
    from tartiflette_aiohttp import register_graphql_handlers
    from functools import partial
    from tartiflette_aiohttp._handler import Handlers

    class app(dict):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)

            self.router = Mock()
            self.router.add_route = Mock()
            self.on_startup = []

    a = app()
    an_engine = Mock()

    assert register_graphql_handlers(a, engine=an_engine) == a
    assert a["ttftt_engine"] == an_engine
    assert a.router.add_route.called
Exemple #18
0
def run() -> None:
    """Entry point for graphql server."""
    port = os.getenv('PORT', standart_port)
    graphiql = str_to_bool(os.getenv('GRAPHIQL', 'True'))

    web.run_app(
        register_graphql_handlers(
            app=init_app(),
            engine_sdl=initialize_sdl(),
            engine_modules=[
                'algernon.api.query_resolvers',
                'algernon.api.mutation_resolvers',
            ],
            executor_http_endpoint='/graphql',
            executor_http_methods=['POST'],
            graphiql_enabled=graphiql,
        ),
        port=port,
    )
def run() -> None:
    """
    Entry point of the application.
    """
    web.run_app(
        register_graphql_handlers(
            app=web.Application(),
            engine_sdl=os.path.dirname(os.path.abspath(__file__)) + "/sdl",
            engine_modules=[
                "recipes_manager.query_resolvers",
                "recipes_manager.mutation_resolvers",
                "recipes_manager.subscription_resolvers",
                "recipes_manager.directives.rate_limiting",
            ],
            executor_http_endpoint="/graphql",
            executor_http_methods=["POST"],
            graphiql_enabled=True,
            subscription_ws_endpoint="/ws",
        ))
Exemple #20
0
def run() -> None:
    """
    Entry point of the application.
    """

    app = register_graphql_handlers(
        app=web.Application(),
        engine_sdl=os.path.dirname(os.path.abspath(__file__)) + "/sdl",
        engine_modules=[
            "server.query_resolvers",
        ],
        executor_http_endpoint="/graphql/",
        executor_http_methods=["POST"],
        graphiql_enabled=False,
    )

    # `aiohttp_cors.setup` returns `aiohttp_cors.CorsConfig` instance.
    # The `cors` instance will store CORS configuration for the
    # application.
    cors = aiohttp_cors.setup(app,
                              defaults={
                                  "*":
                                  aiohttp_cors.ResourceOptions(
                                      allow_credentials=True,
                                      expose_headers="*",
                                      allow_headers="*",
                                      allow_methods=["POST", "OPTIONS"])
                              })

    # Configure CORS on all routes.
    for route in list(app.router.routes()):
        cors.add(route)

    logging.basicConfig(level=logging.INFO)

    web.run_app(
        app,
        host="0.0.0.0",
        port=4000,
    )
Exemple #21
0
async def test_awaitable_engine(aiohttp_client, loop):
    @Resolver("Query.bob", schema_name="test_awaitable_engine")
    async def resolver_lol(*args, **kwargs):
        return {"name": "a", "surname": "b"}

    app = register_graphql_handlers(
        app=web.Application(),
        engine=create_engine(
            """type Query { bob: Ninja } type Ninja { name: String surname: String }""",
            schema_name="test_awaitable_engine",
        ),
    )

    client = await aiohttp_client(app)
    resp = await client.post(
        "/graphql",
        data=json.dumps({"query": "query lol { bob { name surname } }"}),
        headers={"content-type": "application/json"},
    )
    assert resp.status == 200
    result = await resp.json()
    assert result == {"data": {"bob": {"name": "a", "surname": "b"}}}
Exemple #22
0
def create_app() -> Any:
    """
    Returns the app for the api.
    """
    app = register_graphql_handlers(
        app=web.Application(),
        engine_sdl=os.path.dirname(os.path.abspath(__file__)) + "/sdl",
        engine_modules=[
            "api.query_resolvers",
            "api.directives.rate_limiting",
        ],
        executor_http_endpoint="/graphql",
        executor_http_methods=["POST"],
        graphiql_enabled=True,
        graphiql_options=__graphiql_options)

    app.add_routes([web.get('/', index)])

    # allow only the api per default
    cors = aiohttp_cors.setup(
        app,
        defaults={
            '*':
            aiohttp_cors.ResourceOptions(
                # os.getenv('ACCESS_CONTROL_ORIGIN', 'https://kurodoko.xyz'): aiohttp_cors.ResourceOptions(
                allow_credentials=True,
                expose_headers="*",
                allow_headers="*",
            )
        })

    # Configure CORS on all routes.
    for route in list(app.router.routes()):
        # if not isinstance(route.resource, web.StaticResource):  # <<< WORKAROUND
        cors.add(route)

    return app
Exemple #23
0
        modules={'aiohttpdemo_polls': ['aiohttpdemo_polls.models']})


async def close_connection(_=None):
    await Tortoise.close_connections()


if __name__ == '__main__':
    app = web.Application()
    setup_routes(app)
    app.on_startup.append(init_connection)
    app.on_cleanup.append(close_connection)

    web.run_app(
        register_graphql_handlers(
            app=app,
            engine_sdl=os.path.join(settings.BASE_DIR, 'aiohttpdemo_polls',
                                    'graphql', 'sdl'),
            engine_modules=[
                "aiohttpdemo_polls.graphql.query_resolvers",
                "aiohttpdemo_polls.graphql.mutation_resolvers",
                "aiohttpdemo_polls.graphql.subscription_resolvers",
                "aiohttpdemo_polls.graphql.directives.rate_limiting",
                "aiohttpdemo_polls.graphql.directives.auth",
            ],
            executor_http_endpoint="/graphql",
            executor_http_methods=["POST"],
            graphiql_enabled=True,
            subscription_ws_endpoint="/ws",
        ))
import os

from aiohttp import web
from tartiflette_aiohttp import register_graphql_handlers

from {{cookiecutter.project_slug}}.settings import Settings

settings = Settings()
app = web.Application()
registered_handlers = register_graphql_handlers(
    app=app,
    engine_sdl=settings.TARTIFLETTE_SDL_PATH,
    engine_modules=settings.TARTIFLETTE_MODULES,
    **settings.TARTIFLETTE_CONFIG
)

def run():
    web.run_app(registered_handlers)

# For liveroload only
async def create_app():
    return registered_handlers
Exemple #25
0
async def resolver_playlists(ctx, ids, *a, **kwargs):
    result = await _load_playlists(ids)
    return result


@Resolver("Query.tracks")
async def resolver_tracks(ctx, ids, *a, **kwargs):
    result = await _load_tracks(ids)
    return result


@Resolver("Playlist.tracks")
async def _load_tracks_for_playlist(ctx, ids, *a, **kwargs):
    result = await _load_tracks(ids)
    return result


# @Resolver("Track")
# async def load_tracks(ctx, ids, *a, **kwargs):
#     result = await _load_tracks(ids)
#     return result

web.run_app(
    register_graphql_handlers(
        web.Application(),
        engine_sdl=type_defs,
        executor_http_methods=["POST", "GET"],
    ),
    port="8000",
)
Exemple #26
0
def main():
    loop = asyncio.get_event_loop()

    # Init aiohttp
    app = web.Application()

    # Suscribe on_shutdown to the SHUTDOWN event of the app
    app.on_shutdown.append(_on_shutdown)

    register_graphql_handlers(
        app,
        "schema.graphql",
        subscription_ws_endpoint="/ws",
        graphiql_enabled=True,
        graphiql_options={
            "default_query": """fragment DogFields on Dog {
  id
  name
  nickname
}

query Dog($dogId: Int!) {
  dog(id: $dogId) {
    ...DogFields
  }
}

mutation AddDog($addInput: AddDogInput!) {
  addDog(input: $addInput) {
    clientMutationId
    status
    dog {
      ...DogFields
    }
  }
}

mutation UpdateDog($updateInput: UpdateDogInput!) {
  updateDog(input: $updateInput) {
    clientMutationId
    status
    dog {
      ...DogFields
    }
  }
}

subscription DogAdded {
  dogAdded {
    ...DogFields
  }
}

subscription DogUpdated($dogId: Int!) {
  dogUpdated(id: $dogId) {
    ...DogFields
  }
}""",
            "default_variables": {
                "dogId": 1,
                "addInput": {
                    "clientMutationId": "addDog",
                    "name": "Dog #2",
                    "nickname": None,
                },
                "updateInput": {
                    "clientMutationId": "updateDog",
                    "id": 2,
                    "name": "Dog #2.1",
                    "nickname": None,
                },
            },
        },
    )

    # Bind aiohttp to asyncio
    logger.error("Let's go.")

    web.run_app(app, host="0.0.0.0", port="8090")

    return 0
Exemple #27
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os

from aiohttp import web
from tartiflette import Engine
from tartiflette_aiohttp import register_graphql_handlers

import trello_to_graphql.resolvers

engine = Engine([
    os.path.dirname(os.path.abspath(__file__)) +
    "/trello_to_graphql/sdl/queries.sdl"
])
ctx = {}

web.run_app(
    register_graphql_handlers(
        app=web.Application(),
        engine=engine,
        executor_context=ctx,
        executor_http_endpoint="/graphql",
        executor_http_methods=["POST", "GET"],
        graphiql_enabled=True,
    ))