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
def test_asyncio_py35_executor_with_error(): ast = parse('query Example { a, b }') async def resolver(context, *_): await asyncio.sleep(0.001) return 'hey' async def resolver_2(context, *_): await asyncio.sleep(0.003) raise Exception('resolver_2 failed!') Type = GraphQLObjectType( 'Type', { 'a': GraphQLField(GraphQLString, resolver=resolver), 'b': GraphQLField(GraphQLString, resolver=resolver_2) }) result = execute(GraphQLSchema(Type), ast, executor=AsyncioExecutor()) formatted_errors = list(map(format_error, result.errors)) assert formatted_errors == [{ 'locations': [{ 'line': 1, 'column': 20 }], 'message': 'resolver_2 failed!' }] assert result.data == {'a': 'hey', 'b': None}
async def do_exec(): result = await execute(GraphQLSchema(Type), ast, executor=AsyncioExecutor(loop), return_promise=True) assert not result.errors assert result.data == {'a': 'hey', 'b': 'hey2', 'c': 'hey3'}
def init_graphql(app, loop): app.add_route( GraphQLCompatibilityWrapper.as_view( schema=schema, executor=AsyncioExecutor(loop=loop), graphiql=False), '/graphql') app.add_route( GraphQLCompatibilityWrapper.as_view( schema=schema, executor=AsyncioExecutor(loop=loop), graphiql=True), '/graphiql') static_path = pkg_resources.resource_filename(__name__, '../crudl/static') app.static('/static', static_path, use_modified_since=configuration.use_modified_since) app.static('/favicon.ico', '{}/favicon.ico'.format(static_path), use_modified_since=configuration.use_modified_since)
async def test_unfollow_newspaper(self): """ Test unfollowing a newspaper unfollows it """ await self.user_service.save(id=2, username='******') await self.user_service.save(id=self.USER_ID, username='******') await self.newspaper_service.save(name=self.TEST_NEWSPAPER, user_id=2) client = Client(schema) executor = AsyncioExecutor() client.execute(self.FOLLOW_NEWSPAPER_MUTATION, variable_values={'name': self.TEST_NEWSPAPER}, context_value={ 'request': MockRequest({'id': self.USER_ID}, self.app) }, executor=executor) with self.session_provider(): newspaper = await self.newspaper_service.read_one( name=self.TEST_NEWSPAPER) self.assertTrue(len(newspaper.follows)) client.execute(self.UNFOLLOW_NEWSPAPER_MUTATION, variable_values={'name': self.TEST_NEWSPAPER}, context_value={ 'request': MockRequest({'id': self.USER_ID}, self.app) }, executor=executor) with self.session_provider(): newspaper = await self.newspaper_service.read_one( name=self.TEST_NEWSPAPER) self.assertFalse(len(newspaper.follows))
async def main(loop): if DSN is None: print('export DATABASE_URL before running this script') return db = await asyncpg.connect(DSN, loop=loop) query = ''' query country { country(iso: "US") { iso name cities { geonameID name } } } ''' result = await graphql(build_schema(), query, executor=AsyncioExecutor(loop=loop), context_value={ 'db': db, 'loaders': { 'Country': CountryLoader(db), 'City': CityLoader(db) } }, return_promise=True) assert result.errors is None print(json.dumps(result.data, sort_keys=True, indent=4))
def test_get_news(self): """ Test the news query queries the news with the specified arguments and returns the results """ async def news_response(): return [self.TEST_NEW, self.TEST_ANOTHER_NEW] self.news_service_mock.get_news_filtered.return_value = news_response() request_mock = Mock(spec=Request) request_mock.user = True client = Client(schema) executed = client.execute( '''{ news(source: "test_source"){ title } }''', context_value=dict(request=request_mock), executor=AsyncioExecutor(loop=asyncio.get_event_loop())) self.news_service_mock.get_news_filtered.assert_called_with( from_date=None, hydration=None, sentiment=(None, True), source='test_source', to_date=None) expected_data = dict(news=[ dict(title=self.TEST_NEW.title), dict(title=self.TEST_ANOTHER_NEW.title) ]) self.assertEqual(executed['data'], expected_data)
def test_get_new_title(self): """ Test the new(title) query queries the new with the specified title and returns it """ async def new_response(): return self.TEST_NEW self.news_service_mock.get_new_by_title.return_value = new_response() request_mock = Mock(spec=Request) request_mock.user = True client = Client(schema) executed = client.execute( '''{ new(title: "test_query_title"){ title } }''', context_value=dict(request=request_mock), executor=AsyncioExecutor(loop=asyncio.get_event_loop())) self.news_service_mock.get_new_by_title.assert_called_with( "test_query_title") expected_data = dict(new=dict(title=self.TEST_NEW.title)) self.assertEqual(executed['data'], expected_data)
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)
def initialize(self, graphiql_template=None, graphiql_version=None, schema=None, middleware=None, graphiql=False, executor=None, root=None, pretty=False, batch=False, context=None): super().initialize(graphiql_template) if not schema: schema = graphene_settings.SCHEMA if middleware is None: middleware = graphene_settings.MIDDLEWARE if middleware is not None: self.middleware = list(instantiate_middleware(middleware)) if not executor: executor = AsyncioExecutor() self.graphiql_version = graphiql_version self.schema = self.schema or schema self.graphiql = self.graphiql or graphiql self.executor = self.executor or executor self.root = root self.pretty = pretty self.batch = batch self.context = context
async def db_handler(request): """Serve GraphQL queries.""" loop = asyncio.get_event_loop() payload = await request.json() query = payload.get("query") variables = payload.get("variables") config = request.app["config"] context = build_context(request, config) # Spawn query as a coroutine using asynchronous executor response = await tangoschema.execute( query, variable_values=variables, context_value=context, return_promise=True, executor=AsyncioExecutor(loop=loop), ) data = {} if response.errors: for e in response.errors: if hasattr(e, "original_error"): if isinstance(e.original_error, AuthError): return web.HTTPUnauthorized() parsed_errors = [ErrorParser.parse(e) for e in (response.errors)] if parsed_errors: data['errors'] = ErrorParser.remove_duplicated_errors( parsed_errors) if response.data: data["data"] = response.data jsondata = json.dumps(data) return web.Response(text=jsondata, headers={"Content-Type": "application/json"})
async def setup(app, loop): app._executor = AsyncioExecutor(loop=loop) async with ArangoAdmin('root', 'arango-pw') as admin: dbs, users = await asyncio.gather(admin.get_dbs(), admin.get_users()) await asyncio.gather( *(admin.create_user(name, pw) for name, pw in app.config.DB_USERS.items() if name not in [usr['user'] for usr in users])) for db_name, cfg in app.config.DATABASES.items(): if db_name not in dbs: await admin.create_db(db_name) await asyncio.gather( *(admin.set_access_level(name, db_name, level=grants[role]) for role, name in cfg['users'].items()), *(admin.set_access_level(name, db_name, level='none') for name in app.config.DB_USERS.keys() if name not in cfg['users'].values())) app.gq_db = ArangoDB('user', 'user-pw', 'public') await app.gq_db.login() app.add_route( GraphQLView.as_view(schema=await schema.setup(app.gq_db), context={ 'db': app.gq_db, 'cache': {} }, batch=True, executor=app._executor, graphiql=True), 'graphql')
async def get(self): """GraphQL GET - запрос данных. http://graphql.org/learn/serving-over-http/#get-request http://graphql.org/learn/queries/#arguments """ client_redis = self.settings.get("client_redis") client_motor = self.settings.get("client_motor") request = self.get_bytes_body_source() query = request.get("query", "") operation_name = request.get("operationName", "") variables = request.get("variables", {}) result = main_schema.execute( request_string=query, operation_name=operation_name, variable_values=variables, executor=AsyncioExecutor(), return_promise=True, context_value={ "current_user": self.current_user, "client_redis": client_redis, "client_motor": client_motor, }, ) if not isinstance(result, graphql.execution.base.ExecutionResult): result = await result raise Response(result)
def test_asyncio_py35_executor_with_error(): ast = parse("query Example { a, b }") async def resolver(context, *_): await asyncio.sleep(0.001) return "hey" async def resolver_2(context, *_): await asyncio.sleep(0.003) raise Exception("resolver_2 failed!") Type = GraphQLObjectType( "Type", { "a": GraphQLField(GraphQLString, resolver=resolver), "b": GraphQLField(GraphQLString, resolver=resolver_2), }, ) result = execute(GraphQLSchema(Type), ast, executor=AsyncioExecutor()) formatted_errors = list(map(format_error, result.errors)) assert formatted_errors == [{ "locations": [{ "line": 1, "column": 20 }], "path": ["b"], "message": "resolver_2 failed!", }] assert result.data == {"a": "hey", "b": None}
def setup_graphql_routes(app: Application, schema: Schema, logger: Logger, middlewares: List[object] = None): """ Add the graphql routes to the specified application Args: app: application to add routes schema: graphene schema which describes the graphql queries and mutations logger: logger instance used by the different graphene utilities functions middlewares: list of graphql middleware functions """ if not middlewares: middlewares = list() graph_attach_mod(app, route_path='/graphql', schema=schema, graphiql=True, graphiql_template=GRAPHIQL_JWT_TEMPLATE, executor=AsyncioExecutor(loop=asyncio.get_event_loop()), enable_async=True, error_formatter=partial(error_formatter, logger=logger), middleware=middlewares)
async def test_delete_new_like(self): """ Test deleting a new like deletes it """ await self.source_service.save(name='test_source') await self.user_service.save(id=self.USER_ID, username='******') await self.new_service.save(title=self.TEST_NEW, url='test_url', sentiment=0.0, source_id=1) client = Client(schema) executor = AsyncioExecutor() client.execute(self.LIKE_NEW_MUTATION, variable_values={'title': self.TEST_NEW}, context_value={ 'request': MockRequest({'id': self.USER_ID}, self.app) }, executor=executor) with self.session_provider(): new = await self.new_service.read_one(title=self.TEST_NEW) self.assertTrue(len(new.likes)) client.execute(self.DELETE_LIKE_MUTATION, variable_values={'title': self.TEST_NEW}, context_value={ 'request': MockRequest({'id': self.USER_ID}, self.app) }, executor=executor) with self.session_provider(): new = await self.new_service.read_one(title=self.TEST_NEW) self.assertFalse(len(new.likes))
def get_graphql_params(self, *args, **kwargs): params = super(AiohttpSubscriptionServer, self).get_graphql_params( *args, **kwargs ) return dict( params, return_promise=True, executor=AsyncioExecutor(loop=self.loop) )
async def test_unfollow_source(self): """ Test unfollowing a source unfollows it """ await self.source_service.save(name=self.TEST_SOURCE) await self.user_service.save(id=self.USER_ID, username='******') client = Client(schema) executor = AsyncioExecutor() client.execute(self.FOLLOW_SOURCE_MUTATION, variable_values={ 'name': self.TEST_SOURCE }, context_value={'request': MockRequest({'id': self.USER_ID}, self.app)}, executor=executor) with self.session_provider(): source = await self.source_service.read_one(name=self.TEST_SOURCE) self.assertTrue(len(source.follows)) client.execute(self.UNFOLLOW_SOURCE_MUTATION, variable_values={ 'name': self.TEST_SOURCE }, context_value={'request': MockRequest({'id': self.USER_ID}, self.app)}, executor=executor) with self.session_provider(): source = await self.source_service.read_one(name=self.TEST_SOURCE) self.assertFalse(len(source.follows))
async def execute_graphql(self): # Executa a request GraphQL graphql_req = await self.graphql_request logging.debug('graphql request: %s', graphql_req) context_value = graphql_req.get('context', {}) variables = graphql_req.get('variables', {}) context_value['application'] = self.app executor = AsyncioExecutor(loop=asyncio.get_event_loop()) result = await self.schema.execute( graphql_req['query'], executor=executor, return_promise=True, context_value=context_value, variable_values=variables, ) ref = self.request.headers.get('referer') url_path = '' if ref: url = urllib.parse.urlparse(ref) url_path = url.path if result.invalid or result.errors: if '/graphiql' not in url_path: aiohttp.log.server_logger.error( f'Graphql query error: for query "{graphql_req}"') return result
def test_asyncio_py35_executor(): ast = parse("query Example { a, b, c }") async def resolver(context, *_): await asyncio.sleep(0.001) return "hey" async def resolver_2(context, *_): await asyncio.sleep(0.003) return "hey2" def resolver_3(context, *_): return "hey3" Type = GraphQLObjectType( "Type", { "a": GraphQLField(GraphQLString, resolver=resolver), "b": GraphQLField(GraphQLString, resolver=resolver_2), "c": GraphQLField(GraphQLString, resolver=resolver_3), }, ) result = execute(GraphQLSchema(Type), ast, executor=AsyncioExecutor()) assert not result.errors assert result.data == {"a": "hey", "b": "hey2", "c": "hey3"}
def create_app(api_key=None): logging.basicConfig(level=logging.DEBUG) if api_key == None and API_KEY_ENV_VAR in os.environ: logging.getLogger().debug(f'Picked GoodReads API key from environment variable `{API_KEY_ENV_VAR}`.') api_key = os.environ[API_KEY_ENV_VAR] if api_key == None: raise KeyError(f'The GoodReads API key should either be supplied via command line param `-k` or via the environment variable `{API_KEY_ENV_VAR}`. Please get one from https://www.goodreads.com/api.') api = GoodReadsXMLApi(api_key) loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) app = Flask(__name__) app.add_url_rule( '/graphql', view_func=GraphQLView.as_view( 'graphql', executor=AsyncioExecutor(loop=loop), schema=schema, graphiql=True, get_context=lambda: { 'author_loader': data_loaded(fn=api.get_author, loop=loop), 'book_loader': data_loaded(fn=api.get_book, loop=loop) } ) ) return app
async def get(self): """Обработчик запроса по методу GET.""" graphql = self.get_argument(name="graphql") # result = schema.execute(graphql, executor=AsyncioExecutor()) result = await schema.execute(request_string=graphql, executor=AsyncioExecutor(), return_promise=True) raise utils.exceptions.Response(result)
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)
async def init_graphql(app, loop): schema = build_schema() app.add_route(GraphQLView.as_view(schema=schema, executor=AsyncioExecutor(loop=loop), graphiql=True), '/graphql', methods=['POST', 'OPTIONS'])
async def test_node_query_promise(): executed = await schema.execute( 'mutation a { sayPromise(input: {what:"hello", clientMutationId:"1"}) { phrase } }', executor=AsyncioExecutor(), return_promise=True, ) assert not executed.errors assert executed.data == {"sayPromise": {"phrase": "hello"}}
def init_graphql_view(): # pylint: disable=unused-variable """Initiate graphql""" this.graphql_view = GraphQLView.as_view( schema=ax_schema.schema, graphiql=False, enable_async=True, executor=AsyncioExecutor(loop=this.loop)) this.app.add_route(this.graphql_view, '/api/graphql')
async def init(app): loop = asyncio.get_event_loop() app['admin.gql_executor'] = AsyncioExecutor(loop=loop) app['admin.gql_schema_admin'] = graphene.Schema(query=QueryForAdmin, mutation=MutationForAdmin, auto_camelcase=False) app['admin.gql_schema_user'] = graphene.Schema(query=QueryForUser, mutation=None, auto_camelcase=False)
def test_main_graphql(snapshot, graphql_client): """ This will create a snapshot dir and a snapshot file the first time the test is executed, with the response of the execution. """ executed = graphql_client.execute("""{ hello(name: "Archie") }""", executor=AsyncioExecutor()) snapshot.assert_match(executed)
def get_graphql_params(self, connection_context, payload): params = { "request_string": payload.get("query"), "variable_values": payload.get("variables"), "operation_name": payload.get("operationName"), "context_value": connection_context.request_context, } return dict(params, return_promise=True, executor=AsyncioExecutor())
async def do_exec(): result = await execute( GraphQLSchema(Type), ast, executor=AsyncioExecutor(loop), return_promise=True, ) assert not result.errors assert result.data == {"a": "hey", "b": "hey2", "c": "hey3"}
def on_start(self, op_id, params): try: executor = AsyncioExecutor(loop=asyncio.get_event_loop()) old_execute = executor.execute def execute(*args, **kwargs): try: return old_execute(*args, **kwargs) except Exception as e: exc_info = sys.exc_info() from tornado.options import options as opts print_graphql_exception(e) self.log.error(f"Exception: {exc_info}") raise exc_info[1] executor.execute = execute execution_result = graphql( self.schema, **params, allow_subscriptions=True, context=self.context, executor=executor ) if not isinstance(execution_result, Observable): execution_info = json.dumps({ 'data' : execution_result.data, 'errors' : [str(error) for error in execution_result.errors] }) app_log.error(f"GraphQL error: GraphQL execution result returned {execution_info}. Expected: Observable") raise ValueError(f"A subscription must return an observable. Got: {execution_info}") subscription = execution_result.subscribe(SubscriptionObserver( op_id, self.send_execution_result, self.send_error, self.on_close ) ) self.subscribe(op_id, subscription) except Exception as e: self.send_error(op_id, str(e))