Ejemplo n.º 1
0
async def async_main(conf):
    async with AsyncExitStack() as stack:
        alert_webhooks = await stack.enter_async_context(
            AlertWebhooks(conf.alert_webhooks))
        model = await stack.enter_async_context(
            get_model(conf, alert_webhooks=alert_webhooks))
        alert_webhooks.set_model(model)
        app = Application()
        app['model'] = model
        app.router.add_routes(routes)
        GraphQLView.attach(app,
                           route_path='/graphql',
                           schema=graphql_schema,
                           graphiql=True,
                           enable_async=True,
                           executor=GQLAIOExecutor())
        runner = AppRunner(app)
        await runner.setup()
        host = conf.http_interface.bind_host
        port = conf.http_interface.bind_port
        site = TCPSite(runner, host, port)
        await site.start()
        stop_event = asyncio.Event()
        asyncio.get_running_loop().add_signal_handler(SIGINT, stop_event.set)
        asyncio.get_running_loop().add_signal_handler(SIGTERM, stop_event.set)
        logger.debug('Listening on http://%s:%s', host or 'localhost', port)
        await stop_event.wait()
        logger.debug('Cleanup...')
        t = asyncio.create_task(log_still_running_tasks())
        await runner.cleanup()
        t.cancel()
        logger.debug('Cleanup done')
Ejemplo n.º 2
0
def get_app(extra_argv=None) -> Application:
    config = environ.to_config(Config)

    app = Application()
    app['config'] = config
    aiojobs.aiohttp.setup(app, limit=1)

    app.cleanup_ctx.extend((s3_ctx, mongo_ctx, keycloak_ctx))

    cors = aiohttp_cors.setup(app)
    resource = cors.add(
        app.router.add_resource("/graphql"), {
            "*":
            aiohttp_cors.ResourceOptions(expose_headers="*",
                                         allow_headers="*",
                                         allow_credentials=True,
                                         allow_methods=["POST", "PUT", "GET"]),
        })
    GraphQLView(schema=schema, graphiql=True, executor=AsyncioExecutor())
    resource.add_route(
        "*",
        GraphQLView(schema=schema, graphiql=True, executor=AsyncioExecutor()))
    app.router.add_get('/upload_callback/{id}',
                       upload_callback,
                       name='upload_callback')

    return app
Ejemplo n.º 3
0
    def wsgi_app(self):
        """This method defines all the necesarry to be called from the wsgi"""
        self.build()
        app = web.Application()

        # configure route
        GraphQLView.attach(app,
                           schema=self.schema(),
                           field_resolver=self._resolver,
                           batch=True,
                           graphiql=True)

        if self.config.get('API_CORS', False):
            # enable CORS
            cors = aiohttp_cors.setup(
                app,
                defaults={
                    "*":
                    aiohttp_cors.ResourceOptions(
                        allow_credentials=True,
                        expose_headers=("X-Custom-Server-Header", ),
                        allow_headers=("X-Requested-With", "Content-Type"),
                        max_age=3600,
                    )
                })
            #get_route = app.router.add_route('GET', '/graphql', handler, name='graphql')
            #post_route = app.router.add_route('POST', '/graphql', handler, name='graphql')

            #cors.add(get_route)
            #cors.add(post_route)

        return app
Ejemplo n.º 4
0
def get_app():
    model = Model()
    app = web.Application()
    app.router.add_routes(all_routes)
    app['model'] = model
    GraphQLView.attach(app,
                       route_path='/api/graphql',
                       schema=Schema,
                       graphiql=True,
                       enable_async=True,
                       executor=GQLAIOExecutor())

    subscription_server = AiohttpSubscriptionServer(Schema)

    async def subscriptions(request):
        try:
            ws = web.WebSocketResponse(protocols=('graphql-ws', ))
            await ws.prepare(request)
            await subscription_server.handle(ws, {'request': request})
            return ws
        except Exception as e:
            logger.exception('subscriptions failed: %r', e)
            raise e

    app.router.add_get('/api/subscriptions', subscriptions)
    return app
Ejemplo n.º 5
0
async def async_launch_web():
    app.add_routes(routes)
    logger.debug(
        f'Launch web interface on {config.api.host}:{config.api.port}')
    GraphQLView.attach(app, schema=schema, graphiql=True)
    # await web._run_app(app, port=config['api']['port'])
    runner = web.AppRunner(app)
    await runner.setup()
    site = web.TCPSite(runner, '127.0.0.1', config.api.port)
    await site.start()
Ejemplo n.º 6
0
def make_app():
    fernet_key = fernet.Fernet.generate_key()
    secret_key = base64.urlsafe_b64decode(fernet_key)
    storage = EncryptedCookieStorage(secret_key=secret_key)
    session_midl = session_middleware(storage)
    middlewares = [session_midl]
    app = web.Application(loop=loop, middlewares=middlewares)

    setup(app, EncryptedCookieStorage(secret_key=secret_key))
    app.on_startup.append(init_db)
    GraphQLView.attach(app, schema=schema, graphiql=True, enable_async=True)
    app['config'] = conf['db']
    setup_routes(app)
    app.on_cleanup.append(close_db)
    return app
Ejemplo n.º 7
0
async def startup(app):
    authentication = AuthenticationMiddleware(whitelist=[
        ['registerUser'],
        ['authenticate']
    ])

    # Configure default CORS settings.
    cors = aiohttp_cors.setup(app, defaults={
        "*": aiohttp_cors.ResourceOptions(
            allow_credentials=True,
            expose_headers="*",
            allow_headers="*",
        )
    })

    route = app.router.add_route(
        'POST',
        '/graphql',
        dataloader_middleware,
        GraphQLView(
            schema=schema,
            context={
                'config': app['config'],
                'db': app['mongo_db']
            },
            middleware=[authentication],
            graphiql=True,
            executor=AsyncioExecutor(),
            enable_async=True)
        ,
        name='grqphql')

    cors.add(route)
Ejemplo n.º 8
0
async def gql(request: web.Request) -> web.Response:
    gql_view = GraphQLView(
        schema=schema,
        executor=AsyncioExecutor(loop=asyncio.get_event_loop()),
        context={'tles': parse_useful_tle('active.txt')},
        graphiql=True)

    return await gql_view(request)
Ejemplo n.º 9
0
def GQL(schema, graphiql=False) -> GraphQLView:

    view = GraphQLView(
        schema=schema,
        executor=AsyncioExecutor(loop=asyncio.get_event_loop()),
        graphiql=graphiql,
        enable_async=True,
    )
    return view
Ejemplo n.º 10
0
async def startup(app):
    app['config'] = CONFIG

    app.router.add_route('*',
                         '/graphql',
                         dataloader_middleware,
                         GraphQLView(schema=schema,
                                     context={
                                         'pg_pool': app['pg_pool'],
                                         'mongo_db': app['mongo_db']
                                     },
                                     graphiql=True,
                                     executor=AsyncioExecutor(),
                                     enable_async=True),
                         name='grqphql')
Ejemplo n.º 11
0
def get_view(context: Dict[str, Any], graphiql: bool) -> GraphQLView:
    """
    Получение GraphQl-view
    @param context: контекстный словарь вэб-сессии
    @param graphiql: флаг подключения GraphiQL-клиента
    @return: объект GraphQL-view
    """
    view = GraphQLView(
        schema=schema,
        context=context,
        executor=AsyncioExecutor(),
        graphiql=graphiql,
        enable_async=True
    )

    return view
Ejemplo n.º 12
0
def GQL(graphiql: bool = False) -> GraphQLView:
    '''
    Main view providing access to GraphQl. Modes:

        - Simple GraphQl handler
        - GraphIQL view for interactive work with graph application

    :param graphiql: bool
    :return: GraphQLView
    '''

    gql_view = GraphQLView(
        schema=schema,
        executor=AsyncioExecutor(loop=asyncio.get_event_loop()),
        enable_async=True,
        graphiql=graphiql,
        socket="ws://localhost:8080/subscriptions",
    )
    return gql_view
Ejemplo n.º 13
0
def graph_attach_mod(app: Application,
                     *,
                     route_path='/graphql',
                     route_name='graphql',
                     **kwargs):
    """
    Attach the Graphql view to the input aiohttp app avoiding cors problems

    Args:
        app: app to attach the GraphQL view
        route_path: URI path to the GraphQL view
        route_name: name of the route for the GraphQL view
        **kwargs: GraphQL view initialization arguments

    """
    view = GraphQLView(**kwargs)
    for method in 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD':
        app.router.add_route(method, route_path, view, name=route_name)

    if 'graphiql' in kwargs and kwargs['graphiql']:
        for method in 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD':
            app.router.add_route(method, '/graphiql', view, name='graphiql')
Ejemplo n.º 14
0
    def startWeb(self, loop):

        self.app = web.Application(loop=loop)
        # GraphQLView.attach(app,schema=schema,graphiql=True)
        gql_view = GraphQLView(schema=schema, graphiql=True, executor=AsyncioExecutor(loop=loop), )
        self.app.router.add_route('GET', '/graphql', gql_view, name='graphql')
        post = self.app.router.add_route('POST', '/graphql', gql_view, name='graphql')
        cors = aiohttp_cors.setup(
            self.app,
            defaults={
                "*": aiohttp_cors.ResourceOptions(
                    allow_credentials=True,
                    expose_headers="*",
                    allow_headers="*",
                )
            }
        )
        cors.add(post)
        self.app.add_routes(routes)
        static = self.app.router.add_static("/", os.path.join(application_path, 'dist'), show_index=True)
        static = self.app.router.add_static("/help", os.path.join(application_path, 'kvpac_beremiz', 'dist'),
                                            show_index=True)
        StartCoroutine(web._run_app(self.app, port=65000), self)
Ejemplo n.º 15
0
def app(view_kwargs):
    app = web.Application()
    GraphQLView.attach(app, **view_kwargs)
    return app
Ejemplo n.º 16
0
def app(executor, view_kwargs):
    app = web.Application()
    GraphQLView.attach(app, executor=executor, **view_kwargs)
    return app
Ejemplo n.º 17
0
            'set_articles_read': GraphQLField(
                type=GraphQLInt,
                resolver=set_articles_read_resolver
            )
        }
    )
)


async def enable_cors(_request, response):
    response.headers['Access-Control-Allow-Headers'] = 'content-type'
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS'
    response.headers['Access-Control-Allow-Origin'] = 'http://localhost'
    response.headers['Access-Control-Max-Age'] = '86400'


app = web.Application()

app.on_response_prepare.append(enable_cors)

GraphQLView.attach(
    app,
    schema=schema,
    graphiql=True,
    route_path='/gql',
    executor=AsyncioExecutor(),
    enable_async=True
)

web.run_app(app, port=3081)
Ejemplo n.º 18
0
from aiohttp.web import Application, RouteTableDef, Response
from aiohttp_graphql import GraphQLView
from graphql.execution.executors.asyncio import AsyncioExecutor
from motor.motor_asyncio import AsyncIOMotorClient
import os
from .graphql import graphql_schema
from .model import Model

routes = RouteTableDef()

@routes.get('/')
def index(request):
    return Response(text='Hello World! This is polls_backend.\n')

application = Application()
application.add_routes(routes)
GraphQLView.attach(application, schema=graphql_schema, graphiql=True, executor=AsyncioExecutor())

# example how the full connection (MONGO_URI) string looks like:
# "mongodb+srv://user0:[email protected]/test?retryWrites=true&w=majority"

client = AsyncIOMotorClient(os.environ.get('MONGO_URI') or 'mongodb://127.0.0.1:27017')
db_name = os.environ.get('MONGO_DB_NAME') or 'poll_app'
db = client[db_name]

application['model'] = Model(db)
Ejemplo n.º 19
0
from aiohttp import web
from aiohttp_graphql import GraphQLView
from graphql.execution.executors.asyncio import AsyncioExecutor

from schema import schema

app = web.Application()
GraphQLView.attach(app,
                   schema=schema,
                   executor=AsyncioExecutor(),
                   graphiql=True,
                   pretty=True)

web.run_app(app)
Ejemplo n.º 20
0
def setup_routes(app):
    app.add_routes([
        web.get('/search', search),
    ])
    GraphQLView.attach(app, schema=schema, route_path='/graphql',
                       executor=AsyncioExecutor(asyncio.get_event_loop()))
Ejemplo n.º 21
0
    class Meta:
        model = TestModel
        manager = objects


class AuthorConnection(PeeweeConnection):
    class Meta:
        node = AuthorNode


class Query(ObjectType):
    books = PeeweeConnectionField(AuthorConnection)


schema = graphene.Schema(query=Query,
                         # mutation=Mutations
                         )

gqil_view = GraphQLView(
    schema=schema,
    executor=AsyncioExecutor(loop=asyncio.get_event_loop()),
    graphiql=True,
    enable_async=True,
)

gql_view = GraphQLView(
    schema=schema,
    executor=AsyncioExecutor(loop=asyncio.get_event_loop()),
    graphiql=False,
    enable_async=True,
)
Ejemplo n.º 22
0
def create_app(schema=Schema, **kwargs):
    app = web.Application()
    # Only needed to silence aiohttp deprecation warnings
    GraphQLView.attach(app, schema=schema, **kwargs)
    return app
Ejemplo n.º 23
0
def get_view(graphiql: bool) -> web.View:
    """Get the graphql aiohttp view."""
    return web.view("/graphql", GraphQLView(schema=schema, graphiql=graphiql))
Ejemplo n.º 24
0
    lname = info.get('lname')
    if fname == '' or lname == '':
        #        print("403")
        return web.Response(text="ERROR 403")


#    print("name:  ", fname, "\n")
#    print("lname: ", lname, "\n")
    response = await handler(request)
    return response

app = web.Application(middlewares=[my_first_middl])
app.add_routes([
    web.get('/index', index_handle),
    web.get('/echo', wshandle),
    web.get('/settings', settings_handle),
    web.get('/test', test_handle),
    web.get('/login', login_handle),
    web.post('/verify', verify_handle),
    web.get('/edit', edit_handle)
])

#for route in routes:
#        app.router.add_route(route[0], route[1], route[2])

aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates/'))

GraphQLView.attach(app, schema=AsyncShema, graphiql=True)

web.run_app(app)
Ejemplo n.º 25
0
    full_name = String()


class Queries(graphene.ObjectType):

    person = graphene.Field(Person, input=InputPerson())

    # person = graphene.Field(Person, first_name=graphene.String(), last_name=graphene.NonNull(graphene.String))

    def resolve_person(self, *args, input: InputPerson, **kwargs):
        result = Person()
        result.first_name = input.first_name
        result.last_name = input.last_name
        result.full_name = f"{input.first_name} {input.last_name}"

        return result

    # def resolve_person(self, *args, first_name='', last_name='', **kwargs):
    #     result = Person()
    #     result.first_name = first_name
    #     result.last_name = last_name
    #     result.full_name = f"{first_name} {last_name}"
    #
    #     return result


Schema = Schema(query=Queries)
app = web.Application()

GraphQLView.attach(app, schema=Schema, graphiql=True)
web.run_app(app, port=5002)
async def configure_graphql(app):
    """
    Since our resolvers depend on the app's db connection, this
    co-routine must execute after that part of the application
    is configured
    """
    connection = app['connection']

    class Query(g.ObjectType):

        author = g.Field(Author)
        book = g.Field(Book)

        authors = g.List(
            Author,

            # the following will be passed as named
            # arguments to the resolver function.
            # Don't ask why; it took me forever to
            # figure it out. Despite its functionality,
            # graphene's documentation leaves a lot to be desired
            id=g.Int(),
            first_name=g.String(),
            last_name=g.String(),
            age=g.Int(),
            limit=g.Int(
                description='The amount of results you wish to be limited to'))

        books = g.List(
            Book,
            id=g.Int(),
            title=g.String(),
            published=g.String(),
            author_id=g.Int(
                description='The unique ID of the author in the database'),
            limit=g.Int(
                description='The amount of results you with to be limited to'))

        async def resolve_books(self,
                                info,
                                id=None,
                                title=None,
                                published=None,
                                author_id=None,
                                limit=None):

            query_db = partial(fetch_books,
                               connection,
                               id=id,
                               title=title,
                               published=published,
                               author_id=author_id,
                               limit=limit)

            fetched = await app.loop.run_in_executor(None, query_db)

            books = []

            for book_dict in fetched:

                author = Author(id=book_dict['author']['id'],
                                first_name=book_dict['author']['first_name'],
                                last_name=book_dict['author']['last_name'],
                                age=book_dict['author']['age'])

                book = Book(id=book_dict['id'],
                            title=book_dict['title'],
                            published=book_dict['published'],
                            author=author)

                books.append(book)

            return books

        async def resolve_authors(self,
                                  info,
                                  id=None,
                                  first_name=None,
                                  last_name=None,
                                  age=None,
                                  limit=None):

            query_db = partial(fetch_authors,
                               connection,
                               id=id,
                               first_name=first_name,
                               last_name=last_name,
                               age=age,
                               limit=limit)

            fetched = await app.loop.run_in_executor(None, query_db)

            authors = []

            for author_dict in fetched:

                books = [
                    Book(id=b['id'],
                         title=b['title'],
                         published=b['published'])
                    for b in author_dict['books']
                ]

                author = Author(id=author_dict['id'],
                                first_name=author_dict['first_name'],
                                last_name=author_dict['last_name'],
                                age=author_dict['age'],
                                books=books)

                authors.append(author)

            return authors

    schema = g.Schema(query=Query, auto_camelcase=False)

    # create the view

    executor = AsyncioExecutor(loop=app.loop)

    gql_view = GraphQLView(schema=schema,
                           executor=executor,
                           graphiql=True,
                           enable_async=True)

    # attach the view to the app router

    app.router.add_route(
        '*',
        '/graphql',
        gql_view,
    )
Ejemplo n.º 27
0
from aiohttp_graphql import GraphQLView
from graphql.execution.executors.asyncio import AsyncioExecutor

from .schema import schema

gql_view = GraphQLView(schema=schema,
                       graphiql=True,
                       executor=AsyncioExecutor())
Ejemplo n.º 28
0
from aiohttp_graphql import GraphQLView

from .schema import Schema, AsyncSchema

# pylint: disable=invalid-name
# pylint: disable=protected-access


@pytest.fixture
def view_kwargs():
    return {'schema': Schema}


@pytest.mark.parametrize('view,expected', [
    (GraphQLView(schema=Schema), False),
    (GraphQLView(schema=Schema, executor=SyncExecutor()), False),
    (GraphQLView(schema=Schema, executor=AsyncioExecutor()), True),
])
def test_eval(view, expected):
    assert view.enable_async == expected


@pytest.mark.asyncio
async def test_allows_get_with_query_param(client, url_builder):
    response = await client.get(url_builder(query='{test}'))

    assert response.status == 200
    assert await response.json() == {'data': {'test': "Hello World"}}