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
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)
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)
def GQL(schema, graphiql=False) -> GraphQLView: view = GraphQLView( schema=schema, executor=AsyncioExecutor(loop=asyncio.get_event_loop()), graphiql=graphiql, enable_async=True, ) return view
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')
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
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
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')
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)
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, )
def get_view(graphiql: bool) -> web.View: """Get the graphql aiohttp view.""" return web.view("/graphql", GraphQLView(schema=schema, graphiql=graphiql))
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"}}
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, )
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())